Honza 5 anni fa
commit
9945c98759
100 ha cambiato i file con 8859 aggiunte e 0 eliminazioni
  1. 2317 0
      Atlas.py
  2. 50 0
      Atlas_dockwidget.py
  3. 51 0
      Atlas_dockwidget_base.ui
  4. 244 0
      Makefile
  5. 42 0
      README.html
  6. 32 0
      README.md
  7. 32 0
      README.txt
  8. 36 0
      __init__.py
  9. BIN
      __pycache__/Atlas.cpython-37.pyc
  10. BIN
      __pycache__/Atlas_dockwidget.cpython-37.pyc
  11. BIN
      __pycache__/__init__.cpython-37.pyc
  12. BIN
      __pycache__/dlg_ConnectionManager.cpython-37.pyc
  13. BIN
      __pycache__/dlg_GetLayers.cpython-37.pyc
  14. BIN
      __pycache__/dlg_addLayer.cpython-37.pyc
  15. BIN
      __pycache__/dlg_addMap.cpython-37.pyc
  16. BIN
      __pycache__/dlg_createComposite.cpython-37.pyc
  17. BIN
      __pycache__/dlg_deleteLayerFromMap.cpython-37.pyc
  18. BIN
      __pycache__/dlg_deleteMap.cpython-37.pyc
  19. BIN
      __pycache__/dlg_editMap.cpython-37.pyc
  20. BIN
      __pycache__/dlg_importLayer.cpython-37.pyc
  21. BIN
      __pycache__/dlg_importMap.cpython-37.pyc
  22. BIN
      __pycache__/dlg_userInfo.cpython-37.pyc
  23. BIN
      __pycache__/flaskServer.cpython-37.pyc
  24. BIN
      __pycache__/flaskServer2.cpython-37.pyc
  25. BIN
      __pycache__/ogr2ogr.cpython-37.pyc
  26. BIN
      __pycache__/resources.cpython-37.pyc
  27. 44 0
      dlg_ConnectionManager.py
  28. 150 0
      dlg_ConnectionManager.ui
  29. 44 0
      dlg_GetLayers.py
  30. 94 0
      dlg_GetLayers.ui
  31. 44 0
      dlg_addLayer.py
  32. 149 0
      dlg_addLayer.ui
  33. 44 0
      dlg_addMap.py
  34. 136 0
      dlg_addMap.ui
  35. 44 0
      dlg_createComposite.py
  36. 306 0
      dlg_createComposite.ui
  37. 44 0
      dlg_deleteLayerFromMap.py
  38. 120 0
      dlg_deleteLayerFromMap.ui
  39. 44 0
      dlg_deleteMap.py
  40. 60 0
      dlg_deleteMap.ui
  41. 44 0
      dlg_editMap.py
  42. 216 0
      dlg_editMap.ui
  43. 44 0
      dlg_importLayer.py
  44. 102 0
      dlg_importLayer.ui
  45. 44 0
      dlg_importMap.py
  46. 413 0
      dlg_importMap.ui
  47. 44 0
      dlg_userInfo.py
  48. 74 0
      dlg_userInfo.ui
  49. 94 0
      flaskServer.py
  50. 72 0
      flaskServer2.py
  51. BIN
      flask_listener/__pycache__/flask.cpython-37.pyc
  52. 36 0
      flask_listener/flask_listener.py
  53. 130 0
      help/Makefile
  54. 155 0
      help/make.bat
  55. 216 0
      help/source/conf.py
  56. 20 0
      help/source/index.rst
  57. 11 0
      i18n/af.ts
  58. BIN
      icon.png
  59. 13 0
      icons/account.svg
  60. BIN
      icons/cloud.png
  61. BIN
      icons/delete.png
  62. BIN
      icons/download_map.png
  63. BIN
      icons/edit.png
  64. BIN
      icons/file.png
  65. BIN
      icons/globus.png
  66. BIN
      icons/layers-down.png
  67. BIN
      icons/layers-up.png
  68. BIN
      icons/load.png
  69. BIN
      icons/login.png
  70. BIN
      icons/minus.png
  71. BIN
      icons/plus.png
  72. BIN
      icons/save.png
  73. BIN
      icons/upload-map.png
  74. BIN
      icons/upload.png
  75. 6 0
      install_windows/install.bat
  76. 7 0
      install_windows/install_packages.bat
  77. 2 0
      install_windows/readme.txt
  78. 39 0
      metadata.txt
  79. 1696 0
      ogr2ogr.py
  80. 80 0
      pb_tool.cfg
  81. 111 0
      plugin_upload.py
  82. 281 0
      pylintrc
  83. 128 0
      resources.py
  84. 5 0
      resources.qrc
  85. 12 0
      scripts/compile-strings.sh
  86. 28 0
      scripts/run-env-linux.sh
  87. 56 0
      scripts/update-strings.sh
  88. 2 0
      test/__init__.py
  89. 205 0
      test/qgis_interface.py
  90. 19 0
      test/tenbytenraster.asc
  91. 13 0
      test/tenbytenraster.asc.aux.xml
  92. 1 0
      test/tenbytenraster.keywords
  93. 18 0
      test/tenbytenraster.lic
  94. 1 0
      test/tenbytenraster.prj
  95. 26 0
      test/tenbytenraster.qml
  96. 45 0
      test/test_Atlas_dockwidget.py
  97. 64 0
      test/test_init.py
  98. 60 0
      test/test_qgis_environment.py
  99. 44 0
      test/test_resources.py
  100. 55 0
      test/test_translations.py

+ 2317 - 0
Atlas.py

@@ -0,0 +1,2317 @@
+ # -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ Atlas
+                                 A QGIS plugin
+ Atlas
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                              -------------------
+        begin                : 2019-02-15
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by jan vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt, QFileSystemWatcher, QRegExp,QDir
+from PyQt5.QtGui import QIcon, QPixmap, QRegExpValidator, QDoubleValidator
+from PyQt5.QtWidgets import QAction, QTreeWidget, QTreeWidgetItem, QMessageBox, QLabel, QProgressDialog, QDialog, QProgressBar,QListWidgetItem
+# Initialize Qt resources from file resources.py
+from .resources import *
+import re
+#from .flaskServer import *
+from multiprocessing import Process
+from pathlib import Path 
+# Import the code for the DockWidget
+from builtins import str
+from builtins import range
+from builtins import object
+import json
+import zipfile
+import tempfile
+import configparser
+import shutil
+import uuid
+import copy
+import webbrowser
+from .Atlas_dockwidget import AtlasDockWidget
+import os.path
+import tempfile
+import qgis.core
+from qgis.core import *
+import platform
+import os
+import qgis.utils
+import qgis.gui
+from qgis.gui import QgsMapCanvas
+from qgis.core import QgsApplication
+from qgis.utils import iface
+from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QWidget, QInputDialog, QLineEdit, QFileDialog
+import requests
+import tempfile
+import time
+from urllib.request import urlopen
+import subprocess
+import threading
+#from flask import Flask, request, jsonify
+import base64
+import hashlib
+import html
+import re
+import urllib.parse
+from .ogr2ogr import main
+## forms
+from .dlg_GetLayers import GetLayersDialog
+from .dlg_importMap import ImportMapDialog
+from .dlg_deleteMap import DeleteMapDialog
+from .dlg_importLayer import ImportLayerDialog
+from .dlg_addLayer import AddLayerDialog
+from .dlg_addMap import AddMapDialog
+from .dlg_createComposite import CreateCompositeDialog
+from .dlg_deleteLayerFromMap import DeleteLayerFromMapDialog
+from .dlg_editMap import EditMapDialog
+from .dlg_ConnectionManager import ConnectionManagerDialog
+from .dlg_userInfo import UserInfoDialog
+
+
+
+class Atlas:
+    """QGIS Plugin Implementation."""
+
+    def __init__(self, iface):
+        """Constructor.
+        
+        :param iface: An interface instance that will be passed to this class
+            which provides the hook by which you can manipulate the QGIS
+            application at run time.
+        :type iface: QgsInterface
+        """
+        # Save reference to the QGIS interface
+        self.iface = iface
+
+        # initialize plugin directory
+        self.plugin_dir = os.path.dirname(__file__) 
+        
+        ## init global variables
+      #  global filename 
+        self.client_id = None
+        self.filename = None
+        self.layerName = None
+        self.username = 'browser'
+        self.EPSG = 'EPSG:3857'
+        self.composite = None
+        self.thread1 = None
+        self.compositeList = []
+        self.compositeListOld = []
+        self.CHUNK_SIZE = 1048576 ## s touto hodnotou pracuje layman klient (cca 1MB soubor)
+        self.URI = "http://layman.lesprojekt.cz"
+        self.access_token = None
+        self.expires_in = None
+        self.refresh_token = None
+        self.laymanUsername = ""
+        self.authHeader = None
+        self.code_verifier = None
+        self.code_challenge = None
+        self.Agrimail = None
+        self.loadedInMemory = False
+        self.uri = 'http://layman.lesprojekt.cz/rest/'
+     #   global dlgGetLayers 
+        self.dlgGetLayers= GetLayersDialog()
+        # initialize locale
+        locale = QSettings().value('locale/userLocale')[0:2]
+        locale_path = os.path.join(
+            self.plugin_dir,
+            'i18n',
+            'Atlas_{}.qm'.format(locale))
+
+        if os.path.exists(locale_path):
+            self.translator = QTranslator()
+            self.translator.load(locale_path)
+
+            if qVersion() > '4.3.3':
+                QCoreApplication.installTranslator(self.translator)
+
+        # Declare instance attributes
+        self.actions = []
+        self.menu = self.tr(u'&Layman')
+        # TODO: We are going to let the user set this up in a future iteration
+        self.toolbar = self.iface.addToolBar(u'Layman')
+        self.toolbar.setObjectName(u'Layman')
+
+        #print "** INITIALIZING Atlas"
+
+        self.pluginIsActive = False
+        self.dockwidget = None
+        ## prepare temp dir
+        tempDir = tempfile.gettempdir() + os.sep + "atlas" 
+        try:
+            os.mkdir(tempDir)
+            print("Directory " , tempDir ,  " Created ") 
+        except FileExistsError:
+            print("Directory " , tempDir ,  " already exists")
+
+
+    # noinspection PyMethodMayBeStatic
+    def tr(self, message):
+        """Get the translation for a string using Qt translation API.
+
+        We implement this ourselves since we do not inherit QObject.
+
+        :param message: String for translation.
+        :type message: str, QString
+
+        :returns: Translated version of message.
+        :rtype: QString
+        """
+        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
+        return QCoreApplication.translate('Layman', message)
+
+
+    def add_action(
+        self,
+        icon_path,
+        text,
+        callback,
+        enabled_flag=True,
+        add_to_menu=True,
+        add_to_toolbar=True,
+        status_tip=None,
+        whats_this=None,
+        parent=None):
+        
+
+        icon = QIcon(icon_path)
+        action = QAction(icon, text, parent)
+        action.triggered.connect(callback)
+        action.setEnabled(enabled_flag)
+
+        if status_tip is not None:
+            action.setStatusTip(status_tip)
+
+        if whats_this is not None:
+            action.setWhatsThis(whats_this)
+
+        if add_to_toolbar:
+            self.toolbar.addAction(action)
+
+        if add_to_menu:
+            self.iface.addPluginToMenu(
+                self.menu,
+                action)
+
+        self.actions.append(action)
+
+        return action
+
+
+    def initGui(self):
+        """Create the menu entries and toolbar icons inside the QGIS GUI."""
+
+        #icon_path = ':/plugins/Atlas/icon.png'
+        #self.add_action(
+        #    icon_path,
+        #    text=self.tr(u''),
+        #    callback=self.run,
+        #    parent=self.iface.mainWindow())
+        #self.first_start = True
+
+        ################## user
+        self.textbox = QLabel(self.iface.mainWindow())
+        # Set width
+        self.textbox.setFixedWidth(140)
+        # Add textbox to toolbar
+        self.txtAction = self.toolbar.addWidget(self.textbox)
+        # Set tooltip
+        self.txtAction.setToolTip(self.tr(u'Current Row Number'))
+        # Set callback
+        self.textbox.setText("Layman")
+
+        ################ end usericon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'login.png'
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'login.png'
+        self.menu_Connection = self.add_action(
+            icon_path,
+            text=self.tr(u'Login'),
+            callback=self.run_login,
+            enabled_flag=True,
+            parent=self.iface.mainWindow())
+
+
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'save.png'
+        self.menu_saveLocalFile = self.add_action(
+            icon_path,
+            text=self.tr(u'Save as to JSON and SLD'),
+            callback=self.saveLocalFile,
+            enabled_flag=False,
+            parent=self.iface.mainWindow())
+
+        self.first_start = True
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'file.png'
+        self.menu_loadJson = self.add_action(
+            icon_path,
+            text=self.tr(u'Load from JSON'),
+            callback=self.loadLocalFile,
+            enabled_flag=False,
+            parent=self.iface.mainWindow())
+        self.first_start = True
+
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'layers-up.png'
+        self.menu_ImportLayerDialog = self.add_action(
+            icon_path,
+            text=self.tr(u'Export layer to server'),
+            callback=self.run_ImportLayerDialog,
+            enabled_flag=False,
+            parent=self.iface.mainWindow())  
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'layers-down.png'
+        self.menu_AddLayerDialog = self.add_action(
+            icon_path,
+            text=self.tr(u'Load layer from server'),
+            callback=self.run_AddLayerDialog,
+            enabled_flag=False,
+            parent=self.iface.mainWindow()) 
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'upload-map.png'
+        self.menu_ImportMapDialog = self.add_action(
+            icon_path,
+            text=self.tr(u'Manage maps'),
+            callback=self.run_ImportMapDialog,
+            enabled_flag=False,
+            parent=self.iface.mainWindow())  
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'download_map.png'
+        self.menu_AddMapDialog = self.add_action(
+            icon_path,
+            text=self.tr(u'Load map from server'),
+            callback=self.run_AddMapDialog,
+            enabled_flag=False,
+            parent=self.iface.mainWindow())   
+        
+        #icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'delete.png'
+        #self.menu_DeleteMapDialog = self.add_action(
+        #    icon_path,
+        #    text=self.tr(u'Delete map'),
+        #    callback=self.run_DeleteMapDialog,
+        #    enabled_flag=False,
+        #    parent=self.iface.mainWindow())  
+        #icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'globus.png'
+        #self.menu_CreateCompositeDialog = self.add_action(
+        #    icon_path,
+        #    text=self.tr(u'Create map'),
+        #    callback=self.run_CreateCompositeDialog,
+        #    enabled_flag=False,
+        #    parent=self.iface.mainWindow())
+        icon_path = self.plugin_dir + os.sep + 'icons' + os.sep + 'account.svg'
+        self.menu_UserInfoDialog = self.add_action(
+            icon_path,
+            text=self.tr(u'User info'),
+            callback=self.run_UserInfoDialog,
+            enabled_flag=False,
+            parent=self.iface.mainWindow())
+    #--------------------------------------------------------------------------
+    def run_UserInfoDialog(self):
+        self.dlg = UserInfoDialog() 
+        self.dlg.show()
+        userEndpoint = "http://layman.lesprojekt.cz/rest/current-user"
+        r = requests.get(url = userEndpoint,  headers = self.authHeader)
+        res = r.text
+        res = self.fromByteToJson(r.content)
+        print(res['claims'])
+        self.dlg.label_layman.setText(res['claims']['preferred_username'])
+        self.dlg.label_agrihub.setText(res['claims']['email'])
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+
+    def run_EditMap(self, x):
+        self.dlg = EditMapDialog()      
+        self.dlg.pushButton_save.setStyleSheet("#pushButton_save {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_save:hover{background: #66ab27 ;}#pushButton_save:disabled{background: #64818b ;}")
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+        
+       
+        self.dlg.lineEdit_name.hide()
+        self.dlg.label_2.hide()
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        self.dlg.lineEdit_name.setText(self.compositeList[x]['name'])
+        self.dlg.lineEdit_abstract.setText(self.compositeList[x]['abstract'])
+        self.dlg.lineEdit_title.setText(self.compositeList[x]['title'])
+        self.dlg.lineEdit_units.setText(self.compositeList[x]['units'])
+        self.dlg.lineEdit_scale.setText(str(self.compositeList[x]['scale']))
+        self.dlg.lineEdit_user.setText(self.compositeList[x]['user']['name'])
+        self.dlg.rejected.connect(lambda: self.afterCloseEditMapDialog()) 
+        self.dlg.pushButton_save.clicked.connect(lambda: self.modifyMap(x))
+        self.dlg.rejected.connect(lambda: self.afterCloseCompositeDialog())
+        self.dlg.show()
+        result = self.dlg.exec_()
+
+    def run_DeleteLayerFromMap(self):
+        self.dlg = DeleteLayerFromMapDialog()
+        self.dlg.pushButton.clicked.connect(lambda: self.deteteLayerFromComposite(self.dlg.listWidget.currentRow(),self.compositeList[self.dlg.listWidget.currentRow()]['layers'][self.dlg.listWidget_listLayers2.currentRow()]['params']['LAYERS']))
+        #self.dlg.pushButton.clicked.connect(lambda: print(self.dlg.listWidget_2.currentRow()))
+       
+        layers = QgsProject.instance().mapLayers().values()
+        
+        for i in range (0, len(self.compositeList)):
+            self.dlg.listWidget.addItem(self.compositeList[i]['name'])
+       # self.dlg.pushButton.setEnabled(False)
+        self.dlg.listWidget.itemClicked.connect(self.listCompositeLayers)
+        self.dlg.listWidget_listLayers2.itemClicked.connect(self.showThumbnail)   
+        
+
+       # self.dlg.listWidget_listMaps.itemClicked.connect(self.enableButton)    
+        self.dlg.show()
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        result = self.dlg.exec_()
+
+    def run_CreateCompositeDialog(self, fromImport = False):
+        self.dlg = CreateCompositeDialog()
+        self.dlg.label_info.hide()
+        self.dlg.label_2.hide()
+        self.dlg.lineEdit.hide()
+        self.dlg.pushButton_CreateComposition.clicked.connect(lambda: self.createComposite(self.dlg.lineEdit.text(),self.dlg.lineEdit_2.text()))              
+        layers = QgsProject.instance().mapLayers().values()
+        self.dlg.treeWidget.itemClicked.connect(self.setExtent)
+        for layer in layers:
+           # self.dlg.listWidget_listLayers.addItem(layer.name())
+            if (layer.type() == QgsMapLayer.VectorLayer):
+                item = QTreeWidgetItem([layer.name()]) 
+            
+                    
+                self.dlg.treeWidget.addTopLevelItem(item)
+        ext = iface.mapCanvas().extent()
+        self.dlg.lineEdit.setValidator(QRegExpValidator(QRegExp("[a-z]{1}[a-z0-9]{1,30}")))      
+        self.dlg.lineEdit_2.editingFinished.connect(self.checkNameCreateMap)
+        self.dlg.lineEdit_3.setText(str(ext.xMinimum()))
+        self.dlg.lineEdit_4.setText(str(ext.xMaximum()))
+        self.dlg.lineEdit_5.setText(str(ext.yMinimum()))
+        self.dlg.lineEdit_6.setText(str(ext.yMaximum()))
+        self.dlg.pushButton_defaultExtent.clicked.connect(lambda: self.setDefaultExtent(ext))              
+        self.dlg.pushButton_defaultExtent.setStyleSheet("#pushButton_defaultExtent {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_defaultExtent:hover{background: #66ab27 ;}#pushButton_defaultExtent:disabled{background: #64818b ;}")
+        self.dlg.pushButton_CreateComposition.setStyleSheet("#pushButton_CreateComposition {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_CreateComposition:hover{background: #66ab27 ;}#pushButton_CreateComposition:disabled{background: #64818b ;}")
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+
+        self.dlg.show()
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        if (fromImport):
+            self.dlg.rejected.connect(lambda: self.afterCloseCompositeDialog())
+        result = self.dlg.exec_()
+
+
+    def run_ImportMapDialog(self):
+        self.dlg = ImportMapDialog()
+        self.dlg.label_import.hide()
+        #self.dlg.listWidget_listLayers2.hide()
+        self.dlg.pushButton_deleteMap.setEnabled(False)
+        self.dlg.pushButton_editMeta.setEnabled(False)
+        self.dlg.pushButton_addRaster.setEnabled(False)
+        self.dlg.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.VectorLayer)
+        self.dlg.pushButton.clicked.connect(lambda: self.addLayerToComposite(self.dlg.listWidget.currentRow()))   
+        self.dlg.pushButton_deleteMap.clicked.connect(lambda: self.deleteMap(self.dlg.listWidget.currentItem().text(),self.dlg.listWidget.currentRow()))
+       # self.dlg.pushButton_deleteMap.clicked.connect(lambda: self.deleteMapFromCanvas(self.dlg.listWidget.currentRow())) 
+        self.dlg.pushButton_up.clicked.connect(lambda: self.reorderLayers(self.dlg.listWidget_listLayers.currentRow(), 1, self.dlg.listWidget.currentRow()))
+        self.dlg.pushButton_down.clicked.connect(lambda: self.reorderLayers(self.dlg.listWidget_listLayers.currentRow(), -1, self.dlg.listWidget.currentRow()))
+
+
+        if not self.loadedInMemory:
+            self.loadAllComposites()
+        self.dlg.pushButton_addMap.clicked.connect(lambda: self.showAddMapDialog())
+        layers = QgsProject.instance().mapLayers().values()     
+        for i in range (0, len(self.compositeList)):
+            print(self.compositeList[i])
+            #self.dlg.listWidget.addItem(self.compositeList[i]['name'])
+            self.dlg.listWidget.addItem(self.compositeList[i]['title'])
+        self.dlg.progressBar.hide()            
+        self.dlg.pushButton.setIcon(QIcon(self.plugin_dir + os.sep + 'icons' + os.sep + 'plus.png'))
+        self.dlg.pushButton_addMap.setIcon(QIcon(self.plugin_dir + os.sep + 'icons' + os.sep + 'plus.png'))
+        self.dlg.pushButton_addRaster.setIcon(QIcon(self.plugin_dir + os.sep + 'icons' + os.sep + 'plus.png'))
+        self.dlg.pushButton_deleteLayers.setIcon(QIcon(self.plugin_dir + os.sep + 'icons' + os.sep + 'minus.png'))
+        self.dlg.pushButton_deleteMap.setIcon(QIcon(self.plugin_dir + os.sep + 'icons' + os.sep + 'minus.png'))
+        self.dlg.pushButton_editMeta.setIcon(QIcon(self.plugin_dir + os.sep + 'icons' + os.sep + 'edit.png'))
+        self.dlg.listWidget.itemClicked.connect(self.refreshLayerList)
+        self.dlg.listWidget.itemClicked.connect(lambda: self.dlg.pushButton_deleteMap.setEnabled(True))
+        self.dlg.listWidget.itemClicked.connect(lambda: self.dlg.pushButton_editMeta.setEnabled(True))
+        self.dlg.listWidget.itemClicked.connect(lambda: self.dlg.pushButton_addRaster.setEnabled(True))
+        self.dlg.listWidget_listLayers.itemClicked.connect(lambda: self.dlg.pushButton_down.setEnabled(True))
+        self.dlg.listWidget_listLayers.itemClicked.connect(lambda: self.dlg.pushButton_up.setEnabled(True))
+        
+       
+        self.dlg.pushButton_editMeta.clicked.connect(lambda: self.showEditMapDialog(self.dlg.listWidget.currentRow()))
+     ###########nacitam vrstvy z laymana do comboboxu
+        url = self.URI+'/rest/'+self.laymanUsername+'/layers'
+        r = requests.get(url = url)
+       # print(r.content())
+        data = r.json()             
+        for row in range(0, len(data)):          
+            self.dlg.comboBox_raster.addItem(data[row]['name'])
+
+        self.dlg.pushButton_addRaster.clicked.connect(lambda: self.addExistingLayerToComposite(self.dlg.comboBox_raster.currentText()))
+        #### nahrát mapy ze serveru do comboboxu
+        url = self.URI+'/rest/'+self.laymanUsername+'/maps'
+        r = requests.get(url = url)
+        data = r.json()
+        for row in range(0, len(data)):            
+            self.dlg.comboBox_loadMap.addItem(data[row]['name'])
+      
+        self.dlg.pushButton_loadMap.clicked.connect(lambda: self.readMapJson(self.dlg.comboBox_loadMap.currentText(), 'WMS'))
+        self.dlg.pushButton_loadMapWFS.clicked.connect(lambda: self.readMapJson(self.dlg.comboBox_loadMap.currentText(), 'WFS'))
+        self.dlg.pushButton_loadMapWFS.hide()
+        self.dlg.pushButton_loadMap.hide()
+        self.dlg.comboBox_loadMap.hide()
+     #############
+        self.dlg.pushButton.setEnabled(False)
+        self.dlg.pushButton_deleteLayers.setEnabled(False)
+        self.dlg.listWidget_listLayers.itemClicked.connect(self.showSmallThumbnail)
+      #  self.dlg.listWidget_listLayers.itemClicked.connect(self.showThumbnail)
+        self.dlg.listWidget.itemClicked.connect(self.enableButton)          
+        self.dlg.pushButton_deleteLayers.clicked.connect(lambda: self.deteteLayerFromComposite(self.dlg.listWidget.currentRow(),self.dlg.listWidget_listLayers.currentRow(), self.dlg.listWidget_listLayers.currentItem().text()))    
+        self.dlg.show()
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+
+        self.dlg.pushButton_down.setStyleSheet("#pushButton_down {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_down:hover{background: #66ab27 ;}#pushButton_down:disabled{background: #64818b ;}")
+        self.dlg.pushButton_up.setStyleSheet("#pushButton_up {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_up:hover{background: #66ab27 ;}#pushButton_up:disabled{background: #64818b ;}")
+        self.dlg.pushButton.setStyleSheet("#pushButton {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton:hover{background: #66ab27 ;}#pushButton:disabled{background: #64818b ;}")
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}#pushButton_close:disabled{background: #64818b ;}")
+        self.dlg.pushButton_deleteLayers.setStyleSheet("#pushButton_deleteLayers {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_deleteLayers:hover{background: #66ab27 ;}#pushButton_deleteLayers:disabled{background: #64818b ;}")
+        self.dlg.pushButton_deleteMap.setStyleSheet("#pushButton_deleteMap {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_deleteMap:hover{background: #66ab27 ;}#pushButton_deleteMap:disabled{background: #64818b ;}")
+        self.dlg.pushButton_addRaster.setStyleSheet("#pushButton_addRaster {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_addRaster:hover{background: #66ab27 ;}#pushButton_addRaster:disabled{background: #64818b ;}")
+        self.dlg.pushButton_addMap.setStyleSheet("#pushButton_addMap {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_addMap:hover{background: #66ab27 ;}#pushButton_addMap:disabled{background: #64818b ;}")
+        self.dlg.pushButton_editMeta.setStyleSheet("#pushButton_editMeta {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_editMeta:hover{background: #66ab27 ;}#pushButton_editMeta:disabled{background: #64818b ;}")
+        self.dlg.pushButton_loadMapWFS.setStyleSheet("#pushButton_loadMapWFS {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_loadMapWFS:hover{background: #66ab27 ;}#pushButton_loadMapWFS:disabled{background: #64818b ;}")
+        self.dlg.pushButton_loadMap.setStyleSheet("#pushButton_loadMap {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_loadMap:hover{background: #66ab27 ;}#pushButton_loadMap:disabled{background: #64818b ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+        
+
+
+        result = self.dlg.exec_()
+    def run_DeleteMapDialog(self):
+        self.dlg = DeleteMapDialog()
+        self.refreshListWidgetMaps()
+        self.dlg.pushButton.setEnabled(False)
+        self.dlg.treeWidget.itemClicked.connect(self.enableButton) 
+        self.dlg.pushButton.clicked.connect(lambda: self.deleteMapFromServer(self.dlg.treeWidget.selectedItems()[0].text(0)))
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        self.dlg.show()
+        result = self.dlg.exec_()
+    def run_ImportLayerDialog(self):
+        self.dlg = ImportLayerDialog()
+        
+      #  self.dlg.pushButton.clicked.connect(lambda: self.postRequest(self.dlg.treeWidget.currentItem().text(0)))
+
+        self.dlg.pushButton.clicked.connect(lambda: self.callPostRequest(self.dlg.treeWidget.selectedItems()))
+       
+        
+        self.dlg.pushButton.setEnabled(False)
+       # self.dlg.treeWidget.itemClicked.connect(self.enableButton)  
+        self.dlg.treeWidget.itemPressed.connect(self.enableButtonImport)
+        self.dlg.treeWidget.itemClicked.connect(self.onItemClicked)
+        layers = QgsProject.instance().mapLayers().values()
+        
+        for layer in layers:           
+            if (layer.type() == QgsMapLayer.VectorLayer):
+                layerType = 'vector layer'
+            else:
+                layerType = 'raster layer'
+            item = QTreeWidgetItem([layer.name(), layerType])           
+            self.dlg.treeWidget.addTopLevelItem(item)
+        self.dlg.setWindowModality(Qt.ApplicationModal)
+
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}")
+        self.dlg.pushButton.setStyleSheet("#pushButton {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton:hover{background: #66ab27 ;}#pushButton:disabled{background: #64818b ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+
+        self.dlg.show()
+      
+        
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        result = self.dlg.exec_()
+    def run_login(self):
+        self.dlg = ConnectionManagerDialog()
+        self.dlg.show()    
+        self.dlg.pushButton_Connect.setEnabled(False) 
+        if (os.path.isfile(os.getenv("HOME") + os.sep + ".layman" + os.sep +'layman_user.INI')):
+            config = self.loadIni()
+            if len(config['DEFAULT']['login']) > 0:
+                self.Agrimail = config['DEFAULT']['login']
+                self.dlg.pushButton_Connect.setEnabled(True) 
+            self.dlg.lineEdit_userName.setText(config['DEFAULT']['login'] + "@lesprojekt.cz")            
+            self.dlg.lineEdit_AgriID.setText(config['DEFAULT']['id']) 
+        else:
+            try:
+                os.makedirs(os.getenv("HOME") + os.sep + ".layman")
+            except:
+                print("layman directory already exists")
+            self.dlg.lineEdit_userName.setText("@lesprojekt.cz")
+            self.dlg.pushButton_Connect.setEnabled(True) 
+        self.dlg.pushButton_ttt.hide()
+
+        
+        self.dlg.lineEdit_userName.textChanged.connect(self.checkUsername)
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        self.dlg.pushButton_Connect.clicked.connect(lambda: self.openAuthLiferayUrl())
+        self.dlg.pushButton_Continue.clicked.connect(lambda: self.getToken())
+        self.dlg.pushButton_Continue.setEnabled(False)       
+        self.dlg.pushButton_ttt.clicked.connect(lambda: self.printVariables())
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}")
+        self.dlg.pushButton_Connect.setStyleSheet("#pushButton_Connect {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_Connect:hover{background: #66ab27 ;}")
+        self.dlg.pushButton_Continue.setStyleSheet("#pushButton_Continue {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_Continue:hover{background: #66ab27 ;} #pushButton_Continue:disabled{background: #64818b ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+        result = self.dlg.exec_()
+    def run_AddMapDialog(self):        
+        url = self.URI+'/rest/'+self.laymanUsername+'/maps'
+        print(url)
+        r = requests.get(url = url)
+        print(r.content)
+        data = r.json()
+        self.dlg = AddMapDialog()
+        
+        for row in range(0, len(data)):
+            url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+data[row]['name']+'/file'
+            r = requests.get(url = url)
+         #   print(r.content)
+            d = r.json()
+            print(d['title'])
+         #   item = QTreeWidgetItem([data[row]['name'], data[row]['url'], data[row]['uuid']])           
+            item = QTreeWidgetItem([d['title']])            
+            self.dlg.treeWidget.addTopLevelItem(item)
+        
+        
+      
+        self.dlg.pushButton.setEnabled(False)
+        self.dlg.pushButton_mapWFS.setEnabled(False)
+        self.dlg.label_info.hide()
+     
+        self.dlg.treeWidget.itemClicked.connect(self.showThumbnailMap)
+        self.dlg.treeWidget.itemClicked.connect(self.enableButton)
+        self.dlg.treeWidget.itemClicked.connect(self.enableLoadMapButtons)
+        
+
+        self.dlg.pushButton.clicked.connect(lambda: self.readMapJson(self.dlg.treeWidget.selectedItems()[0].text(0), 'WMS'))
+        self.dlg.pushButton_mapWFS.clicked.connect(lambda: self.readMapJson(self.dlg.treeWidget.selectedItems()[0].text(0), 'WFS'))
+        
+
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+
+        self.dlg.pushButton_mapWFS.setStyleSheet("#pushButton_mapWFS {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_mapWFS:hover{background: #66ab27 ;}#pushButton_mapWFS:disabled{background: #64818b ;}")
+        self.dlg.pushButton.setStyleSheet("#pushButton {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton:hover{background: #66ab27 ;}#pushButton:disabled{background: #64818b ;}")
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}#pushButton_close:disabled{background: #64818b ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+
+        self.dlg.show()
+        result = self.dlg.exec_()
+    def run_AddLayerDialog(self):
+        if not self.loadedInMemory:
+            self.loadAllComposites()
+        url = self.URI+'/rest/'+self.laymanUsername+'/layers'
+        r = requests.get(url = url)
+        data = r.json()
+        self.dlg = AddLayerDialog()
+        self.dlg.pushButton_layerRedirect.hide()
+        self.dlg.pushButton_layerRedirect.setEnabled(False)
+        self.dlg.pushButton.setEnabled(False)
+        self.dlg.pushButton_wfs.setEnabled(False)
+        self.dlg.pushButton_delete.setEnabled(False)
+        
+        for row in range(0, len(data)):            
+            item = QTreeWidgetItem([data[row]['name']])
+            self.dlg.treeWidget.addTopLevelItem(item)
+        self.dlg.pushButton_delete.clicked.connect(lambda: self.layerDelete(self.dlg.treeWidget.selectedItems()[0].text(0)))    
+        self.dlg.pushButton_layerRedirect.clicked.connect(lambda: self.layerInfoRedirect(self.dlg.treeWidget.selectedItems()[0].text(0)))
+        self.dlg.pushButton.clicked.connect(lambda: self.readLayerJson(self.dlg.treeWidget.selectedItems()[0].text(0), "WMS"))
+        self.dlg.pushButton_wfs.clicked.connect(lambda: self.readLayerJson(self.dlg.treeWidget.selectedItems()[0].text(0), "WFS"))
+        self.dlg.treeWidget.itemClicked.connect(self.showThumbnail)  
+        self.dlg.treeWidget.itemClicked.connect(self.enableDeleteButton) 
+        self.dlg.pushButton_close.clicked.connect(lambda: self.dlg.close())
+        self.dlg.setWindowModality(Qt.ApplicationModal)
+
+        self.dlg.pushButton_delete.setStyleSheet("#pushButton_delete {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_delete:hover{background: #66ab27 ;}#pushButton_delete:disabled{background: #64818b ;}")
+        self.dlg.pushButton_close.setStyleSheet("#pushButton_close {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_close:hover{background: #66ab27 ;}#pushButton_close:disabled{background: #64818b ;}")
+        self.dlg.pushButton_delete.setStyleSheet("#pushButton_delete {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_delete:hover{background: #66ab27 ;}#pushButton_delete:disabled{background: #64818b ;}")
+        self.dlg.pushButton.setStyleSheet("#pushButton {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton:hover{background: #66ab27 ;}#pushButton:disabled{background: #64818b ;}")
+        self.dlg.pushButton_wfs.setStyleSheet("#pushButton_wfs {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} #pushButton_wfs:hover{background: #66ab27 ;}#pushButton_wfs:disabled{background: #64818b ;}")
+        self.dlg.setStyleSheet("#DialogBase {background: #f0f0f0 ;}")
+
+
+        self.dlg.show()
+        result = self.dlg.exec_()
+    def showExistingLayers(self,x):
+ 
+        self.dlg.listWidget_listLayers.clear()    
+        for i in range (0,len(self.compositeList[self.dlg.listWidget.currentRow()]['layers'])):         
+               
+            self.dlg.listWidget_listLayers.addItem(self.compositeList[self.dlg.listWidget.currentRow()]['layers'][i]['params']['LAYERS'])
+    #--------------------------- slots---------------------
+   # @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
+    def onItemClicked(self, it, col):     
+        if (it.text(1) == 'raster layer'):
+            self.dlg.pushButton.setEnabled(False)
+        else:
+            self.dlg.pushButton.setEnabled(True)
+    def setExtent(self, it, col):
+        layer = QgsProject.instance().mapLayersByName(it.text(0))
+        ext = layer[0].extent()
+        xmin = ext.xMinimum()
+        xmax = ext.xMaximum()
+        ymin = ext.yMinimum()
+        ymax = ext.yMaximum()
+        self.dlg.lineEdit_3.setText(str(xmin))
+        self.dlg.lineEdit_4.setText(str(xmax))
+        self.dlg.lineEdit_5.setText(str(ymin))
+        self.dlg.lineEdit_6.setText(str(ymax))
+        self.dlg.label_4.setText("Extent of canvas: " + it.text(0))
+
+    def enableDeleteButton(self, item, col):
+        self.dlg.pushButton.setEnabled(True)
+        self.dlg.pushButton_wfs.setEnabled(True)
+        self.dlg.pushButton_layerRedirect.setEnabled(True)
+        self.dlg.pushButton_delete.setEnabled(True)
+
+    def enableButton(self, item, col):
+        
+        
+        self.dlg.pushButton.setEnabled(True)
+        self.dlg.pushButton_mapWFS.setEnabled(True)
+        self.dlg.pushButton_deleteLayers.setEnabled(True)
+        self.dlg.pushButton_editMeta.setEnabled(True)
+        self.dlg.pushButton_addRaster.setEnabled(True)       
+
+            
+
+    def checkUsername(self, name):
+        n = name.split("@")
+        if(len(n[0]) > 0):
+            self.dlg.pushButton_Connect.setEnabled(True) 
+            self.Agrimail = n[0]
+        else:
+            self.dlg.pushButton_Connect.setEnabled(False) 
+
+        
+    def checkLoadedMap(self, name):
+        print(self.compositeList)
+        loaded = False
+        for i in range (0, len(self.compositeList)):
+            if self.compositeList[i]['name'] == name:
+                loaded = True
+            
+        return loaded 
+                   
+        
+                   
+    def enableLoadMapButtons(self, item):
+        self.dlg.pushButton_mapWFS.setEnabled(True)
+    def enableButtonImport(self, item, column):
+        if (len(self.dlg.treeWidget.selectedItems()) > 0):
+            self.dlg.pushButton.setEnabled(True)
+        else:
+            self.dlg.pushButton.setEnabled(False)
+
+
+    def enableButton(self, item):
+        try: ## addMap nemá combobox
+            if (self.dlg.mMapLayerComboBox.count() > 0):
+                self.dlg.pushButton.setEnabled(True) 
+                self.dlg.pushButton_mapWFS.setEnabled(True)
+            else:
+                self.dlg.pushButton.setEnabled(False)
+        except:
+            self.dlg.pushButton.setEnabled(True) ## addMap nemá combobox nastavujeme funkční tlačítko
+
+        try:
+            self.dlg.pushButton_deleteLayers.setEnabled(True) # pro formulář importMap
+        except:
+            pass
+    def listCompositeLayers(self, it):    
+         self.dlg.listWidget_listLayers2.clear()    
+         for i in range (0,len(self.compositeList[self.dlg.listWidget.currentRow()]['layers'])):    
+            
+            self.dlg.listWidget_listLayers2.addItem(self.compositeList[self.dlg.listWidget.currentRow()]['layers'][i]['params']['LAYERS'])
+    def deleteLayerThrowCompositions(self, name):
+        for x in range (0,len(self.compositeList)):
+           
+            for i in range (0,len(self.compositeList[x]['layers'])): 
+                if (name == self.compositeList[x]['layers'][i]['params']['LAYERS']):
+                    inComposite = True
+                    print(self.compositeList[x]['layers'][i]['params']['LAYERS'])
+                    self.deteteLayerFromComposite(x, i, name)
+    def checkLayersInComopsitions(self, name):
+        inComposite = False
+        for x in range (0,len(self.compositeList)):
+           
+            for i in range (0,len(self.compositeList[x]['layers'])): 
+                if (name == self.compositeList[x]['layers'][i]['params']['LAYERS']):
+                    inComposite = True
+                    print(self.compositeList[x]['layers'][i]['params']['LAYERS'])
+        return inComposite
+
+
+    def refreshCompositeList(self):
+        self.dlg.listWidget.clear()
+        print (len(self.compositeList))
+        
+        for i in range (0, len(self.compositeList)):
+           # self.dlg.listWidget.addItem(self.compositeList[i]['name'])
+           self.dlg.listWidget.addItem(self.compositeList[i]['title'])
+ 
+
+    def refreshLayerList(self):
+        self.dlg.listWidget_listLayers.clear()
+        for i in range (0,len(self.compositeList[self.dlg.listWidget.currentRow()]['layers'])):
+            self.dlg.listWidget_listLayers.addItem(self.compositeList[self.dlg.listWidget.currentRow()]['layers'][i]['params']['LAYERS'])
+            print(self.compositeList[self.dlg.listWidget.currentRow()]['layers'][i]['params']['LAYERS'])
+
+
+
+    def refreshListWidgetMaps(self):
+        self.dlg.treeWidget.clear()
+        url = self.URI+'/rest/'+self.laymanUsername+'/maps'
+        print(url)
+        r = requests.get(url = url)
+        #print(r.content())
+        data = r.json()  
+       
+        for row in range(0, len(data)):                
+            item = QTreeWidgetItem([data[row]['name']])           
+            self.dlg.treeWidget.addTopLevelItem(item)
+
+    def showAddMapDialog(self):
+        self.old_dlg = self.dlg
+        self.run_CreateCompositeDialog(True)      
+        
+       
+    ### connect
+    def afterCloseCompositeDialog(self):        
+        self.dlg = self.old_dlg
+        self.refreshCompositeList()
+
+    def afterCloseEditMapDialog(self):
+        self.dlg = self.old_dlg
+
+    def showEditMapDialog(self, x):        
+        self.old_dlg = self.dlg
+        self.run_EditMap(x)
+            ############### pravdepodobne půjde smazat
+    def refreshItems(self):
+  
+         self.dlg.listWidget_listLayers.clear()    
+         for i in range (0,len(self.compositeList)):            
+           # self.dlg.listWidget_listLayers.addItem(self.compositeList[i]['name'])
+           self.dlg.listWidget_listLayers.addItem(self.compositeList[i]['title'])
+
+    def saveEditedToComposite(self,x):        
+        self.compositeList[x]['abstract'] =  self.dlg.lineEdit_abstract.text()  
+        self.compositeList[x]['title'] =  self.dlg.lineEdit_title.text() 
+
+    def layerDelete(self, name):
+        if (self.checkLayersInComopsitions(name) == True):
+            msgbox = QMessageBox(QMessageBox.Question, "Delete layer", "This layers is included in other compositions. It will be delete from every composition.")
+            msgbox.addButton(QMessageBox.Yes)
+            msgbox.addButton(QMessageBox.No)
+            msgbox.setDefaultButton(QMessageBox.No)
+            reply = msgbox.exec()
+            if (reply == QMessageBox.Yes):
+                url = self.URI+'/rest/'+self.laymanUsername+'/layers/'+name    
+                response = requests.delete(url, headers = self.authHeader)
+                print(response.content)
+                print(response)
+                self.addLayerRefresh()
+                try:
+                    self.deleteLayerThrowCompositions(name)
+                except:
+                    pass
+                
+        else:    
+            url = self.URI+'/rest/'+self.laymanUsername+'/layers/'+name    
+            response = requests.delete(url, headers = self.authHeader)
+            print(response.content)
+            print(response)
+            self.addLayerRefresh()
+    def addLayerRefresh(self):
+        self.dlg.treeWidget.clear()
+        url = self.URI+'/rest/'+self.laymanUsername+'/layers'
+        r = requests.get(url = url)
+        data = r.json()
+        for row in range(0, len(data)):            
+            item = QTreeWidgetItem([data[row]['name']])
+            self.dlg.treeWidget.addTopLevelItem(item)
+    def checkIfMapExist(self, name):
+        url = "http://layman.lesprojekt.cz/rest/"+self.laymanUsername+"/maps/"+str(name)+"/file"
+        r = requests.get(url)
+        print(r.content)
+        if (r.status_code == 404):
+            return False
+        else:
+            return True
+
+    def reorderLayers(self, pos, order, x):
+        self.compositeList[x]['layers']
+        i = 0
+        
+        for lay in self.compositeList[x]['layers']:
+            #print (lay)
+            if i == pos:
+
+                pom = self.compositeList[x]['layers'][i]
+                self.compositeList[x]['layers'][i] = self.compositeList[x]['layers'][i + order]
+                self.compositeList[x]['layers'][i + order] = pom     
+
+            i = i + 1
+        print(self.compositeList[x]['layers'])
+        self.importMap(x, 'mod')
+        self.refreshLayerList()
+        self.dlg.listWidget_listLayers.setCurrentRow(pos + order)
+
+    def showThumbnail(self, it):
+        try:
+            layer = it.text(0) ##pro QTreeWidget
+        except:
+            layer = it.text()##pro listWidget
+        try:
+            url = self.URI+'/rest/' +self.laymanUsername+'/layers/'+str(layer)+'/thumbnail'    
+            data = urlopen(url).read()
+            pixmap = QPixmap(200, 200)
+            pixmap.loadFromData(data)
+            smaller_pixmap = pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.FastTransformation)
+            self.dlg.label_thumbnail.setPixmap(smaller_pixmap)
+            self.dlg.label_thumbnail.setAlignment(Qt.AlignCenter)
+        except:
+            self.dlg.label_thumbnail.setText('  Unable to load thumbnail.')
+    def showSmallThumbnail(self, it):
+        try:
+            layer = it.text(0) ##pro QTreeWidget
+        except:
+            layer = it.text()##pro listWidget
+        try:
+            url = self.URI+'/rest/'+self.laymanUsername+'/layers/'+str(layer)+'/thumbnail'    
+            data = urlopen(url).read()
+            pixmap = QPixmap(170, 170)
+            pixmap.loadFromData(data)
+            smaller_pixmap = pixmap.scaled(170, 170, Qt.KeepAspectRatio, Qt.FastTransformation)
+            self.dlg.label_thumbnail.setPixmap(smaller_pixmap)
+            self.dlg.label_thumbnail.setAlignment(Qt.AlignCenter)
+        except:
+            self.dlg.label_thumbnail.setText('  Unable to load thumbnail.')
+
+    def showThumbnailMap(self, it):
+        try:
+            map = it.text(0) ##pro QTreeWidget
+        except:
+            map = it.text()##pro listWidget
+        
+        try:
+            map = self.removeUnacceptableChars(str(map))
+            url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+str(map)+'/thumbnail'    
+            print(url)
+            data = urlopen(url).read()
+            pixmap = QPixmap(100, 100)
+            pixmap.loadFromData(data)
+            smaller_pixmap = pixmap.scaled(100, 100, Qt.KeepAspectRatio, Qt.FastTransformation)
+            self.dlg.label_thumbnail.setPixmap(smaller_pixmap)
+           # self.dlg.label_thumbnail.setAlignment(Qt.AlignCenter)
+        except:
+            self.dlg.label_thumbnail.setText('       Unable to load thumbnail.')
+
+    def checkNameCreateMap(self):
+        text = self.dlg.lineEdit_2.text()
+        text = self.removeUnacceptableChars(text)
+        print(text)
+        if (self.checkIfMapExist(text)):
+            self.dlg.pushButton_CreateComposition.setEnabled(False)
+            self.dlg.label_info.show()
+            
+        else:
+            self.dlg.pushButton_CreateComposition.setEnabled(True)
+            self.dlg.label_info.hide()
+    #----------------------------------------------------------
+    def readLayerJson(self,layerName, service):
+        if self.checkLayerOnLayman(layerName):
+            url = self.URI+'/rest/'+self.laymanUsername+'/layers/'+layerName  
+            print (url)
+            r = requests.get(url = url)
+            data = r.json()
+            if (service == "WMS"):
+                print("loading WMS")
+                print (data['wms']['url'])
+                wmsUrl = data['wms']['url']
+                format = 'png'
+                epsg = 'EPSG:4326' 
+                self.loadWms(wmsUrl, layerName, format, epsg) 
+            if (service == "WFS"):
+                wfsUrl = data['wfs']['url']
+                print("loading WFS")
+                self.loadWfs(wfsUrl, layerName) 
+        else:
+            QMessageBox.information(None, "Layman", "Something went wrong with this layer: "+layerName)
+    def loadAllComposites(self):
+        url = self.URI+'/rest/' + self.laymanUsername + '/maps'
+        try:
+            r = requests.get(url = url)
+        except:
+            QMessageBox.information(None, "Error", "Connection with server failed!.")
+        data = r.json()  
+        print(data)
+        for i in data:
+            print(i['name'])
+            url = self.URI+'/rest/' + self.laymanUsername + '/maps/'+i['name']+'/file'  
+            r = requests.get(url = url)
+            map = r.json()
+            self.compositeList.append (map)
+        self.loadedInMemory = True
+
+    def readMapJson(self,name, service):
+        nameWithDiacritics = name        
+        name = self.removeUnacceptableChars(name)
+        print(name)
+        print("readMapJson " + name)
+        if not self.checkLoadedMap(name): ## je nactena mapa?
+            url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+name   +'/file'     
+            r = requests.get(url = url)
+            data = r.json()   
+            print(data)
+        
+            self.addComposite(data,service, name)
+            try:
+                self.refreshCompositeList()        ## pouze pro import Form     
+            except:
+                pass
+        else:
+            url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+name   +'/file'     
+            r = requests.get(url = url)
+            data = r.json()
+            self.loadService(data,service, name)
+
+        #    QMessageBox.information(None, "Message", "This map is already loaded in memory. Loading only layers to canvas")
+    
+
+    def deleteMapFromServer(self,name):        
+        
+        url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+name    
+        response = requests.delete(url, headers = self.authHeader)
+        print(response)
+        QMessageBox.information(None, "Message", "Composition deleted sucessfully.")
+       # self.refreshMapList()            
+        self.refreshListWidgetMaps() ## pro treewidget
+        
+      
+    def deleteMap(self,name, x):      
+        name = self.removeUnacceptableChars(name)
+        url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+name    
+        response = requests.delete(url, headers = self.authHeader)
+        print(response)
+        print(response.content)
+        QMessageBox.information(None, "Message", "Composition deleted sucessfully.")
+        del (self.compositeList[x])        
+        self.refreshCompositeList()## pro import map form
+        self.dlg.listWidget_listLayers.clear()
+      
+        
+        
+      
+    def deleteMapandLayers(self,name, x):        
+        try:
+            url = self.URI+'/rest/'+self.laymanUsername+'/maps/'+name    
+            response = requests.delete(url, headers = self.authHeader)
+            QMessageBox.information(None, "Message", "Composition deleted sucessfully.")
+            
+            
+      
+        except:
+            QMessageBox.information(None, "Warning", "Deleting composition failed.")
+        #self.refreshItems()
+        self.deleteMapFromCanvas(x)
+        self.dlg.listWidget_listLayers.clear()
+        self.dlg.pushButton_deleteLayers.setEnabled(False)
+        self.dlg.pushButton.setEnabled(False)
+        self.dlg.pushButton_deleteMap.setEnabled(False)
+        self.refreshCompositeList()
+
+    def deleteMapFromCanvas(self, x):
+        for i in range (0,len(self.compositeList[x]['layers'])):  #[0]['params']['LAYERS']:
+            name = self.compositeList[x]['layers'][i]['params']['LAYERS']
+            lay = QgsProject.instance().mapLayersByName(name)[0]
+            if (lay != None and lay.type() != QgsMapLayer.VectorLayer):
+                QgsProject.instance().removeMapLayer(lay.id())
+        del (self.compositeList[x])
+
+    def deleteLayerFromCanvas(self, name):        
+        lay = QgsProject.instance().mapLayersByName(name)[0]        
+        if (lay != None and lay.type() != QgsMapLayer.VectorLayer):
+            QgsProject.instance().removeMapLayer(lay.id())
+        
+        
+    def getSelectedLayers(self):
+        arr = self.dlg.listWidget_listLayers2.selectedItems()
+        layers = []
+        for a in arr:
+            layer = QgsProject.instance().mapLayersByName(a.text())
+            for lay in layer:
+
+                if (lay.type() == QgsMapLayer.VectorLayer):
+                    layers.append(lay)
+            
+        return layers
+    def run_getLayer(self):
+        """Run method that performs all the real work"""
+
+        # Create the dialog with elements (after translation) and keep reference
+        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
+        if self.first_start == True:
+            self.first_start = False
+            
+            
+        self.dlgGetLayers.items.clear()
+        # show the dialog
+        self.dlgGetLayers.show()
+        data= self.getExistingLayers()
+        for x in range(len(data)):
+            print(data[x]['name'])
+            self.dlgGetLayers.items.addItem(data[x]['name'])
+        # Run the dialog event loop
+        print (self.dlgGetLayers)
+        result = self.dlgGetLayers.exec_()
+       
+        
+        # See if OK was pressed
+        if result:
+            # Do something useful here - delete the line containing pass and
+            # substitute with your code.
+           
+            print ("test tlacitka")
+   
+    def onClosePlugin(self):
+        """Cleanup necessary items here when plugin dockwidget is closed"""
+
+        #print "** CLOSING Atlas"
+
+        # disconnects
+        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
+
+  
+
+        self.pluginIsActive = False
+
+
+    def unload(self):
+        """Removes the plugin menu item and icon from QGIS GUI."""
+
+        #print "** UNLOAD Atlas"
+
+        for action in self.actions:
+            self.iface.removePluginMenu(
+                self.tr(u'&Atlas'),
+                action)
+            self.iface.removeToolBarIcon(action)
+        # remove the toolbar
+        del self.toolbar
+
+    #--------------------------------------------------------------------------
+    def bounds(self, layers):
+
+        extent = None
+        for layer in layers:
+            if layer.type() == 0:
+                transform = QgsCoordinateTransform(layer.crs(), QgsCoordinateReferenceSystem('EPSG:4326'), QgsProject.instance()) # WGS 84 / UTM zone 33N
+                try:
+                    layerExtent = transform.transform(layer.extent())
+                except QgsCsException:
+                    print("exception in transform layer srs")
+                    layerExtent = QgsRectangle(-180, -90, 180, 90)
+                if extent is None:
+                    extent = layerExtent
+                else:
+                    extent.combineExtentWith(layerExtent)
+
+        return (extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum())
+    def copySymbols(self,symbol, tempPath, fileNames):
+        for i in range(symbol.symbolLayerCount()):
+            sl = symbol.symbolLayer(i)
+            if isinstance(sl, QgsSvgMarkerSymbolLayer):
+                symbolPath = sl.path();
+                shutil.copy(symbolPath, tempPath)
+                print("Copying " + str(sl.path()))
+                fileNames.append(tempPath + os.sep + os.path.basename(symbolPath))
+            else:
+                print("Ignoring " + str(sl))
+
+    def setDefaultExtent (self, ext):        
+        self.dlg.lineEdit_3.setText(str(ext.xMinimum()))
+        self.dlg.lineEdit_4.setText(str(ext.xMaximum()))
+        self.dlg.lineEdit_5.setText(str(ext.yMinimum()))
+        self.dlg.lineEdit_6.setText(str(ext.yMaximum()))
+
+
+    def loadJsonLayer(self, fileName):    
+        name = (os.path.splitext(os.path.basename(fileName))[0])
+        vlayer = QgsVectorLayer(fileName, name,"ogr")
+        sldPath = os.path.splitext(fileName[:-4])[0] + ".sld"
+        print (sldPath)
+        exists = os.path.isfile(sldPath)
+        if (exists):
+            vlayer.loadSldStyle(os.path.splitext(fileName)[0]+ ".sld")
+            print("sld loaded")
+        QgsProject.instance().addMapLayer(vlayer)
+        vlayer.triggerRepaint()
+    def checkLoadedLayer(self):
+        layers = iface.layerTreeView().selectedLayers()
+        if (len(layers) > 0):
+            self.json_export()    
+        else:
+            QMessageBox.information(None, "Message", "You must load layer first!")
+    def getEmptyComposite(self, compositeName, compositeTitle):        
+        compositeEPSG  = "epsg:4326"        
+        if (self.dlg.lineEdit_3.text() == "" or self.dlg.lineEdit_4.text() == "" or self.dlg.lineEdit_5.text() == "" or self.dlg.lineEdit_6.text() == ""):
+           ext = iface.mapCanvas().extent() 
+           xmin = ext.xMinimum()
+           xmax = ext.xMaximum()
+           ymin = ext.yMinimum()
+           ymax = ext.yMaximum()
+        else:   
+           xmin = self.dlg.lineEdit_3.text()
+           xmax = self.dlg.lineEdit_4.text()
+           ymin = self.dlg.lineEdit_5.text()
+           ymax = self.dlg.lineEdit_6.text() 
+        
+            
+        abstract = self.dlg.lineEdit_7.text()        
+        comp = {"abstract":abstract,"center":[1672068,6568819],"current_base_layer":{"title":"Composite_base_layer"},"extent":[str(xmin),str(ymin),str(xmax),str(ymax)],"groups":{"guest":"w"},"layers":[],"name":compositeName,"projection":compositeEPSG,"scale":1,"title":compositeTitle,"units":"m","user":{"email":"","name":self.laymanUsername}}
+        self.dlg.close()
+        iface.messageBar().pushWidget(iface.messageBar().createMessage("Atlas:", " Kompozice  " + compositeName + " byla úspešně vytvořena."), Qgis.Success, duration=3)
+        return comp
+    def loadLocalFile(self):
+        options = QFileDialog.Options()
+        dialog = QFileDialog()
+        dialog.setStyleSheet("QPushButton {color: #fff !important;text-transform: uppercase;  text-decoration: none;   background: #72c02c;   padding: 20px;  border-radius: 50px;    display: inline-block; border: none;transition: all 0.4s ease 0s;} QPushButton:hover{background: #66ab27 ;}QPushButton:disabled{background: #64818b ;}");
+        fileName = dialog.getOpenFileName(None,"Load file", "","GeoJson Files (*.geojson);;Json Files (*.json)", options=options)
+        print ("načítám json ze souboru:" + fileName[0])
+        self.loadJsonLayer(fileName[0])
+    def modifyMap(self, x):        
+        name = self.removeUnacceptableChars(self.dlg.lineEdit_title.text())
+        #self.compositeList[x]['name'] = self.dlg.lineEdit_name.text()
+        self.compositeList[x]['name'] = name
+        self.compositeList[x]['abstract'] = self.dlg.lineEdit_abstract.text()
+        self.compositeList[x]['title'] = self.dlg.lineEdit_title.text()
+
+        
+        print(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'])       
+        oldName = self.dlg.lineEdit_name.text()
+        response = requests.delete(self.URI+'/rest/'+self.laymanUsername+'/maps/'+oldName,headers = self.authHeader)
+        print(response.content)
+        self.dlg.close()
+        self.afterCloseEditMapDialog()
+        self.importMap(x, 'mod')
+        
+        try:
+            self.refreshCompositeList()
+            iface.messageBar().pushWidget(iface.messageBar().createMessage("Import:", " Map metadata was saved successfully."), Qgis.Success, duration=3)
+        except:
+            pass
+        
+        
+    def saveLocalFile(self):
+        
+        layer = self.iface.activeLayer() 
+        path = iface.activeLayer().dataProvider().dataSourceUri()
+        path = path.split("|")[0].replace("'","")
+        if (layer == None):
+            QMessageBox.information(None, "Message", "You must load layer first!")
+        else:
+           # defaultDir = QDir().home()
+            defaultDir = os.path.dirname(path)
+            print(defaultDir)
+            print(defaultDir +os.sep+ str(layer.name()) + ".geojson")
+            print(QDir().homePath() +os.sep+ str(layer.name()) + ".geojson")
+            dialog = QFileDialog()
+            dialog.setFileMode(1)
+            dialog.setDirectory(defaultDir)
+            print(dialog.directory().path())
+           # layer_name = dialog.getSaveFileName(None, "Save file", QDir().homePath() +os.sep+ str(layer.name()) + ".geojson", "*.geojson")        
+            layer_name = dialog.getSaveFileName(None, "Save file", defaultDir +os.sep+ str(layer.name()) + ".geojson", "*.geojson")        
+            self.json_export_local(layer_name[0], layer)
+
+    def json_export_local(self, layer_name, lay):     
+        import shutil
+        filePath = self.getTempPath(layer_name)  
+        ogr_driver_name = "GeoJSON" 
+        project = QgsProject.instance()
+        fileNames = []
+        ## zde musí být zajištěna vektorová vrstva
+        layer = lay        
+        layerType = layer.type()
+        if layerType == QgsMapLayer.VectorLayer:
+
+            renderer = layer.renderer()
+            hasIcon = False
+            if isinstance(renderer, QgsSingleSymbolRenderer):
+
+                self.copySymbols(renderer.symbol(), tempfile.gettempdir(), fileNames)
+                hasIcon = True
+
+
+            layerCrs = qgis.utils.iface.activeLayer().crs().authid()
+            crs = QgsCoordinateReferenceSystem(layerCrs)          
+            result2 = qgis.core.QgsVectorFileWriter.writeAsVectorFormat(layer, layer_name, "utf-8", crs, ogr_driver_name) # export jsonu do souboru
+            print(result2)
+            if(result2[0] == 2): ## testujeme zda není soubor otevřený v jiném procesu / návratový kod 2
+                
+                tempFile = self.getTempPath(os.path.basename(layer_name.replace(".geojson", "") ))
+                print(tempFile)
+                #QMessageBox.information(None, "Layman", "It is not possible overwrite this file. File is already open in other process.")  
+                sld_temp_filename = tempFile.replace("geojson", "sld") 
+                layer.saveSldStyle(sld_temp_filename)
+                result2 = qgis.core.QgsVectorFileWriter.writeAsVectorFormat(layer, tempFile, "utf-8", crs, ogr_driver_name)
+                print(result2)
+                if(result2[0] == 2):
+                    QMessageBox.information(None, "Layman", "It is not possible overwrite this file. File is already open in other process.")  
+                    return
+                if os.path.basename(layer_name.replace(".geojson", "")) != '':
+                    QgsProject.instance().removeMapLayer(layer.id())
+                    print(tempFile, layer_name)
+                    shutil.copy(tempFile, layer_name)
+                    shutil.copy(sld_temp_filename, layer_name.replace(".geojson", ".sld"))
+                    self.loadJsonLayer(layer_name)
+                
+            else:                
+                sld_filename = layer_name.replace("geojson", "sld")             
+                result3 = False
+                layer.saveSldStyle(sld_filename)
+
+    def json_export(self, layer_name):     
+
+        filePath = self.getTempPath(layer_name)  
+        ogr_driver_name = "GeoJSON"     
+        project = QgsProject.instance()
+        fileNames = []      
+        layer = QgsProject.instance().mapLayersByName(layer_name)[0]       
+        
+        layerType = layer.type()
+        if layerType == QgsMapLayer.VectorLayer:
+
+            renderer = layer.renderer()
+            hasIcon = False
+            if isinstance(renderer, QgsSingleSymbolRenderer):
+
+                self.copySymbols(renderer.symbol(), tempfile.gettempdir(), fileNames)
+                hasIcon = True
+
+
+            #layerCrs = qgis.utils.iface.activeLayer().crs().authid()
+            layerCrs = layer.crs().authid()
+            crs = QgsCoordinateReferenceSystem(layerCrs)# původně bylo
+            layer_filename = filePath       
+          #  crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
+            ##crs = layer.crs().authid()
+         #   tempOut = layer_filename.replace(".geojson", "_2.geojson") 
+            result2 = qgis.core.QgsVectorFileWriter.writeAsVectorFormat(layer, layer_filename, "utf-8", crs, ogr_driver_name) # export jsonu do souboru
+            ##transformace
+        #    input = tempOut
+        #    out = layer_filename
+        #    try:
+        #        os.remove(layer_filename)
+        #    except:
+        #        pass
+        ##    print("","-f", "Geojson", "-s_srs", layerCrs, "-t_srs", "epsg:4326", out, input)
+        #    print("convert")
+        #    print(main(["","-f", ogr_driver_name, "-s_srs", "EPSG:5514", "-t_srs", "EPSG:4326", out, input])) ## ogr2ogr
+            ##
+            sld_filename = filePath.replace("geojson", "sld")            
+            result3 = False
+            layer.saveSldStyle(sld_filename)
+
+
+    def checkValidAttributes(self, layer_name):
+        layers = QgsProject.instance().mapLayersByName(layer_name)
+        if len(layers) > 1:
+            for l in layers:
+                if (isinstance(l, QgsVectorLayer)):
+                    print("xxx")
+                    layers.clear()
+                    layers.append(l)
+                    break
+        isValid = True
+        pom =layers[0].getFeature(1)        
+        for nam in pom.fields().names():
+            if (nam == ''):
+                isValid = False
+        return isValid
+
+
+    def checkWgsExtent(self, layer):
+        WgsXmax = 180
+        WgsXmin = -180
+        WgsYmax = 90
+        WgsYmin = -90
+        extent = layer.extent()
+        if (extent.xMaximum() > WgsXmax or extent.xMinimum() < WgsXmin or extent.yMaximum() > WgsYmax or extent.yMinimum() < WgsYmin ):
+            return False
+        else:
+            return True
+
+
+    def callPostRequest(self, layers):
+        
+        for item in layers:
+            print (item.text(0))
+            
+            
+                
+
+            self.postRequest(item.text(0))
+    #def transformLayer2(self, layer):
+    #    pass
+    def setCurrentLayer(name):
+        layers = QgsProject.instance().mapLayersByName(name) 
+        if(len(layers) >1):
+            layerss = QgsProject.instance().mapLayers().values()    
+            i = 0
+            for layer in layerss:  
+                if layers[0].name == layer.name():
+                    if (i == item.currentIndex()):
+                        i = i + 1
+                        break
+                    i = i + 1
+        return i
+    def transformLayer(self, layer):
+        layer = iface.activeLayer()
+        crsSrc = layer.crs()
+        print(crsSrc.authid())
+        crsDest = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
+        print(crsSrc, crsDest)
+        xform = QgsCoordinateTransform(crsSrc, crsDest, 5514, 4326)
+        feats=[]
+
+        if (layer.geometryType() == 0):
+            destLayer = QgsVectorLayer("Point?crs=EPSG:4326","lay","memory")
+        if (layer.geometryType() == 1):
+            destLayer = QgsVectorLayer("Linestring?crs=EPSG:4326","lay","memory")
+        if (layer.geometryType() == 2):
+            destLayer = QgsVectorLayer("Polygon?crs=EPSG:4326","lay","memory")
+
+        for f in layer.getFeatures():
+            g = f.geometry()
+    
+            g.transform(xform)
+            print(g)
+            f.setGeometry(g)
+            feats.append(f)
+    
+        destLayer.dataProvider().addFeatures(feats)
+        return destLayer
+    def postRequest(self, layer_name):     
+        nameCheck = True
+        validExtent = True
+        layers = QgsProject.instance().mapLayersByName(layer_name)  
+        layer_name = self.removeUnacceptableChars(layer_name)
+        layers[0].setName(layer_name)
+        if len(layers) > 1:
+            for l in layers:
+                if (isinstance(l, QgsVectorLayer)):                   
+                    layers.clear()
+                    layers.append(l)
+                    break
+     
+        if not (re.match('[a-zA-Z_]{1}', layer_name)): ## nesmí být nesmysl v názvu na prvním místě
+            QMessageBox.information(None, "Layman", "Diacritics or number in first character is not allowed.")
+            nameCheck = False
+        if not (re.match('[a-zA-Z0-9]', layer_name)): ## není povolena diakritika
+            QMessageBox.information(None, "Layman", "Diacritics is not allowed.")
+            nameCheck = False
+        
+        print(layer_name)
+        #if (layers[0].crs().authid() != 'EPSG:4323'):
+        #    layers[0] = self.transformLayer(layers[0]) 
+
+        if not self.checkWgsExtent(layers[0]):
+            QMessageBox.information(None, "Layman", "Extent of layer is out of WGS 84 range. (EPSG: 4326)")
+            validExtent = False
+
+        if (nameCheck and validExtent):
+                     
+            crs = layers[0].crs().authid()
+            crs = "EPSG:4326"
+            data = { 'name' :  str(layer_name), 'title' : str(layer_name), 'crs' : str(crs) } 
+            
+            if (self.checkValidAttributes(layer_name)):
+                if (self.checkExistingLayer(layer_name)):
+                    print("vrstva již existuje")
+                    msgbox = QMessageBox(QMessageBox.Question, "Layman", "Layer "+layer_name+" already exists in server. Do you want overwrite it´s geometry?")
+                    msgbox.addButton(QMessageBox.Yes)
+                    msgbox.addButton(QMessageBox.No)
+                    msgbox.setDefaultButton(QMessageBox.No)
+                    reply = msgbox.exec()
+                    if (reply == QMessageBox.Yes):
+                        print("vrstva již existuje")
+                        self.json_export(layer_name)
+                        geoPath = self.getTempPath(layer_name)
+                        #try:
+                        if (os.path.getsize(geoPath) > self.CHUNK_SIZE):
+                            self.postInChunks(layer_name, "patch")
+                        else:
+                            self.patchLayer(layer_name, data)
+                            iface.messageBar().pushWidget(iface.messageBar().createMessage("Import:", " Layer  " + layer_name + " was imported successfully."), Qgis.Success, duration=3)
+                        #except:
+                        #    iface.messageBar().pushWidget(iface.messageBar().createMessage("Import:", " Layer  " + layer_name + " was not imported successfully."), Qgis.Warning, duration=3)
+                    else:
+                        pass
+                else:
+            
+                    self.layerName = layer_name
+                   # if (self.checkEpsg(layer_name)):
+                    if(True): ##Pravděpodobně nebude třeba testovat EPSG, pokud se detekuje, je vrstva transformována. 
+                      #  print (layer_name)
+                        self.json_export(layer_name)
+                        sldPath = self.getTempPath(self.layerName).replace("geojson", "sld")
+                        geoPath = self.getTempPath(self.layerName)
+                        if (os.path.getsize(geoPath) > self.CHUNK_SIZE):
+                            self.postInChunks(layer_name, "post")
+                        else:
+                            if(os.path.isfile(sldPath)): ## existuje sld?
+                                files = [('file', open(geoPath, 'rb')), ('sld', open(sldPath, 'rb'))]
+                            else:
+                                files = {'file': (geoPath, open(geoPath, 'rb')),} 
+
+                            print(files)
+                            response = requests.post(self.URI+'/rest/'+self.laymanUsername+'/layers', files=files, data = data, headers = self.authHeader)
+                            print(response.content)
+                            print(response.status_code)
+                            if response.status_code == 200:
+                                iface.messageBar().pushWidget(iface.messageBar().createMessage("Import:", " Layer  " + layer_name + " was imported successfully."), Qgis.Success, duration=3)
+                            else:
+                                iface.messageBar().pushWidget(iface.messageBar().createMessage("Import:", " Layer  " + layer_name + " was not imported."), Qgis.Warning, duration=3)
+                    else:
+                   #     QMessageBox.information(None, "Atlas", "Vrstva "+layer_name+" nelze nahrát. Použíjte EPSG:4326 nebo EPSG:3857")
+                        QMessageBox.information(None, "Layman", "Use EPSG:4326")
+            else:
+                QMessageBox.information(None, "Layman", "Layer "+layer_name+" does not have attributes!")
+
+    def addExistingLayerToComposite(self, name):
+        x = self.dlg.listWidget.currentRow()
+        if self.checkLayerOnLayman(name):
+            inComposite = name in self.isRasterLayerInComposite(x, name)
+            if not(inComposite):
+                response = requests.get(self.URI+'/rest/'+self.laymanUsername+'/layers/'+str(name), verify=False)
+                res = self.fromByteToJson(response.content)
+                print(res)
+                wmsUrl = res['wms']['url']
+        
+            
+                self.compositeList[x]['layers'].append({"metadata":{},"visibility":True,"opacity":1,"title":str(name),"className":"HSLayers.Layer.WMS","singleTile":True,"wmsMaxScale":0,"legends":[""],"maxResolution":None,"minResolution":0,"url": wmsUrl ,"params":{"LAYERS": str(name),"INFO_FORMAT":"application/vnd.ogc.gml","FORMAT":"image/png","FROMCRS":"EPSG:3857","VERSION":"1.3.0"},"ratio":1.5,"dimensions":{}})
+                self.importMap(x, 'add', 1)
+                self.refreshLayerList()
+            else:
+                QMessageBox.information(None, "Message", "Composition already include layer "+name+"!")
+        else:
+            QMessageBox.information(None, "Layman", "Something went wrong with this layer: "+name)
+
+    def addExistingMapToMemory(self, name):
+        response = requests.get(self.URI+'/rest/'+self.laymanUsername+'/maps/'+str(name), verify=False)
+        res = self.fromByteToJson(response.content)
+        print(res)
+        wmsUrl = res['wms']['url']
+        
+        x = self.dlg.listWidget.currentRow()
+
+
+        self.compositeList[x]['layers'].append({"metadata":{},"visibility":True,"opacity":1,"title":str(name),"className":"HSLayers.Layer.WMS","singleTile":True,"wmsMaxScale":0,"legends":[""],"maxResolution":None,"minResolution":0,"url": wmsUrl ,"params":{"LAYERS": str(name),"INFO_FORMAT":"application/vnd.ogc.gml","FORMAT":"image/png","FROMCRS":"EPSG:3857","VERSION":"1.3.0"},"ratio":1.5,"dimensions":{}})
+        self.importMap(x, 'add', 1)
+        self.refreshLayerList()
+
+    def layerInfoRedirect(self, name):
+        url = self.URI+'/rest/'+self.laymanUsername+"/layers/" + name
+        print(url)
+        response = requests.get(url)
+        r = self.fromByteToJson(response.content)
+        try:
+            url = r['metadata']['record_url']
+            webbrowser.open(url, new=2) ## redirect na micku pro více info
+        except:
+            QMessageBox.information(None, "Layman", "Link is unavailable.")
+    def checkLayerOnLayman(self, layer_name):
+        url = self.URI+'/rest/'+self.laymanUsername+"/layers/"+layer_name
+        r = requests.get(url = url, verify=False)
+        #print(r.content)
+        data = r.json()
+        try:
+            if data['wms']['status'] == 'NOT_AVAILABLE' or data['wms']['status'] == 'PENDING':
+                return False
+            else:
+                return True
+        except:
+            return True # validní vrstva nemá status
+
+
+    def addLayerToComposite(self,x):
+       
+        self.compositeListOld = copy.deepcopy(self.compositeList) ## list pred upravou pro vraceni zmen
+        #layers = self.getSelectedLayers() #odkomentovat pro zapnuti nacitani vrstev z listwidgetu
+        layers = []
+        layers.append(self.dlg.mMapLayerComboBox.currentLayer())
+        successful = 0
+        print (len(layers))
+        try:
+            step = self.getProgressBarStep(len(layers))
+        except:
+            QMessageBox.information(None, "Layman", "No layer selected!")
+        
+        for i in range (0, len(layers)):
+            print(type(layers[i]))            
+            print("tst")
+            print (self.isLayerInComposite(x))
+            print (layers[i].name() in self.isLayerInComposite(x))
+            inComposite = layers[i].name() in self.isLayerInComposite(x)
+            if (self.checkExistingLayer(layers[i].name()) and inComposite):
+                j = self.getLayerInCompositePosition(x)
+                print("j je: " + str(j))
+                
+               # QMessageBox.information(None, "Message", "Composition already include layer "+layers[i].name()+"!")
+               # self.deteteLayerFromComposite(x, j, layers[i].name())
+             
+                self.postRequest(layers[i].name())
+                wmsStatus = 'PENDING'
+                j = 0
+                while ((wmsStatus == 'PENDING') and (j < 10)):
+                    print (self.URI+'/rest/'+self.laymanUsername+'/layers/'+str(layers[i].name()))
+                    response = requests.get(self.URI+'/rest/'+self.laymanUsername+'/layers/'+str(layers[i].name()), verify=False)
+                    res = self.fromByteToJson(response.content)
+                    try:
+                        wmsStatus = res['wms']['status']
+                    except:
+                        wmsStatus = "done"
+                    time.sleep(1)
+                    j = j + 1
+            
+
+                #print(res)
+                #try:
+                #    wmsUrl = res['wms']['url']
+                #except:
+                #    wmsUrl = self.URI+'/geoserver/'+layers[i].name()+'/ows'
+                #self.compositeList[x]['layers'].append({"metadata":{},"visibility":True,"opacity":1,"title":str(layers[i].name()),"className":"HSLayers.Layer.WMS","singleTile":True,"wmsMaxScale":0,"legends":[""],"maxResolution":None,"minResolution":0,"url": wmsUrl ,"params":{"LAYERS": str(layers[i].name()),"INFO_FORMAT":"application/vnd.ogc.gml","FORMAT":"image/png","FROMCRS":"EPSG:3857","VERSION":"1.3.0"},"ratio":1.5,"dimensions":{}})
+                #successful = successful + 1
+                #self.dlg.progressBar.setValue(self.dlg.progressBar.value()+step)
+ 
+                #self.importMap(x, "add", successful) 
+
+              
+            else:
+                self.postRequest(layers[i].name())
+                wmsStatus = 'PENDING'
+                j = 0
+                while ((wmsStatus == 'PENDING') and (j < 10)):
+                    print (self.URI+'/rest/'+self.laymanUsername+'/layers/'+str(layers[i].name()))
+                    response = requests.get(self.URI+'/rest/'+self.laymanUsername+'/layers/'+str(layers[i].name()), verify=False)
+                    res = self.fromByteToJson(response.content)
+                    try:
+                        wmsStatus = res['wms']['status']
+                    except:
+                        wmsStatus = "done"
+                    time.sleep(1)
+                    j = j + 1
+            
+
+                print(res)
+                try:
+                    wmsUrl = res['wms']['url']
+                except:
+                    wmsUrl = self.URI+'/geoserver/'+layers[i].name()+'/ows'
+                self.compositeList[x]['layers'].append({"metadata":{},"visibility":True,"opacity":1,"title":str(layers[i].name()),"className":"HSLayers.Layer.WMS","singleTile":True,"wmsMaxScale":0,"legends":[""],"maxResolution":None,"minResolution":0,"url": wmsUrl ,"params":{"LAYERS": str(layers[i].name()),"INFO_FORMAT":"application/vnd.ogc.gml","FORMAT":"image/png","FROMCRS":"EPSG:3857","VERSION":"1.3.0"},"ratio":1.5,"dimensions":{}})
+                successful = successful + 1
+                self.dlg.progressBar.setValue(self.dlg.progressBar.value()+step)
+ 
+                self.importMap(x, "add", successful) 
+    def getProgressBarStep(self, count):
+        return (100/count)
+
+    def deteteLayerFromComposite(self, x, position, name):   ## pro verzi s komboboxem   
+        
+        previousLayers = self.compositeList[x]['layers']         
+        self.compositeList[x]['layers'] = []  
+        for i in range (0,len(previousLayers)):
+            if (i != position):              
+               self.compositeList[x]['layers'].append(previousLayers[i])        
+        self.importMap(x, "del")
+        done = True
+        if (len(self.compositeList[x]['layers']) != 0 and len(self.compositeList[x]['layers']) != None):
+            for i in range (0, len(self.compositeList[x]['layers'])):
+                if (self.compositeList[x]['layers'][i]['params']['LAYERS'] == name):
+                    done = False
+        if (done and QgsProject.instance().mapLayersByName(name)):    ## kompozice může mít načtené vrstvy, které nejsou v canvasu
+            self.deleteLayerFromCanvas(name)    
+        
+    def importCleanComposite(self,x):
+        tempFile = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "compsite.json"
+        with open(tempFile, 'w') as outfile:  
+                    json.dump(self.compositeList[x], outfile)
+        with open(tempFile, 'rb') as f:
+                    d = json.load(f)        
+        files = {'file': (tempFile, open(tempFile, 'rb')),} 
+        data = { 'name' :  self.compositeList[x]['name'], 'title' : self.compositeList[x]['title'], 'description' : self.compositeList[x]['abstract']} 
+        print(self.URI+'/rest/'+self.laymanUsername+'/maps/')
+        #response = requests.post(self.URI+'/rest/'+self.laymanUsername+'/maps/', data = data, files=files, headers = self.authHeader, verify=False)
+        print(self.authHeader)
+        response = requests.post(self.URI+'/rest/'+self.laymanUsername+'/maps', files=files, data = data, headers = self.authHeader, verify=False)
+        
+        print(response.content)
+
+
+
+    def showProgressBar(self, bar):
+        bar = QProgressBar() 
+        bar.setRange(0,0) ## range 0,0 je nekonečný
+        self.showProgressBar(bar)
+        bar.show()
+        iface.mainWindow().statusBar().addWidget(bar)
+    def fromByteToJson(self, res):
+        pom = res
+        pom = pom.decode('utf_8')
+        pom = json.loads(pom)
+        return pom
+
+    def importMap(self, x, operation, s = 0): ##s je počet vrstev úspěšně nahraných na server   
+        if (s != 0):
+            self.dlg.progressBar.show() 
+            self.dlg.label_import.show()
+        tempFile = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "compsite.json"
+        
+        try:
+            existingLayers = self.isLayerInComposite(x)
+        except:
+            existingLayers = []        
+        successful = s
+        with open(tempFile, 'w') as outfile:  
+            json.dump(self.compositeList[x], outfile)
+        jsonPath = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "compsite.json"
+        with open(jsonPath, 'rb') as f:
+            d = json.load(f)
+
+        files = {'file': (jsonPath, open(jsonPath, 'rb')),} 
+        data = { 'name' :  self.compositeList[x]['name'], 'title' : self.compositeList[x]['title'], 'description' : self.compositeList[x]['abstract']} 
+        req = requests.get(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'])
+        mapCode = req.status_code ## test jestli vrstva na serveru existuje. Pokud ne = error 404
+        if (mapCode == 404):
+            if (operation == "add"):                
+                msgbox = QMessageBox(QMessageBox.Question, "Import Map", "Chcete přidat do kompozice "+str(successful)+" vrstev?") 
+            if (operation == "mod"): 
+                msgbox = QMessageBox(QMessageBox.Question, "Import Map", "Chcete opravdu provést změny v této kompozici?") 
+                self.dlg.close()
+                self.afterCloseEditMapDialog()
+                print(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'])       
+              
+                response = requests.delete(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'],headers = self.authHeader, verify=False)
+                print(response.content)
+                self.dlg.show()
+            if (operation == "del"):
+                msgbox = QMessageBox(QMessageBox.Question, "Import Map", "Chcete smazat vybranou vrstvu?")
+            msgbox.addButton(QMessageBox.Yes)
+            msgbox.addButton(QMessageBox.No)
+            msgbox.setDefaultButton(QMessageBox.No)
+            reply = msgbox.exec()
+            if (reply == QMessageBox.Yes):
+                response = requests.post(self.URI+'/rest/'+self.laymanUsername+'/maps', files=files, data = data, headers = self.authHeader, verify=False)
+                print(response.content)
+                data = response.content
+                self.dlg.progressBar.hide() 
+               # self.refreshItems()## refresh formuláře
+                if (operation != "mod"):
+                    self.refreshLayerList()
+                
+            else:
+                if (operation == "add"):
+                    self.dlg.progressBar.setValue(0)                
+     
+        else:
+            print(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'])       
+            files = {'file': (jsonPath, open(jsonPath, 'rb')),} 
+            response = requests.patch(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'], data = data, files=files, headers = self.authHeader, verify=False)
+            try:
+                self.refreshLayerList()
+            except:
+                ## nacházíme se v jiném formuláři, není co refreshovat
+                pass
+            #if (operation == "add"):
+            #    print(len(existingLayers))
+            #    msgbox = QMessageBox(QMessageBox.Question, "Layman", "Vybraná vrstva bude přidána do kompozice.")
+            #    #if(len(existingLayers) == 0):
+                    
+            #    #    #if (successful != 0):
+            #    #    msgbox = QMessageBox(QMessageBox.Question, "Layman", "Vybraná vrstva bude přidána do kompozice.")
+            #    #else:
+            #    #  #  msgbox = QMessageBox(QMessageBox.Question, "Import Map", "Kompozice již obsauje vrstvy: "+(', '.join(existingLayers))+". Chcete vybrané vrstvy opravdu znovu přidat?.")
+            #    #     msgbox = QMessageBox(QMessageBox.Question, "Layman", "Vybraná vrstva bude přidána do kompozice.")
+            #if (operation == "del"):
+            #    msgbox = QMessageBox(QMessageBox.Question, "Import Map", "Chcete smazat vybranou vrstvu?")
+            #if (operation == "mod"):
+            #    msgbox = QMessageBox(QMessageBox.Question, "Import Map", "Chcete uložit upravenou mapu?")
+            #msgbox.addButton(QMessageBox.Yes)
+            #msgbox.addButton(QMessageBox.No)
+            #msgbox.setDefaultButton(QMessageBox.No)
+            #reply = msgbox.exec()
+            #if (reply == QMessageBox.Yes):            
+            #    print(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'])       
+            #    files = {'file': (jsonPath, open(jsonPath, 'rb')),} 
+            #    response = requests.patch(self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name'], data = data, files=files, headers = self.authHeader, verify=False)
+   
+            #    try:
+            #        self.refreshLayerList()
+            #    except:
+            #        ## nacházíme se v jiném formuláři, není co refreshovat
+            #        pass
+            #if (reply == QMessageBox.No):
+                
+            #    self.compositeList = copy.deepcopy(self.compositeListOld)
+            #    #self.refreshItems()##refresh formulare
+               # self.refreshLayerList()
+        try: ## některé formuláře nemají progress bar
+            self.dlg.progressBar.hide() 
+            self.dlg.label_import.hide() 
+        except:
+            pass
+    def deleteLayer(self, layerName):
+        url = self.URI+'/rest/'+self.laymanUsername+"/layers/" + layerName
+        r = requests.delete(url)
+        print (r.content)
+    def getActiveLayer(self):
+        layer = self.iface.activeLayer()
+        return layer
+    
+    def createComposite(self, name, title):
+      #  if (name == "" or title == ""):
+        if (title == ""):
+            QMessageBox.information(None, "Message", "Není vyplněn titulek!")
+        else:
+            name = self.removeUnacceptableChars(title)
+            data = self.getEmptyComposite(name,title)
+            print (data)
+            self.compositeList.append(data)   
+            x = len(self.compositeList) - 1
+            self.importCleanComposite(x)
+            try:
+                self.refreshCompositeList()
+            except:
+                pass
+
+
+    def patchLayer(self, layer_name, data):
+        self.layerName = layer_name
+        self.json_export(layer_name)
+        sldPath = self.getTempPath(self.layerName).replace("geojson", "sld")
+        geoPath = self.getTempPath(self.layerName)
+        print(sldPath)
+        if(os.path.isfile(sldPath)): ## existuje sld?
+            files = [('file', open(geoPath, 'rb')), ('sld', open(sldPath, 'rb'))]
+            print("sld")
+        else:
+            files = {'file': (geoPath, open(geoPath, 'rb')),}  
+            print("ne sld")
+        url = self.URI+'/rest/'+self.laymanUsername+"/layers/" + layer_name
+        print(url)
+        r = requests.patch(url, files=files, data = data, headers = self.authHeader, verify=False)
+        print(r.content)
+
+    def getTempPath(self, name):
+
+        print (name)
+        if type(name) is tuple:
+            return (name[0] +  name[1])
+        else:
+            tempFile = tempfile.gettempdir() + os.sep + name +'.geojson'
+
+            return tempFile
+    def sendLayer(self):       
+        layer = self.getActiveLayer()      
+        if (layer == None):
+            QMessageBox.information(None, "Message", "Neexistuje žádná vrstva k uložení")
+        else:
+            self.json_export()
+            self.postRequest()
+    def getExistingLayers(self):
+        url = self.URI+'/rest/'+self.laymanUsername+"/layers"
+        r = requests.get(url = url) 
+        data = r.json()
+        for x in range(len(data)):
+            print(data[x]['name'])
+        return data
+    def checkExistingLayer(self, layerName):
+        layerName = self.removeUnacceptableChars(layerName)
+        url = self.URI+'/rest/'+self.laymanUsername+"/layers"
+        r = requests.get(url = url) 
+        data = r.json()
+        
+        pom = set()
+        for x in range(len(data)):
+            pom.add((data[x]['name']))
+        layerName = layerName.replace(" ", "_").lower()
+        print(layerName)
+        print(pom)
+        if (layerName in pom):
+            return True
+        else:
+            return False
+   
+    def removeUnacceptableChars(self, input):
+        input = input.replace("ř","r")
+        input = input.replace("š","s")
+        input = input.replace("ž","z")
+        input = input.replace("ů","u")
+        input = input.replace("ú","u")
+        input = input.replace(" ","_")
+        input = input.replace("é","e")
+        input = input.replace("í","i")
+        input = input.replace("á","a")
+        input = input.replace("ó","o")
+        input = input.replace("č","c")
+        input = input.replace("ď","d")
+        input = input.replace("ě","e")
+        input = input.replace("ť","t")
+        input = re.sub(r'[?|$|.|!]',r'',input)
+        input = input.lower()
+       # iface.messageBar().pushWidget(iface.messageBar().createMessage("Layman:", "Diacritics in name of layer was replaced."), Qgis.Success, duration=3)
+        return input
+
+    def test (self):
+        item = self.dlgGetLayers.items.currentItem().text()
+        print( item)
+    
+    def isLayerInComposite(self, x):      
+        layers =[]
+        layers.append(self.dlg.mMapLayerComboBox.currentLayer())
+        print (self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name']+'/file')
+        req = requests.get (self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name']+'/file')
+        data = req.json()
+       
+        print (data['abstract'])
+        print (len(self.compositeList[x]['layers']))
+        existingLayers = []
+        for i in range (0, len(data['layers'])):
+            for j in range (0, len(layers)):
+                if (data['layers'][i]['params']['LAYERS'] in layers[j].name() ):
+                    existingLayers.append(data['layers'][i]['params']['LAYERS'])
+
+        return existingLayers
+    def getLayerInCompositePosition(self, x):      
+        layers =[]
+        layers.append(self.dlg.mMapLayerComboBox.currentLayer())
+        print (self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name']+'/file')
+        req = requests.get (self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name']+'/file')
+        data = req.json()
+       
+        print (data['abstract'])
+        print (len(self.compositeList[x]['layers']))
+        existingLayers = []
+        j = 0
+        for i in range (0, len(data['layers'])):
+            for j in range (0, len(layers)):
+                if (data['layers'][i]['params']['LAYERS'] in layers[j].name() ):
+                  #  existingLayers.append(data['layers'][i]['params']['LAYERS'])
+                   j = i
+                   print("founded")
+
+        return j
+
+    def isRasterLayerInComposite(self, x, name):
+        req = requests.get (self.URI+'/rest/'+self.laymanUsername+'/maps/'+self.compositeList[x]['name']+'/file')
+        data = req.json()
+        existingLayers = []
+        for i in range (0, len(data['layers'])):
+            if (data['layers'][i]['params']['LAYERS'] ==  name ):
+                existingLayers.append(data['layers'][i]['params']['LAYERS'])
+        return existingLayers
+    
+    def addComposite(self, data, service, groupName = ''):      
+        #self.compositeList.append (data)
+        print(len(data['layers']))
+        for x in range(0, len(data['layers'])):        
+          #  repairUrl = self.convertUrlFromHex(data['layers'][x]['url'])  
+            repairUrl = self.URI+"/geoserver/"+self.laymanUsername+"/ows"
+            layerName = data['layers'][x]['params']['LAYERS']
+            format = data['layers'][x]['params']['FORMAT']
+           #  epsg = str(data['groups']['projection']).upper()
+            epsg = 'EPSG:4326' 
+            #abstract = data['data']['layers'][x]['params']['ABSTRACT']
+            wmsName = data['layers'][x]['params']['LAYERS']             
+            if service == 'WMS':         
+                self.loadWms(repairUrl, layerName, format,epsg, groupName)
+
+            if service == 'WFS':          
+                self.loadWfs(repairUrl, layerName, groupName)
+    def loadService(self, data, service, groupName = ''):     
+        
+        print(len(data['layers']))
+        for x in range(0, len(data['layers'])):        
+            #repairUrl = self.convertUrlFromHex(data['layers'][x]['url'])  
+            repairUrl = "http://layman.lesprojekt.cz/geoserver/"+self.laymanUsername+"/ows"
+            layerName = data['layers'][x]['params']['LAYERS']
+            format = data['layers'][x]['params']['FORMAT']
+           #  epsg = str(data['groups']['projection']).upper()
+            epsg = 'EPSG:4326' 
+            #abstract = data['data']['layers'][x]['params']['ABSTRACT']
+            wmsName = data['layers'][x]['params']['LAYERS']  
+            if self.checkLayerOnLayman(layerName):
+                if service == 'WMS':         
+                    self.loadWms(repairUrl, layerName, format,epsg, groupName)
+
+                if service == 'WFS':          
+                    self.loadWfs(repairUrl, layerName, groupName)
+            else:
+                QMessageBox.information(None, "Layman", "Layer: "+layerName + " is corrupted and will not be loaded.")
+                
+    def loadWms(self, url, layerName, format, epsg, groupName = ''):          
+        print(url)
+        urlWithParams = 'contextualWMSLegend=0&crs='+epsg+'&dpiMode=7&featureCount=10&format=image/png&layers='+layerName+'&styles=&url=' + url 
+        print(urlWithParams)
+        rlayer = QgsRasterLayer(urlWithParams, layerName, 'wms')
+        if (groupName != ''):
+            self.addWmsToGroup(groupName,rlayer)
+        else:
+            QgsProject.instance().addMapLayer(rlayer)
+
+    def loadWfs(self, url, layerName, groupName = ''):
+        epsg = 'EPSG:4326'        
+        uri = "http://layman.lesprojekt.cz/geoserver/"+self.laymanUsername+"/ows?srsname="+epsg+"&typename="+self.laymanUsername+":"+layerName+"&restrictToRequestBBOX=1&pagingEnabled=True &version=auto&request=GetFeature&service=WFS"
+        
+        print(uri)
+        vlayer = QgsVectorLayer(uri, layerName, "WFS")
+        print(vlayer.isValid())  
+        if (groupName != ''):
+            self.addWmsToGroup(groupName,vlayer)
+        else:
+            QgsProject.instance().addMapLayer(vlayer)
+    def addWmsToGroup(self, groupName, layer):
+        root = QgsProject.instance().layerTreeRoot()
+        group = root.findGroup(groupName)
+        if not(group):
+            group = root.addGroup(groupName)           
+        QgsProject.instance().addMapLayer(layer,False)
+        group.insertChildNode(1,QgsLayerTreeLayer(layer))         
+
+    def convertUrlFromHex(self, url):
+        url = url.replace('%3A',':')
+        url = url.replace('%2F','/')
+        url = url.replace('%3F','?')
+        url = url.replace('%3D','=')
+        url = url.replace('%26','&') 
+        return url
+
+    def checkEpsg(self, name):
+        ret = False
+        layer = QgsProject.instance().mapLayersByName(name)
+        layerCRS = layer[0].crs().authid()
+        if ((layerCRS == 'EPSG:4326') or (layerCRS == 'EPSG:3857')):
+            ret = True
+        return ret
+
+    def registerLayer(self, name):
+        sldPath = self.getTempPath(name).replace("geojson", "sld")
+        geoPath = self.getTempPath(name)
+
+        url = "http://layman.lesprojekt.cz/rest/"+self.laymanUsername+"/layers"
+                             
+        files = {'sld': (sldPath, open(sldPath, 'rb')),} # nahrávám sld
+        payload = {        
+            'file': name+".geojson"
+            }    
+        response = requests.request("POST", url, files = files, data=payload, headers = self.authHeader)    
+       # print(response.text)
+
+    def read_in_chunks(self, file_object): ## cca 1MB chunk převzato z laymana test klienta
+        chunk_size=self.CHUNK_SIZE
+        while True:
+            data = file_object.read(chunk_size)
+            if not data:
+                break
+            yield data
+    
+    def postInChunks(self, layer_name, reqType):
+        print(reqType)
+        if (reqType == "patch"):
+            url = self.URI+'/rest/'+self.laymanUsername+'/layers/'+layer_name
+            r = requests.delete(url,headers = self.authHeader)
+           # print(r.content)
+         
+        self.registerLayer(layer_name)
+
+        filePath = os.path.join(tempfile.gettempdir(), "atlas_chunks" ) ## chunky se ukládají do adresáře v tempu
+        
+        if not (os.path.exists(filePath)):
+            os.mkdir(filePath)
+        file = self.getTempPath(layer_name) 
+        f = open(file, 'rb')
+        arr = []
+        for piece in self.read_in_chunks(f):
+            arr.append(piece)
+     
+        url = self.URI+'/rest/'+self.laymanUsername+'/layers/'+layer_name+'/chunk'     
+        resumableFilename = layer_name+'.geojson'
+        layman_original_parameter = "file"  
+        resumableTotalChunks = len(arr)
+
+        for i in range (1, len(arr)+1):  ##chunky jsou počítané od 1 proto +1  
+            print("chunk" + str(i))
+            file = arr[i-1] # rozsekaná část souboru
+            resumableChunkNumber = i  # cislo casti
+            payload = {
+            'file' : "chunk"+str(i)+".geojson",
+            'resumableFilename': resumableFilename,
+            'layman_original_parameter': layman_original_parameter,
+            'resumableChunkNumber': i,
+            'resumableTotalChunks': resumableTotalChunks
+            } 
+         
+            f = open(filePath + os.sep+"chunk"+str(i)+".geojson", "wb")
+            f.write(bytearray(arr[i-1]))
+            f.close()              
+            files = {'file': (layer_name+".geojson", open(filePath +os.sep+ "chunk"+str(i)+".geojson", 'rb')),}              
+            response = requests.post(url, files = files, data=payload, headers = self.authHeader)
+
+            print(response.content)
+
+
+############################################# auth part############################
+
+    def startThread(self): 
+        self.thread1 = threading.Thread(target=self.refreshToken)
+        self.thread1.start()
+
+    def refreshToken(self):
+        #self.expires_in = 60
+        path = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "tsts.txt" 
+        i = 0
+        tokenEndpoint = "https://www.agrihub.cz/o/oauth2/token"
+        while (i < self.expires_in):        
+            f = open(path, "a")
+            f.write(str(i))
+
+            f.close()            
+            time.sleep(1)         
+            if i == self.expires_in - 4:
+            
+               
+                data = {'grant_type':'refresh_token',
+                        'refresh_token': self.refresh_token,
+                        'client_id':'id-3462f94b-875c-9185-4ced-b69841f24b3', 
+                        'redirect_uri':'http://localhost:3000/client/authn/oauth2-liferay/callback', 
+                        'code_verifier':'test'
+                        } 
+                
+                r = requests.post(url = tokenEndpoint, data = data, headers = self.authHeader) 
+                res = self.fromByteToJson(r.content)
+                self.access_token = res['access_token']
+                self.refresh_token = res['refresh_token']
+                self.expires_in = res['expires_in']
+                print(self.access_token)
+                self.setAuthHeader()
+                i = 0
+            else:
+                i += 1
+        
+        
+        
+        
+
+
+
+    
+    def authOptained (self):        
+        self.dlg.pushButton_Continue.setEnabled(True)
+
+        self.menu_Connection.setEnabled(True)
+        self.menu_saveLocalFile.setEnabled(True)
+        self.menu_loadJson.setEnabled(True)
+        self.menu_ImportLayerDialog.setEnabled(True)
+        self.menu_AddLayerDialog.setEnabled(True) 
+        self.menu_AddMapDialog.setEnabled(True)       
+        self.menu_ImportLayerDialog.setEnabled(True)
+        self.menu_ImportMapDialog.setEnabled(True)       
+     #   self.menu_DeleteMapDialog.setEnabled(True)
+    #    self.menu_CreateCompositeDialog.setEnabled(True)
+        self.menu_UserInfoDialog.setEnabled(True)
+        self.textbox.setText("Layman: Logged user")
+
+    def getCodeVerifier(self):
+        code_verifier = base64.urlsafe_b64encode(os.urandom(40)).decode('utf-8')
+        code_verifier = re.sub('[^a-zA-Z0-9]+', '', code_verifier)
+        self.code_verifier = code_verifier
+        return (code_verifier)
+      
+    def getCodeChallenge(self, code_verifier):
+        code_challenge = hashlib.sha256(code_verifier.encode('utf-8')).digest()
+        code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8')
+        code_challenge = code_challenge.replace('=', '')
+        self.code_challenge = code_challenge
+        return (code_challenge)        
+
+    def printVariables(self):
+        print (self.access_token)
+        print(self.refresh_token)
+        print(self.authHeader)
+        print(self.laymanUsername)
+
+    def getAuthCode(self):
+        path = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "auth.txt"        
+        f = open(path, "r")
+        ret =  f.read()
+        f.close()
+        return ret
+
+    def getToken(self):
+        self.saveIni()
+
+        tokenEndpoint = "https://www.agrihub.cz/o/oauth2/token"
+        # data to be sent to api 
+        data = {'grant_type':'authorization_code', 
+                'client_id': self.client_id, 
+                'redirect_uri':'http://localhost:3000/client/authn/oauth2-liferay/callback', 
+                'code_verifier': self.code_verifier, 
+                'code': self.getAuthCode()} 
+  
+        # sending post request and saving response as response object 
+        r = requests.post(url = tokenEndpoint, data = data, headers = self.authHeader) 
+        res = self.fromByteToJson(r.content)
+        print (res)
+        try:
+            print(res['access_token'])
+            print(res['expires_in'])
+            print(res['refresh_token'])
+        except:
+            QMessageBox.information(None, "Message", "Autorization was not sucessfull! Please try it again.")
+            return
+        self.access_token = res['access_token']
+        self.refresh_token = res['refresh_token']
+        self.expires_in = res['expires_in']
+        self.setAuthHeader()
+        data ={
+            'access_token': res['access_token'], 
+            'refresh_token': res['refresh_token'],
+            'expires_in':res['expires_in']
+            }
+        path = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "tokens.json"        
+        with open(path, 'w') as outfile:
+            json.dump(data, outfile)
+        self.startThread()
+        self.registerUserIfNotExists()
+        self.dlg.close()
+        
+    def setAuthHeader(self):
+        self.authHeader ={
+          "Authorization": "Bearer " + self.access_token, 
+          "AuthorizationIssUrl" : 'https://www.agrihub.cz/o/oauth2/authorize'
+        } 
+        
+    def registerUserIfNotExists(self):
+        userEndpoint = "http://layman.lesprojekt.cz/rest/current-user"
+        #self.laymanUsername = self.dlg.lineEdit_userName.text()
+        id = self.client_id.replace('-', '')
+        user = {'username':self.Agrimail}  
+        #user =  self.Agrimail        
+        print("authheader: "+ str(self.authHeader))
+        r = requests.patch(url = userEndpoint, data = user, headers = self.authHeader)
+        res = r.text
+        res = self.fromByteToJson(r.content)
+        print (res)
+        print(user)
+        print(res)
+        try:
+           # if res['message'] == 'User already reserved username.': # res['code'] == 34, code 35 je pokud již jiný uživatel má účet, který chceme registrovat
+           if res['code'] == 34: # res['code'] == 34, code 35 je pokud již jiný uživatel má účet, který chceme registrovat (code 35 pravděpodobně nemůže nastat)
+
+                print("user exists")
+                self.laymanUsername = res['detail']['username']
+            #self.laymanUsername = res['username']
+            #else:
+            #    self.laymanUsername =  user['username']
+        except:
+
+            print("creating new user: " + res['username'])
+            self.laymanUsername =  res['username']
+        #API_ENDPOINT = "http://layman.lesprojekt.cz/rest/current-user"
+        #headers ={
+        #  "Authorization": "Bearer "+ self.access_token, 
+        #  "AuthorizationIssUrl" : 'https://www.agrihub.cz/o/oauth2/authorize'
+        #} 
+
+
+    def openAuthLiferayUrl(self):
+        
+        self.getCodeChallenge(self.getCodeVerifier()) ##generování kódů
+        self.client_id = self.dlg.lineEdit_AgriID.text()
+        path = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "auth.txt" 
+        self.watcher = QFileSystemWatcher()
+        self.watcher.addPath(path)
+        self.watcher.fileChanged.connect(self.authOptained)
+      
+        
+            #################       
+     
+        print ("##### flask server is starting #####")                     
+        thread = StartFlaskDaemon()
+        thread.daemon = True
+        thread.start()       
+        url = 'https://www.agrihub.cz/o/oauth2/authorize?response_type=code&client_id='+self.client_id+'&redirect_uri=http%3A%2F%2Flocalhost:3000%2Fclient%2Fauthn%2Foauth2-liferay%2Fcallback&code_challenge='+self.code_challenge ##n4bQgYhMfWWaL-qgxVrQFaO_TxsrC4Is0V1sFbDwCgg'
+        webbrowser.open(url, new=2)
+
+    def saveIni(self):
+        file =  os.getenv("HOME") + os.sep + ".layman" + os.sep + 'layman_user.INI'  
+        dir = os.getenv("HOME") + os.sep + ".layman"
+        if not (os.path.isdir(dir)):
+            try:  
+                os.mkdir(dir)
+            except OSError:  
+                print ("vytváření adresáře selhalo")
+        config = configparser.ConfigParser()
+        config['DEFAULT']['login'] = self.Agrimail
+        config['DEFAULT']['id'] = self.client_id
+        
+
+        with open(file, 'w') as configfile:
+            config.write(configfile)        
+    def loadIni(self):
+        file =  os.getenv("HOME") + os.sep + ".layman" + os.sep +'layman_user.INI'        
+        config = configparser.ConfigParser()
+        config.read(file)
+        return config   
+    def run(self):
+        """Run method that loads and starts the plugin"""
+
+        if not self.pluginIsActive:
+            self.pluginIsActive = True
+
+            #print "** STARTING Atlas"
+
+            # dockwidget may not exist if:
+            #    first run of plugin
+            #    removed on close (see self.onClosePlugin method)
+            if self.dockwidget == None:
+                # Create the dockwidget (after translation) and keep reference
+                self.dockwidget = AtlasDockWidget()
+
+            
+            # connect to provide cleanup on closing of dockwidget
+            self.dockwidget.closingPlugin.connect(self.onClosePlugin)            
+            self.dockwidget.pushButton.clicked.connect(self.sendLayer)   
+            self.dockwidget.pushButton_2.clicked.connect(self.loadLocalFile) 
+            self.dockwidget.pushButton_3.clicked.connect(self.saveLocalFile)
+            self.dockwidget.pushButton_getLayers.clicked.connect(self.run_getLayer)            
+            self.dlgGetLayers.pushButtonxx.clicked.connect(lambda: print(self.dlgGetLayers.items.currentItem().text()))          
+            
+            # show the dockwidget
+            # TODO: fix to allow choice of dock location
+            self.iface.addDockWidget(Qt.TopDockWidgetArea, self.dockwidget)
+            self.dockwidget.show()
+            
+class StartFlaskDaemon(threading.Thread):
+    def run(self):
+        from subprocess import Popen, PIPE
+        import platform
+        import sys
+        from pathlib import Path
+        d= os.path.dirname(Path(__file__).absolute()) + os.sep+"flask_listener" + os.sep + "flask_listener.py" 
+       
+        if platform.system() == 'Windows':
+            process = subprocess.Popen(["python", d],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+        else:
+            process = subprocess.Popen(["python " + d],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+        stdout, stderr = process.communicate()
+        print (stdout, stderr)  
+        '''Start your thread here'''
+        

+ 50 - 0
Atlas_dockwidget.py

@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ AtlasDockWidget
+                                 A QGIS plugin
+ Atlas
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-02-15
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by jan vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import QtGui, QtWidgets, uic
+from PyQt5.QtCore import pyqtSignal
+
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'Atlas_dockwidget_base.ui'))
+
+
+class AtlasDockWidget(QtWidgets.QDockWidget, FORM_CLASS):
+
+    closingPlugin = pyqtSignal()
+
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(AtlasDockWidget, self).__init__(parent)
+        # Set up the user interface from Designer.
+        # After setupUI you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://doc.qt.io/qt-5/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)
+
+    def closeEvent(self, event):
+        self.closingPlugin.emit()
+        event.accept()

+ 51 - 0
Atlas_dockwidget_base.ui

@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>AtlasDockWidgetBase</class>
+ <widget class="QDockWidget" name="AtlasDockWidgetBase">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>558</width>
+    <height>498</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Atlas</string>
+  </property>
+  <widget class="QWidget" name="dockWidgetContents">
+   <layout class="QGridLayout" name="gridLayout">
+    <item row="0" column="0">
+     <widget class="QPushButton" name="pushButton">
+      <property name="text">
+       <string>Export JSON</string>
+      </property>
+     </widget>
+    </item>
+    <item row="1" column="0">
+     <widget class="QPushButton" name="pushButton_2">
+      <property name="text">
+       <string>Nacti json</string>
+      </property>
+     </widget>
+    </item>
+    <item row="2" column="0">
+     <widget class="QPushButton" name="pushButton_3">
+      <property name="text">
+       <string>Do souboru</string>
+      </property>
+     </widget>
+    </item>
+    <item row="3" column="0">
+     <widget class="QPushButton" name="pushButton_getLayers">
+      <property name="text">
+       <string>Načti vzdálené vrstvy</string>
+      </property>
+     </widget>
+    </item>
+   </layout>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 244 - 0
Makefile

@@ -0,0 +1,244 @@
+#/***************************************************************************
+# Atlas
+#
+# Atlas
+#							 -------------------
+#		begin				: 2019-02-15
+#		git sha				: $Format:%H$
+#		copyright			: (C) 2019 by jan vrobel
+#		email				: vrobel.jan@seznam.cz
+# ***************************************************************************/
+#
+#/***************************************************************************
+# *																		 *
+# *   This program is free software; you can redistribute it and/or modify  *
+# *   it under the terms of the GNU General Public License as published by  *
+# *   the Free Software Foundation; either version 2 of the License, or	 *
+# *   (at your option) any later version.								   *
+# *																		 *
+# ***************************************************************************/
+
+#################################################
+# Edit the following to match your sources lists
+#################################################
+
+
+#Add iso code for any locales you want to support here (space separated)
+# default is no locales
+# LOCALES = af
+LOCALES =
+
+# If locales are enabled, set the name of the lrelease binary on your system. If
+# you have trouble compiling the translations, you may have to specify the full path to
+# lrelease
+#LRELEASE = lrelease
+#LRELEASE = lrelease-qt4
+
+
+# translation
+SOURCES = \
+	__init__.py \
+	Atlas.py Atlas_dockwidget.py
+
+PLUGINNAME = Atlas
+
+PY_FILES = \
+	__init__.py \
+	Atlas.py Atlas_dockwidget.py
+
+UI_FILES = Atlas_dockwidget_base.ui
+
+EXTRAS = metadata.txt icon.png
+
+EXTRA_DIRS =
+
+COMPILED_RESOURCE_FILES = resources.py
+
+PEP8EXCLUDE=pydev,resources.py,conf.py,third_party,ui
+
+# QGISDIR points to the location where your plugin should be installed.
+# This varies by platform, relative to your HOME directory:
+#	* Linux:
+#	  .local/share/QGIS/QGIS3/profiles/default/python/plugins/
+#	* Mac OS X:
+#	  Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins
+#	* Windows:
+#	  AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins'
+
+QGISDIR=C:\Users\Honza\AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins
+
+#################################################
+# Normally you would not need to edit below here
+#################################################
+
+HELP = help/build/html
+
+PLUGIN_UPLOAD = $(c)/plugin_upload.py
+
+RESOURCE_SRC=$(shell grep '^ *<file' resources.qrc | sed 's@</file>@@g;s/.*>//g' | tr '\n' ' ')
+
+.PHONY: default
+default:
+	@echo While you can use make to build and deploy your plugin, pb_tool
+	@echo is a much better solution.
+	@echo A Python script, pb_tool provides platform independent management of
+	@echo your plugins and runs anywhere.
+	@echo You can install pb_tool using: pip install pb_tool
+	@echo See https://g-sherman.github.io/plugin_build_tool/ for info. 
+
+compile: $(COMPILED_RESOURCE_FILES)
+
+%.py : %.qrc $(RESOURCES_SRC)
+	pyrcc5 -o $*.py  $<
+
+%.qm : %.ts
+	$(LRELEASE) $<
+
+test: compile transcompile
+	@echo
+	@echo "----------------------"
+	@echo "Regression Test Suite"
+	@echo "----------------------"
+
+	@# Preceding dash means that make will continue in case of errors
+	@-export PYTHONPATH=`pwd`:$(PYTHONPATH); \
+		export QGIS_DEBUG=0; \
+		export QGIS_LOG_FILE=/dev/null; \
+		nosetests -v --with-id --with-coverage --cover-package=. \
+		3>&1 1>&2 2>&3 3>&- || true
+	@echo "----------------------"
+	@echo "If you get a 'no module named qgis.core error, try sourcing"
+	@echo "the helper script we have provided first then run make test."
+	@echo "e.g. source run-env-linux.sh <path to qgis install>; make test"
+	@echo "----------------------"
+
+deploy: compile doc transcompile
+	@echo
+	@echo "------------------------------------------"
+	@echo "Deploying plugin to your .qgis2 directory."
+	@echo "------------------------------------------"
+	# The deploy  target only works on unix like operating system where
+	# the Python plugin directory is located at:
+	# $HOME/$(QGISDIR)/python/plugins
+	mkdir -p $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+	cp -vf $(PY_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+	cp -vf $(UI_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+	cp -vf $(COMPILED_RESOURCE_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+	cp -vf $(EXTRAS) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+	cp -vfr i18n $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+	cp -vfr $(HELP) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)/help
+	# Copy extra directories if any
+	(foreach EXTRA_DIR,(EXTRA_DIRS), cp -R (EXTRA_DIR) (HOME)/(QGISDIR)/python/plugins/(PLUGINNAME)/;)
+
+
+# The dclean target removes compiled python files from plugin directory
+# also deletes any .git entry
+dclean:
+	@echo
+	@echo "-----------------------------------"
+	@echo "Removing any compiled python files."
+	@echo "-----------------------------------"
+	find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname "*.pyc" -delete
+	find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname ".git" -prune -exec rm -Rf {} \;
+
+
+derase:
+	@echo
+	@echo "-------------------------"
+	@echo "Removing deployed plugin."
+	@echo "-------------------------"
+	rm -Rf $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+
+zip: deploy dclean
+	@echo
+	@echo "---------------------------"
+	@echo "Creating plugin zip bundle."
+	@echo "---------------------------"
+	# The zip target deploys the plugin and creates a zip file with the deployed
+	# content. You can then upload the zip file on http://plugins.qgis.org
+	rm -f $(PLUGINNAME).zip
+	cd $(HOME)/$(QGISDIR)/python/plugins; zip -9r $(CURDIR)/$(PLUGINNAME).zip $(PLUGINNAME)
+
+package: compile
+	# Create a zip package of the plugin named $(PLUGINNAME).zip.
+	# This requires use of git (your plugin development directory must be a
+	# git repository).
+	# To use, pass a valid commit or tag as follows:
+	#   make package VERSION=Version_0.3.2
+	@echo
+	@echo "------------------------------------"
+	@echo "Exporting plugin to zip package.	"
+	@echo "------------------------------------"
+	rm -f $(PLUGINNAME).zip
+	git archive --prefix=$(PLUGINNAME)/ -o $(PLUGINNAME).zip $(VERSION)
+	echo "Created package: $(PLUGINNAME).zip"
+
+upload: zip
+	@echo
+	@echo "-------------------------------------"
+	@echo "Uploading plugin to QGIS Plugin repo."
+	@echo "-------------------------------------"
+	$(PLUGIN_UPLOAD) $(PLUGINNAME).zip
+
+transup:
+	@echo
+	@echo "------------------------------------------------"
+	@echo "Updating translation files with any new strings."
+	@echo "------------------------------------------------"
+	@chmod +x scripts/update-strings.sh
+	@scripts/update-strings.sh $(LOCALES)
+
+transcompile:
+	@echo
+	@echo "----------------------------------------"
+	@echo "Compiled translation files to .qm files."
+	@echo "----------------------------------------"
+	@chmod +x scripts/compile-strings.sh
+	@scripts/compile-strings.sh $(LRELEASE) $(LOCALES)
+
+transclean:
+	@echo
+	@echo "------------------------------------"
+	@echo "Removing compiled translation files."
+	@echo "------------------------------------"
+	rm -f i18n/*.qm
+
+clean:
+	@echo
+	@echo "------------------------------------"
+	@echo "Removing uic and rcc generated files"
+	@echo "------------------------------------"
+	rm $(COMPILED_UI_FILES) $(COMPILED_RESOURCE_FILES)
+
+doc:
+	@echo
+	@echo "------------------------------------"
+	@echo "Building documentation using sphinx."
+	@echo "------------------------------------"
+	cd help; make html
+
+pylint:
+	@echo
+	@echo "-----------------"
+	@echo "Pylint violations"
+	@echo "-----------------"
+	@pylint --reports=n --rcfile=pylintrc . || true
+	@echo
+	@echo "----------------------"
+	@echo "If you get a 'no module named qgis.core' error, try sourcing"
+	@echo "the helper script we have provided first then run make pylint."
+	@echo "e.g. source run-env-linux.sh <path to qgis install>; make pylint"
+	@echo "----------------------"
+
+
+# Run pep8 style checking
+#http://pypi.python.org/pypi/pep8
+pep8:
+	@echo
+	@echo "-----------"
+	@echo "PEP8 issues"
+	@echo "-----------"
+	@pep8 --repeat --ignore=E203,E121,E122,E123,E124,E125,E126,E127,E128 --exclude $(PEP8EXCLUDE) . || true
+	@echo "-----------"
+	@echo "Ignored in PEP8 check:"
+	@echo $(PEP8EXCLUDE)

+ 42 - 0
README.html

@@ -0,0 +1,42 @@
+<html>
+<body>
+<h3>Plugin Builder Results</h3>
+
+Congratulations! You just built a plugin for QGIS!<br/><br />
+
+<div id='help' style='font-size:.9em;'>
+Your plugin <b>Atlas</b> was created in:<br>
+&nbsp;&nbsp;<b>C:/Program Files/QGIS 3.4/apps/qgis/python/plugins\atlas</b>
+<p>
+Your QGIS plugin directory is located at:<br>
+&nbsp;&nbsp;<b>C:/Users/Honza/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins</b>
+<p>
+<h3>What's Next</h3>
+<ol>
+    <li>In your plugin directory, compile the resources file using pyrcc5 (simply run <b>make</b> if you have automake or use <b>pb_tool</b>)
+    <li>Test the generated sources using <b>make test</b> (or run tests from your IDE)
+    <li>Copy the entire directory containing your new plugin to the QGIS plugin directory (see Notes below)
+    <li>Test the plugin by enabling it in the QGIS plugin manager
+    <li>Customize it by editing the implementation file <b>Atlas.py</b>
+    <li>Create your own custom icon, replacing the default <b>icon.png</b>
+    <li>Modify your user interface by opening <b>Atlas_dockwidget_base.ui</b> in Qt Designer
+</ol>
+Notes:
+<ul>
+    <li>You can use the <b>Makefile</b> to compile and deploy when you
+        make changes. This requires GNU make (gmake). The Makefile is ready to use, however you 
+        will have to edit it to add addional Python source files, dialogs, and translations.
+    <li>You can also use <b>pb_tool</b> to compile and deploy your plugin. Tweak the <i>pb_tool.cfg</i> file included with your plugin as you add files. Install <b>pb_tool</b> using 
+        <i>pip</i> or <i>easy_install</i>. See <b>http://loc8.cc/pb_tool</b> for more information.
+</ul>
+</div>
+<div style='font-size:.9em;'>
+<p>
+For information on writing PyQGIS code, see <b>http://loc8.cc/pyqgis_resources</b> for a list of resources.
+</p>
+</div>
+<p>
+&copy;2011-2018 GeoApt LLC - geoapt.com 
+</p>
+</body>
+</html>

+ 32 - 0
README.md

@@ -0,0 +1,32 @@
+# QGIS Client usable for importing map layers to Layman server  
+
+## OAuth2 login
+For usage of this plugin is needed account at www.agrihub.cz and agrihub ID. There is implemented OAuth2 authentification. Authentization is processed in Agrihub login form. There is user redirected.
+Email in plugin part is used as name for creating new Layman user if not exists. Authentication is valid only 10 minutes. Due this fact plugin every 10 minutes renew authentication tokens.    
+
+## After sucessfull autentization functions are unlocked and you are able to:
+### Load, Save vector layers in JSON format on local pc.    
+It provides simple forms for loading data. SLD file with symbology is also stored with same name like JSON file.
+
+### Import vector layer to Layman server. 
+In case size of layer is bigger than 1MB is layer automaticaly parted and send asynchronously. It is usable for bigger layers when importing fails. Plugin is able to establish uploading at point of failure. 
+EPSG: 4326 is allowed.
+From every layer is generated and imported SLD file, that keeps layer symbology. 
+
+### Load existing layer from Layman to QGIS.  
+Layers are loaded as WMS service to QGIS layer tree. Layer thumbnail is loaded into form. 
+
+### Create map composite and save to Layman server.   
+For creating composite is necessary fill all mandatory fields (name, title, description). This information is stored in composition file. There are also required specify the extent of the map. Extend can be automatically assumed from existing layer. 
+
+### Add, delete layers to map composite.  
+User can use new local layers and also existing layers in Layman. For working with compositions is prepaired main form with all functionalities.
+
+### Delete map composites from memory/server.  
+
+### Load all map composites to QGIS.  
+After loading existing composition from Layman are layers ordered to group in QGIS layer tree. One composition can be loaded only once. Composition name is unique. Map thumbnail is loaded into form. 
+ 
+
+ 
+

+ 32 - 0
README.txt

@@ -0,0 +1,32 @@
+Plugin Builder Results
+
+Your plugin Atlas was created in:
+    C:/Program Files/QGIS 3.4/apps/qgis/python/plugins\atlas
+
+Your QGIS plugin directory is located at:
+    C:/Users/Honza/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins
+
+What's Next:
+
+  * Copy the entire directory containing your new plugin to the QGIS plugin
+    directory
+
+  * Compile the resources file using pyrcc5
+
+  * Run the tests (``make test``)
+
+  * Test the plugin by enabling it in the QGIS plugin manager
+
+  * Customize it by editing the implementation file: ``Atlas.py``
+
+  * Create your own custom icon, replacing the default icon.png
+
+  * Modify your user interface by opening Atlas_dockwidget_base.ui in Qt Designer
+
+  * You can use the Makefile to compile your Ui and resource files when
+    you make changes. This requires GNU make (gmake)
+
+For more information, see the PyQGIS Developer Cookbook at:
+http://www.qgis.org/pyqgis-cookbook/index.html
+
+(C) 2011-2018 GeoApt LLC - geoapt.com

+ 36 - 0
__init__.py

@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ Atlas
+                                 A QGIS plugin
+ Atlas
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-02-15
+        copyright            : (C) 2019 by jan vrobel
+        email                : vrobel.jan@seznam.cz
+        git sha              : $Format:%H$
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+ This script initializes the plugin, making it known to QGIS.
+"""
+
+
+# noinspection PyPep8Naming
+def classFactory(iface):  # pylint: disable=invalid-name
+    """Load Atlas class from file Atlas.
+
+    :param iface: A QGIS interface instance.
+    :type iface: QgsInterface
+    """
+    #
+    from .Atlas import Atlas
+    return Atlas(iface)

BIN
__pycache__/Atlas.cpython-37.pyc


BIN
__pycache__/Atlas_dockwidget.cpython-37.pyc


BIN
__pycache__/__init__.cpython-37.pyc


BIN
__pycache__/dlg_ConnectionManager.cpython-37.pyc


BIN
__pycache__/dlg_GetLayers.cpython-37.pyc


BIN
__pycache__/dlg_addLayer.cpython-37.pyc


BIN
__pycache__/dlg_addMap.cpython-37.pyc


BIN
__pycache__/dlg_createComposite.cpython-37.pyc


BIN
__pycache__/dlg_deleteLayerFromMap.cpython-37.pyc


BIN
__pycache__/dlg_deleteMap.cpython-37.pyc


BIN
__pycache__/dlg_editMap.cpython-37.pyc


BIN
__pycache__/dlg_importLayer.cpython-37.pyc


BIN
__pycache__/dlg_importMap.cpython-37.pyc


BIN
__pycache__/dlg_userInfo.cpython-37.pyc


BIN
__pycache__/flaskServer.cpython-37.pyc


BIN
__pycache__/flaskServer2.cpython-37.pyc


BIN
__pycache__/ogr2ogr.cpython-37.pyc


BIN
__pycache__/resources.cpython-37.pyc


+ 44 - 0
dlg_ConnectionManager.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_ConnectionManager.ui'))
+
+
+class ConnectionManagerDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(ConnectionManagerDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 150 - 0
dlg_ConnectionManager.ui

@@ -0,0 +1,150 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>635</width>
+    <height>186</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>635</width>
+    <height>186</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>635</width>
+    <height>186</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Layman</string>
+  </property>
+  <widget class="QLineEdit" name="lineEdit_AgriID">
+   <property name="enabled">
+    <bool>true</bool>
+   </property>
+   <property name="geometry">
+    <rect>
+     <x>155</x>
+     <y>57</y>
+     <width>351</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>id-3462f94b-875c-9185-4ced-b69841f24b3</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_APIKey">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>57</y>
+     <width>111</width>
+     <height>19</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Agrihub ID:</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_Connect">
+   <property name="geometry">
+    <rect>
+     <x>155</x>
+     <y>97</y>
+     <width>111</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Login</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>394</x>
+     <y>97</y>
+     <width>111</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_Continue">
+   <property name="geometry">
+    <rect>
+     <x>279</x>
+     <y>97</y>
+     <width>101</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Continue</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_ttt">
+   <property name="geometry">
+    <rect>
+     <x>154</x>
+     <y>137</y>
+     <width>88</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>test</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_APIKey_2">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>22</y>
+     <width>121</width>
+     <height>19</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Agrihub login:</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_userName">
+   <property name="enabled">
+    <bool>true</bool>
+   </property>
+   <property name="geometry">
+    <rect>
+     <x>155</x>
+     <y>20</y>
+     <width>351</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>@lesprojekt.cz</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_GetLayers.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_GetLayers.ui'))
+
+
+class GetLayersDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(GetLayersDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 94 - 0
dlg_GetLayers.ui

@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>CartoDBDialogBase</class>
+ <widget class="QDialog" name="CartoDBDialogBase">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>400</width>
+    <height>300</height>
+   </rect>
+  </property>
+  <property name="focusPolicy">
+   <enum>Qt::ClickFocus</enum>
+  </property>
+  <property name="windowTitle">
+   <string>Atlas</string>
+  </property>
+  <widget class="QDialogButtonBox" name="button_box">
+   <property name="geometry">
+    <rect>
+     <x>30</x>
+     <y>240</y>
+     <width>341</width>
+     <height>32</height>
+    </rect>
+   </property>
+   <property name="orientation">
+    <enum>Qt::Horizontal</enum>
+   </property>
+   <property name="standardButtons">
+    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label">
+   <property name="geometry">
+    <rect>
+     <x>30</x>
+     <y>10</y>
+     <width>111</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Existing layers:</string>
+   </property>
+  </widget>
+  <widget class="QListWidget" name="items">
+   <property name="geometry">
+    <rect>
+     <x>30</x>
+     <y>50</y>
+     <width>291</width>
+     <height>141</height>
+    </rect>
+   </property>
+   <property name="selectionMode">
+    <enum>QAbstractItemView::NoSelection</enum>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButtonxx">
+   <property name="geometry">
+    <rect>
+     <x>110</x>
+     <y>200</y>
+     <width>93</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>PushButton</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections>
+  <connection>
+   <sender>button_box</sender>
+   <signal>rejected()</signal>
+   <receiver>CartoDBDialogBase</receiver>
+   <slot>reject()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>20</x>
+     <y>20</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>20</x>
+     <y>20</y>
+    </hint>
+   </hints>
+  </connection>
+ </connections>
+</ui>

+ 44 - 0
dlg_addLayer.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_addLayer.ui'))
+
+
+class AddLayerDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(AddLayerDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 149 - 0
dlg_addLayer.ui

@@ -0,0 +1,149 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>716</width>
+    <height>410</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>716</width>
+    <height>410</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>716</width>
+    <height>410</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Layman - Layers</string>
+  </property>
+  <widget class="QPushButton" name="pushButton">
+   <property name="geometry">
+    <rect>
+     <x>190</x>
+     <y>360</y>
+     <width>141</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Load WMS</string>
+   </property>
+  </widget>
+  <widget class="QTreeWidget" name="treeWidget">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>10</y>
+     <width>331</width>
+     <height>341</height>
+    </rect>
+   </property>
+   <column>
+    <property name="text">
+     <string>Layer</string>
+    </property>
+   </column>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>450</x>
+     <y>360</y>
+     <width>131</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_thumbnail">
+   <property name="geometry">
+    <rect>
+     <x>416</x>
+     <y>50</y>
+     <width>200</width>
+     <height>200</height>
+    </rect>
+   </property>
+   <property name="frameShape">
+    <enum>QFrame::Box</enum>
+   </property>
+   <property name="text">
+    <string/>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_2">
+   <property name="geometry">
+    <rect>
+     <x>416</x>
+     <y>20</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Preview:</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_layerRedirect">
+   <property name="geometry">
+    <rect>
+     <x>450</x>
+     <y>270</y>
+     <width>131</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>More info</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_wfs">
+   <property name="geometry">
+    <rect>
+     <x>30</x>
+     <y>360</y>
+     <width>141</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Load WFS</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_delete">
+   <property name="geometry">
+    <rect>
+     <x>450</x>
+     <y>310</y>
+     <width>131</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Delete layer</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_addMap.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_addMap.ui'))
+
+
+class AddMapDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(AddMapDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 136 - 0
dlg_addMap.ui

@@ -0,0 +1,136 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>780</width>
+    <height>450</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>780</width>
+    <height>450</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>780</width>
+    <height>450</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Layman - Add Map</string>
+  </property>
+  <widget class="QPushButton" name="pushButton">
+   <property name="geometry">
+    <rect>
+     <x>407</x>
+     <y>320</y>
+     <width>151</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Load map (WMS)</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>410</y>
+     <width>121</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QTreeWidget" name="treeWidget">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>10</y>
+     <width>331</width>
+     <height>371</height>
+    </rect>
+   </property>
+   <column>
+    <property name="text">
+     <string>Layer</string>
+    </property>
+   </column>
+  </widget>
+  <widget class="QLabel" name="label_thumbnail">
+   <property name="geometry">
+    <rect>
+     <x>460</x>
+     <y>50</y>
+     <width>200</width>
+     <height>200</height>
+    </rect>
+   </property>
+   <property name="frameShape">
+    <enum>QFrame::Box</enum>
+   </property>
+   <property name="text">
+    <string/>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_2">
+   <property name="geometry">
+    <rect>
+     <x>460</x>
+     <y>20</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Preview:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_info">
+   <property name="geometry">
+    <rect>
+     <x>370</x>
+     <y>250</y>
+     <width>411</width>
+     <height>31</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:12pt; color:#ff0000;&quot;&gt;Unable to load already loaded composition!&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_mapWFS">
+   <property name="geometry">
+    <rect>
+     <x>570</x>
+     <y>320</y>
+     <width>151</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Load map (WFS)</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_createComposite.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_createComposite.ui'))
+
+
+class CreateCompositeDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(CreateCompositeDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 306 - 0
dlg_createComposite.ui

@@ -0,0 +1,306 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>650</width>
+    <height>380</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>650</width>
+    <height>380</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>650</width>
+    <height>380</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Layman - Create Composite</string>
+  </property>
+  <widget class="QPushButton" name="pushButton_CreateComposition">
+   <property name="geometry">
+    <rect>
+     <x>287</x>
+     <y>340</y>
+     <width>141</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Create </string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>449</x>
+     <y>340</y>
+     <width>151</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Storno</string>
+   </property>
+  </widget>
+  <widget class="QTreeWidget" name="treeWidget">
+   <property name="geometry">
+    <rect>
+     <x>288</x>
+     <y>46</y>
+     <width>311</width>
+     <height>241</height>
+    </rect>
+   </property>
+   <column>
+    <property name="text">
+     <string>Layer</string>
+    </property>
+   </column>
+  </widget>
+  <widget class="QLabel" name="label">
+   <property name="geometry">
+    <rect>
+     <x>290</x>
+     <y>17</y>
+     <width>311</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>You can choose externt of composition from layer:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_2">
+   <property name="geometry">
+    <rect>
+     <x>40</x>
+     <y>380</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Composition name:</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit">
+   <property name="geometry">
+    <rect>
+     <x>30</x>
+     <y>410</y>
+     <width>201</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_2">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>46</y>
+     <width>201</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_3">
+   <property name="geometry">
+    <rect>
+     <x>21</x>
+     <y>20</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Title:</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_3">
+   <property name="geometry">
+    <rect>
+     <x>92</x>
+     <y>177</y>
+     <width>130</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_4">
+   <property name="geometry">
+    <rect>
+     <x>92</x>
+     <y>207</y>
+     <width>130</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_5">
+   <property name="geometry">
+    <rect>
+     <x>92</x>
+     <y>237</y>
+     <width>130</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_6">
+   <property name="geometry">
+    <rect>
+     <x>92</x>
+     <y>267</y>
+     <width>130</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_4">
+   <property name="geometry">
+    <rect>
+     <x>22</x>
+     <y>150</y>
+     <width>211</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Extent of canvas:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_5">
+   <property name="geometry">
+    <rect>
+     <x>22</x>
+     <y>181</y>
+     <width>41</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>XMin:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_6">
+   <property name="geometry">
+    <rect>
+     <x>22</x>
+     <y>210</y>
+     <width>41</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>XMax:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_7">
+   <property name="geometry">
+    <rect>
+     <x>22</x>
+     <y>241</y>
+     <width>41</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>YMin:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_8">
+   <property name="geometry">
+    <rect>
+     <x>22</x>
+     <y>270</y>
+     <width>41</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>YMax:</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_7">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>110</y>
+     <width>201</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_9">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>84</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Description:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_info">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>300</y>
+     <width>321</width>
+     <height>31</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:12pt; color:#ff0000;&quot;&gt;Composition name already exists!&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_defaultExtent">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>340</y>
+     <width>141</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Canvas extent</string>
+   </property>
+  </widget>
+ </widget>
+ <tabstops>
+  <tabstop>lineEdit</tabstop>
+  <tabstop>lineEdit_2</tabstop>
+  <tabstop>lineEdit_7</tabstop>
+  <tabstop>lineEdit_3</tabstop>
+  <tabstop>lineEdit_4</tabstop>
+  <tabstop>lineEdit_5</tabstop>
+  <tabstop>lineEdit_6</tabstop>
+  <tabstop>treeWidget</tabstop>
+  <tabstop>pushButton_CreateComposition</tabstop>
+  <tabstop>pushButton_close</tabstop>
+ </tabstops>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_deleteLayerFromMap.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_deleteLayerFromMap.ui'))
+
+
+class DeleteLayerFromMapDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(DeleteLayerFromMapDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 120 - 0
dlg_deleteLayerFromMap.ui

@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>CartoDBDialogBase</class>
+ <widget class="QDialog" name="CartoDBDialogBase">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>657</width>
+    <height>455</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Layman - Delete layer from map</string>
+  </property>
+  <widget class="QPushButton" name="pushButton">
+   <property name="geometry">
+    <rect>
+     <x>70</x>
+     <y>250</y>
+     <width>88</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Delete layer</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>360</x>
+     <y>250</y>
+     <width>93</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>10</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Loaded compositions:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_2">
+   <property name="geometry">
+    <rect>
+     <x>360</x>
+     <y>10</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Layers in composition:</string>
+   </property>
+  </widget>
+  <widget class="QListWidget" name="listWidget">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>40</y>
+     <width>261</width>
+     <height>192</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QListWidget" name="listWidget_listLayers2">
+   <property name="geometry">
+    <rect>
+     <x>360</x>
+     <y>40</y>
+     <width>271</width>
+     <height>192</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_3">
+   <property name="geometry">
+    <rect>
+     <x>370</x>
+     <y>320</y>
+     <width>131</width>
+     <height>121</height>
+    </rect>
+   </property>
+   <property name="frameShape">
+    <enum>QFrame::Box</enum>
+   </property>
+   <property name="text">
+    <string/>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_4">
+   <property name="geometry">
+    <rect>
+     <x>370</x>
+     <y>292</y>
+     <width>141</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Preview:</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_deleteMap.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_deleteMap.ui'))
+
+
+class DeleteMapDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(DeleteMapDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 60 - 0
dlg_deleteMap.ui

@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>CartoDBDialogBase</class>
+ <widget class="QDialog" name="CartoDBDialogBase">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>716</width>
+    <height>450</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Atlas - Delete Map</string>
+  </property>
+  <widget class="QPushButton" name="pushButton">
+   <property name="geometry">
+    <rect>
+     <x>280</x>
+     <y>410</y>
+     <width>88</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Delete map</string>
+   </property>
+  </widget>
+  <widget class="QTreeWidget" name="treeWidget">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>10</y>
+     <width>691</width>
+     <height>391</height>
+    </rect>
+   </property>
+   <column>
+    <property name="text">
+     <string>Map</string>
+    </property>
+   </column>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>420</x>
+     <y>410</y>
+     <width>93</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Zavřít</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_editMap.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_editMap.ui'))
+
+
+class EditMapDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(EditMapDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 216 - 0
dlg_editMap.ui

@@ -0,0 +1,216 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>350</width>
+    <height>250</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>350</width>
+    <height>250</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>350</width>
+    <height>250</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Layman - Edit metadata</string>
+  </property>
+  <widget class="QPushButton" name="pushButton_save">
+   <property name="geometry">
+    <rect>
+     <x>51</x>
+     <y>204</y>
+     <width>88</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Save</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>188</x>
+     <y>203</y>
+     <width>93</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_name">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>1</y>
+     <width>137</width>
+     <height>20</height>
+    </rect>
+   </property>
+   <property name="readOnly">
+    <bool>true</bool>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_abstract">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>60</y>
+     <width>137</width>
+     <height>20</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_title">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>30</y>
+     <width>137</width>
+     <height>20</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>60</y>
+     <width>71</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Abstract:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_2">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>1</y>
+     <width>61</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Name:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_3">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>30</y>
+     <width>61</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Title:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_4">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>89</y>
+     <width>61</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Units:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_5">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>119</y>
+     <width>51</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Scale:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_6">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>150</y>
+     <width>61</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>User:</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_units">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>89</y>
+     <width>137</width>
+     <height>20</height>
+    </rect>
+   </property>
+   <property name="readOnly">
+    <bool>true</bool>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_scale">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>119</y>
+     <width>137</width>
+     <height>20</height>
+    </rect>
+   </property>
+   <property name="readOnly">
+    <bool>true</bool>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_user">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>150</y>
+     <width>137</width>
+     <height>20</height>
+    </rect>
+   </property>
+   <property name="readOnly">
+    <bool>true</bool>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_importLayer.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_importLayer.ui'))
+
+
+class ImportLayerDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(ImportLayerDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 102 - 0
dlg_importLayer.ui

@@ -0,0 +1,102 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>400</width>
+    <height>299</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>400</width>
+    <height>299</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>400</width>
+    <height>299</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Layman - Export Layer to server</string>
+  </property>
+  <widget class="QListWidget" name="listWidget_listLayers">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>10</y>
+     <width>381</width>
+     <height>191</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton">
+   <property name="geometry">
+    <rect>
+     <x>50</x>
+     <y>260</y>
+     <width>131</width>
+     <height>27</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Export layer</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>212</x>
+     <y>260</y>
+     <width>131</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QTreeWidget" name="treeWidget">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>10</y>
+     <width>381</width>
+     <height>241</height>
+    </rect>
+   </property>
+   <property name="selectionMode">
+    <enum>QAbstractItemView::ExtendedSelection</enum>
+   </property>
+   <property name="selectionBehavior">
+    <enum>QAbstractItemView::SelectRows</enum>
+   </property>
+   <column>
+    <property name="text">
+     <string>Layer</string>
+    </property>
+   </column>
+   <column>
+    <property name="text">
+     <string>Type</string>
+    </property>
+   </column>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_importMap.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_importMap.ui'))
+
+
+class ImportMapDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(ImportMapDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 413 - 0
dlg_importMap.ui

@@ -0,0 +1,413 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="enabled">
+   <bool>true</bool>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>1139</width>
+    <height>544</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>1139</width>
+    <height>544</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>1139</width>
+    <height>544</height>
+   </size>
+  </property>
+  <property name="acceptDrops">
+   <bool>false</bool>
+  </property>
+  <property name="windowTitle">
+   <string>Layman -Manage Maps</string>
+  </property>
+  <widget class="QPushButton" name="pushButton_close">
+   <property name="geometry">
+    <rect>
+     <x>510</x>
+     <y>490</y>
+     <width>151</width>
+     <height>28</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Close</string>
+   </property>
+  </widget>
+  <widget class="QGroupBox" name="groupBox">
+   <property name="geometry">
+    <rect>
+     <x>420</x>
+     <y>10</y>
+     <width>701</width>
+     <height>471</height>
+    </rect>
+   </property>
+   <property name="title">
+    <string>Layers</string>
+   </property>
+   <widget class="QListWidget" name="listWidget_listLayers">
+    <property name="geometry">
+     <rect>
+      <x>22</x>
+      <y>50</y>
+      <width>351</width>
+      <height>191</height>
+     </rect>
+    </property>
+    <property name="acceptDrops">
+     <bool>false</bool>
+    </property>
+    <property name="dragDropMode">
+     <enum>QAbstractItemView::NoDragDrop</enum>
+    </property>
+    <property name="selectionMode">
+     <enum>QAbstractItemView::SingleSelection</enum>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_4">
+    <property name="geometry">
+     <rect>
+      <x>23</x>
+      <y>29</y>
+      <width>201</width>
+      <height>16</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Existing layers in map composition:</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_deleteLayers">
+    <property name="geometry">
+     <rect>
+      <x>22</x>
+      <y>290</y>
+      <width>161</width>
+      <height>27</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string> Delete Layer</string>
+    </property>
+    <property name="icon">
+     <iconset>
+      <normaloff>../../../../../../../Users/Honza/.designer/backup/icons/minus.png</normaloff>../../../../../../../Users/Honza/.designer/backup/icons/minus.png</iconset>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_thumbnail">
+    <property name="geometry">
+     <rect>
+      <x>200</x>
+      <y>290</y>
+      <width>170</width>
+      <height>170</height>
+     </rect>
+    </property>
+    <property name="frameShape">
+     <enum>QFrame::Box</enum>
+    </property>
+    <property name="text">
+     <string/>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_5">
+    <property name="geometry">
+     <rect>
+      <x>52</x>
+      <y>370</y>
+      <width>181</width>
+      <height>16</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Layer preview:</string>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_import">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>270</y>
+      <width>141</width>
+      <height>16</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Importing layer:</string>
+    </property>
+   </widget>
+   <widget class="QProgressBar" name="progressBar">
+    <property name="enabled">
+     <bool>true</bool>
+    </property>
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>310</y>
+      <width>191</width>
+      <height>23</height>
+     </rect>
+    </property>
+    <property name="maximum">
+     <number>0</number>
+    </property>
+    <property name="value">
+     <number>0</number>
+    </property>
+   </widget>
+   <widget class="QgsMapLayerComboBox" name="mMapLayerComboBox">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>50</y>
+      <width>231</width>
+      <height>27</height>
+     </rect>
+    </property>
+    <property name="showCrs">
+     <bool>true</bool>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>96</y>
+      <width>161</width>
+      <height>27</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string> Add Layer</string>
+    </property>
+    <property name="icon">
+     <iconset>
+      <normaloff>../../../../../../../Users/Honza/.designer/backup/icons/plus.png</normaloff>../../../../../../../Users/Honza/.designer/backup/icons/plus.png</iconset>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_2">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>27</y>
+      <width>211</width>
+      <height>16</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Loaded vector layer from canvas:</string>
+    </property>
+   </widget>
+   <widget class="QComboBox" name="comboBox_raster">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>180</y>
+      <width>231</width>
+      <height>22</height>
+     </rect>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_addRaster">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>220</y>
+      <width>161</width>
+      <height>27</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string> Add Layer</string>
+    </property>
+    <property name="icon">
+     <iconset>
+      <normaloff>../../../../../../../Users/Honza/.designer/backup/icons/plus.png</normaloff>../../../../../../../Users/Honza/.designer/backup/icons/plus.png</iconset>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_3">
+    <property name="geometry">
+     <rect>
+      <x>420</x>
+      <y>150</y>
+      <width>201</width>
+      <height>16</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Existing layers in Layman:</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_down">
+    <property name="geometry">
+     <rect>
+      <x>200</x>
+      <y>250</y>
+      <width>171</width>
+      <height>28</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Up</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_up">
+    <property name="geometry">
+     <rect>
+      <x>22</x>
+      <y>250</y>
+      <width>161</width>
+      <height>28</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Down</string>
+    </property>
+   </widget>
+  </widget>
+  <widget class="QGroupBox" name="groupBox_2">
+   <property name="geometry">
+    <rect>
+     <x>7</x>
+     <y>10</y>
+     <width>391</width>
+     <height>471</height>
+    </rect>
+   </property>
+   <property name="title">
+    <string>map compositions</string>
+   </property>
+   <widget class="QListWidget" name="listWidget">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>47</y>
+      <width>341</width>
+      <height>191</height>
+     </rect>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label">
+    <property name="geometry">
+     <rect>
+      <x>23</x>
+      <y>27</y>
+      <width>171</width>
+      <height>16</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Loaded map compositions:</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_deleteMap">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>260</y>
+      <width>161</width>
+      <height>27</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string> Delete Map</string>
+    </property>
+    <property name="icon">
+     <iconset>
+      <normaloff>../../../../../../../Users/Honza/.designer/backup/icons/minus.png</normaloff>../../../../../../../Users/Honza/.designer/backup/icons/minus.png</iconset>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_addMap">
+    <property name="geometry">
+     <rect>
+      <x>200</x>
+      <y>260</y>
+      <width>161</width>
+      <height>28</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string> Add Map</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_editMeta">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>320</y>
+      <width>161</width>
+      <height>28</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>  Edit metada</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_loadMap">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>380</y>
+      <width>161</width>
+      <height>28</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Load Map (WMS)</string>
+    </property>
+   </widget>
+   <widget class="QComboBox" name="comboBox_loadMap">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>420</y>
+      <width>231</width>
+      <height>22</height>
+     </rect>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="pushButton_loadMapWFS">
+    <property name="geometry">
+     <rect>
+      <x>200</x>
+      <y>380</y>
+      <width>161</width>
+      <height>28</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Load Map (WFS)</string>
+    </property>
+   </widget>
+  </widget>
+ </widget>
+ <customwidgets>
+  <customwidget>
+   <class>QgsMapLayerComboBox</class>
+   <extends>QComboBox</extends>
+   <header>qgsmaplayercombobox.h</header>
+  </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>

+ 44 - 0
dlg_userInfo.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CartoDBDialog
+                                 A QGIS plugin
+ CartoDB plugin
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+                             -------------------
+        begin                : 2019-03-19
+        git sha              : $Format:%H$
+        copyright            : (C) 2019 by Ondřej Tomančák, Jan Vrobel
+        email                : vrobel.jan@seznam.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ *                                                                         *
+ ***************************************************************************/
+"""
+
+import os
+
+from PyQt5 import uic
+from PyQt5 import QtWidgets
+
+# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
+FORM_CLASS, _ = uic.loadUiType(os.path.join(
+    os.path.dirname(__file__), 'dlg_userInfo.ui'))
+
+
+class UserInfoDialog(QtWidgets.QDialog, FORM_CLASS):
+    def __init__(self, parent=None):
+        """Constructor."""
+        super(UserInfoDialog, self).__init__(parent)
+        # Set up the user interface from Designer through FORM_CLASS.
+        # After self.setupUi() you can access any designer object by doing
+        # self.<objectname>, and you can use autoconnect slots - see
+        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
+        # #widgets-and-dialogs-with-auto-connect
+        self.setupUi(self)

+ 74 - 0
dlg_userInfo.ui

@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DialogBase</class>
+ <widget class="QDialog" name="DialogBase">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>400</width>
+    <height>300</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Layman</string>
+  </property>
+  <widget class="QLabel" name="label">
+   <property name="geometry">
+    <rect>
+     <x>40</x>
+     <y>60</y>
+     <width>111</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Layman username:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_2">
+   <property name="geometry">
+    <rect>
+     <x>40</x>
+     <y>100</y>
+     <width>111</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>Agrihub username:</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_layman">
+   <property name="geometry">
+    <rect>
+     <x>200</x>
+     <y>60</y>
+     <width>181</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string/>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_agrihub">
+   <property name="geometry">
+    <rect>
+     <x>200</x>
+     <y>100</y>
+     <width>191</width>
+     <height>16</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string/>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>

+ 94 - 0
flaskServer.py

@@ -0,0 +1,94 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Wed Nov 20 16:17:30 2019
+
+@author: Honza
+"""
+class flaskServer(object):
+    from flask import Flask                                                         
+    import threading
+
+    data = 'foo'
+    print(data)
+    app = Flask(__name__)
+
+    #@app.route("/")
+    #def main():
+    #    return data
+
+    @app.route("/")
+    def main():
+        print('aa')
+        threading.Thread(target=app.run).start()
+
+
+
+
+#from flask import Flask, request, jsonify
+#import threading
+#class flaskServer(object):
+#     app = Flask(__name__)                                                             
+#     def main():
+#         print("python main function")  
+
+#         data = 'foo'
+         
+#         print("test")
+#         threading.Thread(target=app.run).start()
+#     @app.route("/")
+#     def main():
+#         return "Layman"
+#     @app.route("/client/authn/oauth2-liferay/callback", methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
+#     def form_to_json(self):
+#         data = request.form.to_dict(flat=False)
+#         code = request.args.get('code')   
+      
+#         return (code)
+#     def startServer():
+#         app.run(host='0.0.0.0', port=3000)
+
+
+
+
+
+
+     #if __name__ == "__main__":
+     #    print("flask is starting")
+     #    threading.Thread(target=app.run).start()
+    #app = Flask(__name__)
+    #app.run(host='0.0.0.0', port=3000)
+    ##def __init__(self):
+    ##    app = Flask(__name__)
+    ##    #if __name__ == '__main__':
+    ##    app.run(host='0.0.0.0', port=3000)
+
+    #@app.route('/')
+    #def hello():
+    #    return "Hello World!"
+
+
+    #@app.route('/<name>')
+    #def hello_name(name):
+    #    return "Hello {}!".format(name)
+
+    #@app.route("/client/authn/oauth2-liferay/callback", methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
+    ##def get_text():
+    ##    return "some text"
+    ##def add():                                                                                                                              
+    ##    data = request.get_json()
+    #    # ... do your business logic, and return some response
+    #    # e.g. below we're just echo-ing back the received JSON data
+    #  # print (jsonify(data))
+    #   # print (request.headers)
+    #   # print (request.__dict__)
+    #    print (request.data)
+    #    return jsonify(data)
+    #def form_to_json(self):
+    #    data = request.form.to_dict(flat=False)
+    #    code = request.args.get('code')
+    
+    #    return jsonify(data)
+    #    return (code)
+
+
+    

+ 72 - 0
flaskServer2.py

@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Wed Nov 20 16:17:30 2019
+
+@author: Honza
+"""
+
+from flask import Flask, request, jsonify
+import threading
+class flaskServer(object):
+                                                                   
+       
+
+     data = 'foo'
+     print (data)
+     app = Flask(__name__)
+     app.run(host='0.0.0.0', port=3000)
+    # threading.Thread(target=app.run).start()
+     @app.route("/")
+     def main():
+         print(data)
+         return "Layman"
+#     @app.route("/client/authn/oauth2-liferay/callback", methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
+#     def form_to_json(self):
+#         data = request.form.to_dict(flat=False)
+#         code = request.args.get('code')   
+#      
+#         return (code)
+#     def startServer():
+#         print("test")
+#         app.run(host='0.0.0.0', port=3000)
+
+     #if __name__ == "__main__":
+     #    print("flask is starting")
+     #    threading.Thread(target=app.run).start()
+    #app = Flask(__name__)
+    #app.run(host='0.0.0.0', port=3000)
+    ##def __init__(self):
+    ##    app = Flask(__name__)
+    ##    #if __name__ == '__main__':
+    ##    app.run(host='0.0.0.0', port=3000)
+
+    #@app.route('/')
+    #def hello():
+    #    return "Hello World!"
+
+
+    #@app.route('/<name>')
+    #def hello_name(name):
+    #    return "Hello {}!".format(name)
+
+    #@app.route("/client/authn/oauth2-liferay/callback", methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
+    ##def get_text():
+    ##    return "some text"
+    ##def add():                                                                                                                              
+    ##    data = request.get_json()
+    #    # ... do your business logic, and return some response
+    #    # e.g. below we're just echo-ing back the received JSON data
+    #  # print (jsonify(data))
+    #   # print (request.headers)
+    #   # print (request.__dict__)
+    #    print (request.data)
+    #    return jsonify(data)
+    #def form_to_json(self):
+    #    data = request.form.to_dict(flat=False)
+    #    code = request.args.get('code')
+    
+    #    return jsonify(data)
+    #    return (code)
+
+
+    

BIN
flask_listener/__pycache__/flask.cpython-37.pyc


+ 36 - 0
flask_listener/flask_listener.py

@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Wed Nov 20 16:17:30 2019
+
+@author: Honza
+"""
+
+from flask import Flask, request, jsonify
+import json
+import tempfile
+import os
+
+app = Flask(__name__)
+
+def writeCode(value):
+    path = tempfile.gettempdir() + os.sep + "atlas" + os.sep + "auth.txt"    
+    f = open(path, "w")
+    f.write(value)
+    f.close()
+
+@app.route('/')
+def hello():
+    return "Flask server"
+
+
+@app.route("/client/authn/oauth2-liferay/callback", methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
+def form_to_json():
+    data = request.form.to_dict(flat=False)
+    code = request.args.get('code')
+    writeCode(code)
+    return "Authorize code optained. Please continue with QGIS plugin."
+
+
+
+if __name__ == '__main__':
+    app.run(host='0.0.0.0', port=3000)

+ 130 - 0
help/Makefile

@@ -0,0 +1,130 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS    =
+SPHINXBUILD   = sphinx-build
+PAPER         =
+BUILDDIR      = build
+
+# Internal variables.
+PAPEROPT_a4     = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
+
+help:
+	@echo "Please use \`make <target>' where <target> is one of"
+	@echo "  html       to make standalone HTML files"
+	@echo "  dirhtml    to make HTML files named index.html in directories"
+	@echo "  singlehtml to make a single large HTML file"
+	@echo "  pickle     to make pickle files"
+	@echo "  json       to make JSON files"
+	@echo "  htmlhelp   to make HTML files and a HTML help project"
+	@echo "  qthelp     to make HTML files and a qthelp project"
+	@echo "  devhelp    to make HTML files and a Devhelp project"
+	@echo "  epub       to make an epub"
+	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
+	@echo "  text       to make text files"
+	@echo "  man        to make manual pages"
+	@echo "  changes    to make an overview of all changed/added/deprecated items"
+	@echo "  linkcheck  to check all external links for integrity"
+	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+	-rm -rf $(BUILDDIR)/*
+
+html:
+	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+	@echo
+	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+	@echo
+	@echo "Build finished; now you can process the pickle files."
+
+json:
+	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+	@echo
+	@echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+	@echo
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
+	      ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+	@echo
+	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
+	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/template_class.qhcp"
+	@echo "To view the help file:"
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/template_class.qhc"
+
+devhelp:
+	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+	@echo
+	@echo "Build finished."
+	@echo "To view the help file:"
+	@echo "# mkdir -p $$HOME/.local/share/devhelp/template_class"
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/template_class"
+	@echo "# devhelp"
+
+epub:
+	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+	@echo
+	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo
+	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+	@echo "Run \`make' in that directory to run these through (pdf)latex" \
+	      "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo "Running LaTeX files through pdflatex..."
+	make -C $(BUILDDIR)/latex all-pdf
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+	@echo
+	@echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+	@echo
+	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+changes:
+	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+	@echo
+	@echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+	@echo
+	@echo "Link check complete; look for any errors in the above output " \
+	      "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+	@echo "Testing of doctests in the sources finished, look at the " \
+	      "results in $(BUILDDIR)/doctest/output.txt."

+ 155 - 0
help/make.bat

@@ -0,0 +1,155 @@
+@ECHO OFF
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+	set SPHINXBUILD=sphinx-build
+)
+set BUILDDIR=build
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
+if NOT "%PAPER%" == "" (
+	set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
+)
+
+if "%1" == "" goto help
+
+if "%1" == "help" (
+	:help
+	echo.Please use `make ^<target^>` where ^<target^> is one of
+	echo.  html       to make standalone HTML files
+	echo.  dirhtml    to make HTML files named index.html in directories
+	echo.  singlehtml to make a single large HTML file
+	echo.  pickle     to make pickle files
+	echo.  json       to make JSON files
+	echo.  htmlhelp   to make HTML files and a HTML help project
+	echo.  qthelp     to make HTML files and a qthelp project
+	echo.  devhelp    to make HTML files and a Devhelp project
+	echo.  epub       to make an epub
+	echo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter
+	echo.  text       to make text files
+	echo.  man        to make manual pages
+	echo.  changes    to make an overview over all changed/added/deprecated items
+	echo.  linkcheck  to check all external links for integrity
+	echo.  doctest    to run all doctests embedded in the documentation if enabled
+	goto end
+)
+
+if "%1" == "clean" (
+	for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
+	del /q /s %BUILDDIR%\*
+	goto end
+)
+
+if "%1" == "html" (
+	%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
+	echo.
+	echo.Build finished. The HTML pages are in %BUILDDIR%/html.
+	goto end
+)
+
+if "%1" == "dirhtml" (
+	%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
+	echo.
+	echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
+	goto end
+)
+
+if "%1" == "singlehtml" (
+	%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
+	echo.
+	echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
+	goto end
+)
+
+if "%1" == "pickle" (
+	%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
+	echo.
+	echo.Build finished; now you can process the pickle files.
+	goto end
+)
+
+if "%1" == "json" (
+	%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
+	echo.
+	echo.Build finished; now you can process the JSON files.
+	goto end
+)
+
+if "%1" == "htmlhelp" (
+	%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
+	echo.
+	echo.Build finished; now you can run HTML Help Workshop with the ^
+.hhp project file in %BUILDDIR%/htmlhelp.
+	goto end
+)
+
+if "%1" == "qthelp" (
+	%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
+	echo.
+	echo.Build finished; now you can run "qcollectiongenerator" with the ^
+.qhcp project file in %BUILDDIR%/qthelp, like this:
+	echo.^> qcollectiongenerator %BUILDDIR%\qthelp\template_class.qhcp
+	echo.To view the help file:
+	echo.^> assistant -collectionFile %BUILDDIR%\qthelp\template_class.ghc
+	goto end
+)
+
+if "%1" == "devhelp" (
+	%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
+	echo.
+	echo.Build finished.
+	goto end
+)
+
+if "%1" == "epub" (
+	%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
+	echo.
+	echo.Build finished. The epub file is in %BUILDDIR%/epub.
+	goto end
+)
+
+if "%1" == "latex" (
+	%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+	echo.
+	echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
+	goto end
+)
+
+if "%1" == "text" (
+	%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
+	echo.
+	echo.Build finished. The text files are in %BUILDDIR%/text.
+	goto end
+)
+
+if "%1" == "man" (
+	%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
+	echo.
+	echo.Build finished. The manual pages are in %BUILDDIR%/man.
+	goto end
+)
+
+if "%1" == "changes" (
+	%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
+	echo.
+	echo.The overview file is in %BUILDDIR%/changes.
+	goto end
+)
+
+if "%1" == "linkcheck" (
+	%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
+	echo.
+	echo.Link check complete; look for any errors in the above output ^
+or in %BUILDDIR%/linkcheck/output.txt.
+	goto end
+)
+
+if "%1" == "doctest" (
+	%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
+	echo.
+	echo.Testing of doctests in the sources finished, look at the ^
+results in %BUILDDIR%/doctest/output.txt.
+	goto end
+)
+
+:end

+ 216 - 0
help/source/conf.py

@@ -0,0 +1,216 @@
+# -*- coding: utf-8 -*-
+#
+# Atlas documentation build configuration file, created by
+# sphinx-quickstart on Sun Feb 12 17:11:03 2012.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.todo', 'sphinx.ext.imgmath', 'sphinx.ext.viewcode']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'Atlas'
+copyright = u'2013, jan vrobel'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '0.1'
+# The full version, including alpha/beta/rc tags.
+release = '0.1'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = []
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_TemplateModuleNames = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  See the documentation for
+# a list of builtin themes.
+html_theme = 'default'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further.  For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.  The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'TemplateClassdoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+  ('index', 'Atlas.tex', u'Atlas Documentation',
+   u'jan vrobel', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+    ('index', 'TemplateClass', u'Atlas Documentation',
+     [u'jan vrobel'], 1)
+]

+ 20 - 0
help/source/index.rst

@@ -0,0 +1,20 @@
+.. Atlas documentation master file, created by
+   sphinx-quickstart on Sun Feb 12 17:11:03 2012.
+   You can adapt this file completely to your liking, but it should at least
+   contain the root `toctree` directive.
+
+Welcome to Atlas's documentation!
+============================================
+
+Contents:
+
+.. toctree::
+   :maxdepth: 2
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+

+ 11 - 0
i18n/af.ts

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS><TS version="2.0" language="af" sourcelanguage="en">
+<context>
+    <name>@default</name>
+    <message>
+        <location filename="test_translations.py" line="48"/>
+        <source>Good morning</source>
+        <translation>Goeie more</translation>
+    </message>
+</context>
+</TS>

BIN
icon.png


File diff suppressed because it is too large
+ 13 - 0
icons/account.svg


BIN
icons/cloud.png


BIN
icons/delete.png


BIN
icons/download_map.png


BIN
icons/edit.png


BIN
icons/file.png


BIN
icons/globus.png


BIN
icons/layers-down.png


BIN
icons/layers-up.png


BIN
icons/load.png


BIN
icons/login.png


BIN
icons/minus.png


BIN
icons/plus.png


BIN
icons/save.png


BIN
icons/upload-map.png


BIN
icons/upload.png


+ 6 - 0
install_windows/install.bat

@@ -0,0 +1,6 @@
+SET PYTHONPATH=
+SET PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
+PATH %OSGEO4W_ROOT%\apps\Python37;%OSGEO4W_ROOT%\apps\Python37\Scripts;%PATH%
+python -m ensurepip --default-pip
+python -m pip install --upgrade pip
+python -m pip install flask

+ 7 - 0
install_windows/install_packages.bat

@@ -0,0 +1,7 @@
+python -m ensurepip --default-pip
+SET PYTHONPATH=
+SET PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
+PATH %OSGEO4W_ROOT%\apps\Python37;%OSGEO4W_ROOT%\apps\Python37\Scripts;%PATH%
+python -m pip install --upgrade pip
+pip install flask
+

+ 2 - 0
install_windows/readme.txt

@@ -0,0 +1,2 @@
+1. run C:\Program Files\QGIS 3.4\OSGeo4W.bat as administrator
+2. run install_packages.bat from OSGeo command line - this install additional packages to QGIS Python

+ 39 - 0
metadata.txt

@@ -0,0 +1,39 @@
+# This file contains metadata for your plugin. Since 
+# version 2.0 of QGIS this is the proper way to supply 
+# information about a plugin. The old method of 
+# embedding metadata in __init__.py will 
+# is no longer supported since version 2.0.
+
+# This file should be included when you package your plugin.# Mandatory items:
+
+[general]
+name=Atlas
+qgisMinimumVersion=3.0
+description=Atlas
+version=0.1
+author=jan vrobel
+email=vrobel.jan@seznam.cz
+
+about=Export json to Atlas server
+
+tracker=http://bugs
+repository=http://repo
+# End of mandatory metadata
+
+# Recommended items:
+
+# Uncomment the following line and add your changelog:
+# changelog=
+
+# Tags are comma separated with spaces allowed
+tags=python
+
+homepage=http://homepage
+category=Plugins
+icon=icon.png
+# experimental flag
+experimental=False
+
+# deprecated flag (applies to the whole plugin, not just a single version)
+deprecated=False
+

+ 1696 - 0
ogr2ogr.py

@@ -0,0 +1,1696 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#*****************************************************************************
+# $Id$
+#
+# Project:  OpenGIS Simple Features Reference Implementation
+# Purpose:  Python port of a simple client for translating between formats.
+# Author:   Even Rouault, <even dot rouault at mines dash paris dot org>
+#
+# Port from ogr2ogr.cpp whose author is Frank Warmerdam
+#
+#*****************************************************************************
+# Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org>
+# Copyright (c) 1999, Frank Warmerdam
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+# DEALINGS IN THE SOFTWARE.
+#**************************************************************************
+
+# Note : this is the most direct port of ogr2ogr.cpp possible
+# It could be made much more Python'ish !
+
+import sys
+import os
+import stat
+
+from osgeo import gdal
+from osgeo import ogr
+from osgeo import osr
+
+###############################################################################
+
+class ScaledProgressObject:
+    def __init__(self, min, max, cbk, cbk_data = None):
+        self.min = min
+        self.max = max
+        self.cbk = cbk
+        self.cbk_data = cbk_data
+
+###############################################################################
+
+def ScaledProgressFunc(pct, msg, data):
+    if data.cbk is None:
+        return True
+    return data.cbk(data.min + pct * (data.max - data.min), msg, data.cbk_data)
+
+###############################################################################
+
+def EQUAL(a, b):
+    return a.lower() == b.lower()
+
+###############################################################################
+# Redefinition of GDALTermProgress, so that autotest/pyscripts/test_ogr2ogr_py.py
+# can check that the progress bar is displayed
+
+nLastTick = -1
+
+def TermProgress( dfComplete, pszMessage, pProgressArg ):
+
+    global nLastTick
+    nThisTick = (int) (dfComplete * 40.0)
+
+    if nThisTick < 0:
+        nThisTick = 0
+    if nThisTick > 40:
+        nThisTick = 40
+
+    # Have we started a new progress run?
+    if nThisTick < nLastTick and nLastTick >= 39:
+        nLastTick = -1
+
+    if nThisTick <= nLastTick:
+        return True
+
+    while nThisTick > nLastTick:
+        nLastTick = nLastTick + 1
+        if (nLastTick % 4) == 0:
+            sys.stdout.write('%d' % ((nLastTick / 4) * 10))
+        else:
+            sys.stdout.write('.')
+
+    if nThisTick == 40:
+        print(" - done." )
+    else:
+        sys.stdout.flush()
+
+    return True
+
+class TargetLayerInfo:
+    def __init__(self):
+        self.poDstLayer = None
+        self.poCT = None
+        #self.papszTransformOptions = None
+        self.panMap = None
+        self.iSrcZField = None
+
+class AssociatedLayers:
+    def __init__(self):
+        self.poSrcLayer = None
+        self.psInfo = None
+
+#**********************************************************************
+#                                main()
+#**********************************************************************
+
+bSkipFailures = False
+nGroupTransactions = 200
+bPreserveFID = False
+nFIDToFetch = ogr.NullFID
+
+class Enum(set):
+    def __getattr__(self, name):
+        if name in self:
+            return name
+        raise AttributeError
+
+GeomOperation = Enum(["NONE", "SEGMENTIZE", "SIMPLIFY_PRESERVE_TOPOLOGY"])
+
+def main(args = None, progress_func = TermProgress, progress_data = None):
+
+    global bSkipFailures
+    global nGroupTransactions
+    global bPreserveFID
+    global nFIDToFetch
+
+    pszFormat = "ESRI Shapefile"
+    pszDataSource = None
+    pszDestDataSource = None
+    papszLayers = []
+    papszDSCO = []
+    papszLCO = []
+    bTransform = False
+    bAppend = False
+    bUpdate = False
+    bOverwrite = False
+    pszOutputSRSDef = None
+    pszSourceSRSDef = None
+    poOutputSRS = None
+    bNullifyOutputSRS = False
+    poSourceSRS = None
+    pszNewLayerName = None
+    pszWHERE = None
+    poSpatialFilter = None
+    pszSelect = None
+    papszSelFields = None
+    pszSQLStatement = None
+    eGType = -2
+    bPromoteToMulti = False
+    eGeomOp = GeomOperation.NONE
+    dfGeomOpParam = 0
+    papszFieldTypesToString = []
+    bDisplayProgress = False
+    pfnProgress = None
+    pProgressArg = None
+    bClipSrc = False
+    bWrapDateline = False
+    poClipSrc = None
+    pszClipSrcDS = None
+    pszClipSrcSQL = None
+    pszClipSrcLayer = None
+    pszClipSrcWhere = None
+    poClipDst = None
+    pszClipDstDS = None
+    pszClipDstSQL = None
+    pszClipDstLayer = None
+    pszClipDstWhere = None
+    #pszSrcEncoding = None
+    #pszDstEncoding = None
+    bWrapDateline = False
+    bExplodeCollections = False
+    pszZField = None
+    nCoordDim = -1
+
+    if args is None:
+        args = sys.argv
+
+    args = ogr.GeneralCmdLineProcessor( args )
+
+# --------------------------------------------------------------------
+#      Processing command line arguments.
+# --------------------------------------------------------------------
+    if args is None:
+        return False
+
+    nArgc = len(args)
+
+    iArg = 1
+    while iArg < nArgc:
+        if EQUAL(args[iArg],"-f") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszFormat = args[iArg]
+
+        elif EQUAL(args[iArg],"-dsco") and iArg < nArgc-1:
+            iArg = iArg + 1
+            papszDSCO.append(args[iArg] )
+
+        elif EQUAL(args[iArg],"-lco") and iArg < nArgc-1:
+            iArg = iArg + 1
+            papszLCO.append(args[iArg] )
+
+        elif EQUAL(args[iArg],"-preserve_fid"):
+            bPreserveFID = True
+
+        elif len(args[iArg]) >= 5 and EQUAL(args[iArg][0:5], "-skip"):
+            bSkipFailures = True
+            nGroupTransactions = 1 # #2409
+
+        elif EQUAL(args[iArg],"-append"):
+            bAppend = True
+            bUpdate = True
+
+        elif EQUAL(args[iArg],"-overwrite"):
+            bOverwrite = True
+            bUpdate = True
+
+        elif EQUAL(args[iArg],"-update"):
+            bUpdate = True
+
+        elif EQUAL(args[iArg],"-fid") and iArg < nArgc-1:
+            iArg = iArg + 1
+            nFIDToFetch = int(args[iArg])
+
+        elif EQUAL(args[iArg],"-sql") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszSQLStatement = args[iArg]
+
+        elif EQUAL(args[iArg],"-nln") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszNewLayerName = args[iArg]
+
+        elif EQUAL(args[iArg],"-nlt") and iArg < nArgc-1:
+
+            if EQUAL(args[iArg+1],"NONE"):
+                eGType = ogr.wkbNone
+            elif EQUAL(args[iArg+1],"GEOMETRY"):
+                eGType = ogr.wkbUnknown
+            elif EQUAL(args[iArg+1],"PROMOTE_TO_MULTI"):
+                bPromoteToMulti = True
+            elif EQUAL(args[iArg+1],"POINT"):
+                eGType = ogr.wkbPoint
+            elif EQUAL(args[iArg+1],"LINESTRING"):
+                eGType = ogr.wkbLineString
+            elif EQUAL(args[iArg+1],"POLYGON"):
+                eGType = ogr.wkbPolygon
+            elif EQUAL(args[iArg+1],"GEOMETRYCOLLECTION"):
+                eGType = ogr.wkbGeometryCollection
+            elif EQUAL(args[iArg+1],"MULTIPOINT"):
+                eGType = ogr.wkbMultiPoint
+            elif EQUAL(args[iArg+1],"MULTILINESTRING"):
+                eGType = ogr.wkbMultiLineString
+            elif EQUAL(args[iArg+1],"MULTIPOLYGON"):
+                eGType = ogr.wkbMultiPolygon
+            elif EQUAL(args[iArg+1],"GEOMETRY25D"):
+                eGType = ogr.wkbUnknown | ogr.wkb25DBit
+            elif EQUAL(args[iArg+1],"POINT25D"):
+                eGType = ogr.wkbPoint25D
+            elif EQUAL(args[iArg+1],"LINESTRING25D"):
+                eGType = ogr.wkbLineString25D
+            elif EQUAL(args[iArg+1],"POLYGON25D"):
+                eGType = ogr.wkbPolygon25D
+            elif EQUAL(args[iArg+1],"GEOMETRYCOLLECTION25D"):
+                eGType = ogr.wkbGeometryCollection25D
+            elif EQUAL(args[iArg+1],"MULTIPOINT25D"):
+                eGType = ogr.wkbMultiPoint25D
+            elif EQUAL(args[iArg+1],"MULTILINESTRING25D"):
+                eGType = ogr.wkbMultiLineString25D
+            elif EQUAL(args[iArg+1],"MULTIPOLYGON25D"):
+                eGType = ogr.wkbMultiPolygon25D
+            else:
+                print("-nlt %s: type not recognised." % args[iArg+1])
+                return False
+
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-dim") and iArg < nArgc-1:
+
+            nCoordDim = int(args[iArg+1])
+            if nCoordDim != 2 and nCoordDim != 3:
+                print("-dim %s: value not handled." % args[iArg+1])
+                return False
+            iArg = iArg + 1
+
+        elif (EQUAL(args[iArg],"-tg") or \
+                EQUAL(args[iArg],"-gt")) and iArg < nArgc-1:
+            iArg = iArg + 1
+            nGroupTransactions = int(args[iArg])
+
+        elif EQUAL(args[iArg],"-s_srs") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszSourceSRSDef = args[iArg]
+
+        elif EQUAL(args[iArg],"-a_srs") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszOutputSRSDef = args[iArg]
+            if EQUAL(pszOutputSRSDef, "NULL") or \
+               EQUAL(pszOutputSRSDef, "NONE"):
+                pszOutputSRSDef = None
+                bNullifyOutputSRS = True
+
+        elif EQUAL(args[iArg],"-t_srs") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszOutputSRSDef = args[iArg]
+            bTransform = True
+
+        elif EQUAL(args[iArg],"-spat") and iArg + 4 < nArgc:
+            oRing = ogr.Geometry(ogr.wkbLinearRing)
+
+            oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) )
+            oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+4]) )
+            oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+4]) )
+            oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+2]) )
+            oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) )
+
+            poSpatialFilter = ogr.Geometry(ogr.wkbPolygon)
+            poSpatialFilter.AddGeometry(oRing)
+            iArg = iArg + 4
+
+        elif EQUAL(args[iArg],"-where") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszWHERE = args[iArg]
+
+        elif EQUAL(args[iArg],"-select") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszSelect = args[iArg]
+            if pszSelect.find(',') != -1:
+                papszSelFields = pszSelect.split(',')
+            else:
+                papszSelFields = pszSelect.split(' ')
+            if papszSelFields[0] == '':
+                papszSelFields = []
+
+        elif EQUAL(args[iArg],"-simplify") and iArg < nArgc-1:
+            iArg = iArg + 1
+            eGeomOp = GeomOperation.SIMPLIFY_PRESERVE_TOPOLOGY
+            dfGeomOpParam = float(args[iArg])
+
+        elif EQUAL(args[iArg],"-segmentize") and iArg < nArgc-1:
+            iArg = iArg + 1
+            eGeomOp = GeomOperation.SEGMENTIZE
+            dfGeomOpParam = float(args[iArg])
+
+        elif EQUAL(args[iArg],"-fieldTypeToString") and iArg < nArgc-1:
+            iArg = iArg + 1
+            pszFieldTypeToString = args[iArg]
+            if pszFieldTypeToString.find(',') != -1:
+                tokens = pszFieldTypeToString.split(',')
+            else:
+                tokens = pszFieldTypeToString.split(' ')
+
+            for token in tokens:
+                if EQUAL(token,"Integer") or \
+                    EQUAL(token,"Real") or \
+                    EQUAL(token,"String") or \
+                    EQUAL(token,"Date") or \
+                    EQUAL(token,"Time") or \
+                    EQUAL(token,"DateTime") or \
+                    EQUAL(token,"Binary") or \
+                    EQUAL(token,"IntegerList") or \
+                    EQUAL(token,"RealList") or \
+                    EQUAL(token,"StringList"):
+
+                    papszFieldTypesToString.append(token)
+
+                elif EQUAL(token,"All"):
+                    papszFieldTypesToString = [ 'All' ]
+                    break
+
+                else:
+                    print("Unhandled type for fieldtypeasstring option : %s " % token)
+                    return Usage()
+
+        elif EQUAL(args[iArg],"-progress"):
+            bDisplayProgress = True
+
+        #elif EQUAL(args[iArg],"-wrapdateline") )
+        #{
+        #    bWrapDateline = True;
+        #}
+        #
+        elif EQUAL(args[iArg],"-clipsrc") and iArg < nArgc-1:
+
+            bClipSrc = True
+            if IsNumber(args[iArg+1]) and iArg < nArgc - 4:
+                oRing = ogr.Geometry(ogr.wkbLinearRing)
+
+                oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) )
+                oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+4]) )
+                oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+4]) )
+                oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+2]) )
+                oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) )
+
+                poClipSrc = ogr.Geometry(ogr.wkbPolygon)
+                poClipSrc.AddGeometry(oRing)
+                iArg = iArg + 4
+
+            elif (len(args[iArg+1]) >= 7 and EQUAL(args[iArg+1][0:7],"POLYGON") ) or \
+                  (len(args[iArg+1]) >= 12 and EQUAL(args[iArg+1][0:12],"MULTIPOLYGON") ) :
+                poClipSrc = ogr.CreateGeometryFromWkt(args[iArg+1])
+                if poClipSrc is None:
+                    print("FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n")
+                    return Usage()
+
+                iArg = iArg + 1
+
+            elif EQUAL(args[iArg+1],"spat_extent"):
+                iArg = iArg + 1
+
+            else:
+                pszClipSrcDS = args[iArg+1]
+                iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipsrcsql") and iArg < nArgc-1:
+            pszClipSrcSQL = args[iArg+1]
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipsrclayer") and iArg < nArgc-1:
+            pszClipSrcLayer = args[iArg+1]
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipsrcwhere") and iArg < nArgc-1:
+            pszClipSrcWhere = args[iArg+1]
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipdst") and iArg < nArgc-1:
+
+            if IsNumber(args[iArg+1]) and iArg < nArgc - 4:
+                oRing = ogr.Geometry(ogr.wkbLinearRing)
+
+                oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) )
+                oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+4]) )
+                oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+4]) )
+                oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+2]) )
+                oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) )
+
+                poClipDst = ogr.Geometry(ogr.wkbPolygon)
+                poClipDst.AddGeometry(oRing)
+                iArg = iArg + 4
+
+            elif (len(args[iArg+1]) >= 7 and EQUAL(args[iArg+1][0:7],"POLYGON") ) or \
+                  (len(args[iArg+1]) >= 12 and EQUAL(args[iArg+1][0:12],"MULTIPOLYGON") ) :
+                poClipDst = ogr.CreateGeometryFromWkt(args[iArg+1])
+                if poClipDst is None:
+                    print("FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n")
+                    return Usage()
+
+                iArg = iArg + 1
+
+            elif EQUAL(args[iArg+1],"spat_extent"):
+                iArg = iArg + 1
+
+            else:
+                pszClipDstDS = args[iArg+1]
+                iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipdstsql") and iArg < nArgc-1:
+            pszClipDstSQL = args[iArg+1]
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipdstlayer") and iArg < nArgc-1:
+            pszClipDstLayer = args[iArg+1]
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-clipdstwhere") and iArg < nArgc-1:
+            pszClipDstWhere = args[iArg+1]
+            iArg = iArg + 1
+
+        elif EQUAL(args[iArg],"-explodecollections"):
+            bExplodeCollections = True
+
+        elif EQUAL(args[iArg],"-zfield") and iArg < nArgc-1:
+            pszZField = args[iArg+1]
+            iArg = iArg + 1
+
+        elif args[iArg][0] == '-':
+            return Usage()
+
+        elif pszDestDataSource is None:
+            pszDestDataSource = args[iArg]
+        elif pszDataSource is None:
+            pszDataSource = args[iArg]
+        else:
+            papszLayers.append (args[iArg] )
+
+        iArg = iArg + 1
+
+    if pszDataSource is None:
+        return Usage()
+
+    if bPreserveFID and bExplodeCollections:
+        print("FAILURE: cannot use -preserve_fid and -explodecollections at the same time\n\n")
+        return Usage()
+
+    if bClipSrc and pszClipSrcDS is not None:
+        poClipSrc = LoadGeometry(pszClipSrcDS, pszClipSrcSQL, pszClipSrcLayer, pszClipSrcWhere)
+        if poClipSrc is None:
+            print("FAILURE: cannot load source clip geometry\n" )
+            return Usage()
+
+    elif bClipSrc and poClipSrc is None:
+        if poSpatialFilter is not None:
+            poClipSrc = poSpatialFilter.Clone()
+        if poClipSrc is None:
+            print("FAILURE: -clipsrc must be used with -spat option or a\n" + \
+                  "bounding box, WKT string or datasource must be specified\n")
+            return Usage()
+
+    if pszClipDstDS is not None:
+        poClipDst = LoadGeometry(pszClipDstDS, pszClipDstSQL, pszClipDstLayer, pszClipDstWhere)
+        if poClipDst is None:
+            print("FAILURE: cannot load dest clip geometry\n" )
+            return Usage()
+
+# --------------------------------------------------------------------
+#      Open data source.
+# --------------------------------------------------------------------
+    poDS = ogr.Open( pszDataSource, False )
+
+# --------------------------------------------------------------------
+#      Report failure
+# --------------------------------------------------------------------
+    if poDS is None:
+        print("FAILURE:\n" + \
+                "Unable to open datasource `%s' with the following drivers." % pszDataSource)
+
+        for iDriver in range(ogr.GetDriverCount()):
+            print("  ->  " + ogr.GetDriver(iDriver).GetName() )
+
+        return False
+
+# --------------------------------------------------------------------
+#      Try opening the output datasource as an existing, writable
+# --------------------------------------------------------------------
+    poODS = None
+    poDriver = None
+
+    if bUpdate:
+        poODS = ogr.Open( pszDestDataSource, True )
+        if poODS is None:
+
+            if bOverwrite or bAppend:
+                poODS = ogr.Open( pszDestDataSource, False )
+                if poODS is None:
+                    # the datasource doesn't exist at all
+                    bUpdate = False
+                else:
+                    poODS.delete()
+                    poODS = None
+
+            if bUpdate:
+                print("FAILURE:\n" +
+                        "Unable to open existing output datasource `%s'." % pszDestDataSource)
+                return False
+
+        elif len(papszDSCO) > 0:
+            print("WARNING: Datasource creation options ignored since an existing datasource\n" + \
+                    "         being updated." )
+
+        if poODS is not None:
+            poDriver = poODS.GetDriver()
+
+# --------------------------------------------------------------------
+#      Find the output driver.
+# --------------------------------------------------------------------
+    if not bUpdate:
+        poDriver = ogr.GetDriverByName(pszFormat)
+        if poDriver is None:
+            print("Unable to find driver `%s'." % pszFormat)
+            print( "The following drivers are available:" )
+
+            for iDriver in range(ogr.GetDriverCount()):
+                print("  ->  %s" % ogr.GetDriver(iDriver).GetName() )
+
+            return False
+
+        if poDriver.TestCapability( ogr.ODrCCreateDataSource ) == False:
+            print( "%s driver does not support data source creation." % pszFormat)
+            return False
+
+# --------------------------------------------------------------------
+#      Special case to improve user experience when translating
+#      a datasource with multiple layers into a shapefile. If the
+#      user gives a target datasource with .shp and it does not exist,
+#      the shapefile driver will try to create a file, but this is not
+#      appropriate because here we have several layers, so create
+#      a directory instead.
+# --------------------------------------------------------------------
+        if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
+           pszSQLStatement is None and \
+           (len(papszLayers) > 1 or \
+            (len(papszLayers) == 0 and poDS.GetLayerCount() > 1)) and \
+            pszNewLayerName is None and \
+            EQUAL(os.path.splitext(pszDestDataSource)[1], ".SHP") :
+
+            try:
+                os.stat(pszDestDataSource)
+            except:
+                try:
+                    # decimal 493 = octal 0755. Python 3 needs 0o755, but
+                    # this syntax is only supported by Python >= 2.6
+                    os.mkdir(pszDestDataSource, 493)
+                except:
+                    print("Failed to create directory %s\n"
+                          "for shapefile datastore.\n" % pszDestDataSource )
+                    return False
+
+# --------------------------------------------------------------------
+#      Create the output data source.
+# --------------------------------------------------------------------
+        poODS = poDriver.CreateDataSource( pszDestDataSource, options = papszDSCO )
+        if poODS is None:
+            print( "%s driver failed to create %s" % (pszFormat, pszDestDataSource ))
+            return False
+
+# --------------------------------------------------------------------
+#      Parse the output SRS definition if possible.
+# --------------------------------------------------------------------
+    if pszOutputSRSDef is not None:
+        poOutputSRS = osr.SpatialReference()
+        if poOutputSRS.SetFromUserInput( pszOutputSRSDef ) != 0:
+            print( "Failed to process SRS definition: %s" % pszOutputSRSDef )
+            return False
+
+# --------------------------------------------------------------------
+#      Parse the source SRS definition if possible.
+# --------------------------------------------------------------------
+    if pszSourceSRSDef is not None:
+        poSourceSRS = osr.SpatialReference()
+        if poSourceSRS.SetFromUserInput( pszSourceSRSDef ) != 0:
+            print( "Failed to process SRS definition: %s" % pszSourceSRSDef )
+            return False
+
+# --------------------------------------------------------------------
+#      For OSM file.
+# --------------------------------------------------------------------
+    bSrcIsOSM = poDS.GetDriver() is not None and \
+                             poDS.GetDriver().GetName() == "OSM"
+    nSrcFileSize = 0
+    if bSrcIsOSM and poDS.GetName() != "/vsistdin/":
+        sStat = gdal.VSIStatL(poDS.GetName())
+        if sStat is not None:
+            nSrcFileSize = sStat.size
+
+# --------------------------------------------------------------------
+#      Special case for -sql clause.  No source layers required.
+# --------------------------------------------------------------------
+    if pszSQLStatement is not None:
+        if pszWHERE is not None:
+            print( "-where clause ignored in combination with -sql." )
+        if len(papszLayers) > 0:
+            print( "layer names ignored in combination with -sql." )
+
+        poResultSet = poDS.ExecuteSQL( pszSQLStatement, poSpatialFilter, \
+                                        None )
+
+        if poResultSet is not None:
+            nCountLayerFeatures = 0
+            if bDisplayProgress:
+                if bSrcIsOSM:
+                    pfnProgress = progress_func
+                    pProgressArg = progress_data
+
+                elif not poResultSet.TestCapability(ogr.OLCFastFeatureCount):
+                    print( "Progress turned off as fast feature count is not available.")
+                    bDisplayProgress = False
+
+                else:
+                    nCountLayerFeatures = poResultSet.GetFeatureCount()
+                    pfnProgress = progress_func
+                    pProgressArg = progress_data
+
+# --------------------------------------------------------------------
+#      Special case to improve user experience when translating into
+#      single file shapefile and source has only one layer, and that
+#      the layer name isn't specified
+# --------------------------------------------------------------------
+            if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
+                pszNewLayerName is None:
+                try:
+                    mode = os.stat(pszDestDataSource).st_mode
+                    if (mode & stat.S_IFDIR) == 0:
+                        pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0]
+                except:
+                    pass
+
+
+            psInfo = SetupTargetLayer(  poDS, \
+                                        poResultSet,
+                                        poODS, \
+                                        papszLCO, \
+                                        pszNewLayerName, \
+                                        bTransform, \
+                                        poOutputSRS, \
+                                        bNullifyOutputSRS, \
+                                        poSourceSRS, \
+                                        papszSelFields, \
+                                        bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \
+                                        papszFieldTypesToString, \
+                                        bWrapDateline, \
+                                        bExplodeCollections, \
+                                        pszZField, \
+                                        pszWHERE )
+
+            poResultSet.ResetReading()
+
+            if psInfo is None or not TranslateLayer( psInfo, poDS, poResultSet, poODS, \
+                                poOutputSRS, bNullifyOutputSRS, \
+                                eGType, bPromoteToMulti, nCoordDim, \
+                                eGeomOp, dfGeomOpParam, \
+                                nCountLayerFeatures, \
+                                poClipSrc, poClipDst, \
+                                bExplodeCollections, \
+                                nSrcFileSize, None, \
+                                pfnProgress, pProgressArg ):
+                print(
+                        "Terminating translation prematurely after failed\n" + \
+                        "translation from sql statement." )
+
+                return False
+
+            poDS.ReleaseResultSet( poResultSet )
+
+
+# --------------------------------------------------------------------
+#      Special case for layer interleaving mode.
+# --------------------------------------------------------------------
+    elif bSrcIsOSM and gdal.GetConfigOption("OGR_INTERLEAVED_READING", None) is None:
+
+        gdal.SetConfigOption("OGR_INTERLEAVED_READING", "YES")
+
+        #if (bSplitListFields)
+        #{
+        #    fprintf( stderr, "FAILURE: -splitlistfields not supported in this mode\n" );
+        #    exit( 1 );
+        #}
+
+        nSrcLayerCount = poDS.GetLayerCount()
+        pasAssocLayers = [ AssociatedLayers() for i in range(nSrcLayerCount) ]
+
+# --------------------------------------------------------------------
+#      Special case to improve user experience when translating into
+#      single file shapefile and source has only one layer, and that
+#      the layer name isn't specified
+# --------------------------------------------------------------------
+
+        if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
+           (len(papszLayers) == 1 or nSrcLayerCount == 1) and pszNewLayerName is None:
+            try:
+                mode = os.stat(pszDestDataSource).st_mode
+                if (mode & stat.S_IFDIR) == 0:
+                    pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0]
+            except:
+                pass
+
+        if bDisplayProgress and bSrcIsOSM:
+            pfnProgress = progress_func
+            pProgressArg = progress_data
+
+# --------------------------------------------------------------------
+#      If no target layer specified, use all source layers.
+# --------------------------------------------------------------------
+        if len(papszLayers) == 0:
+            papszLayers = [ None for i in range(nSrcLayerCount) ]
+            for iLayer in range(nSrcLayerCount):
+                poLayer = poDS.GetLayer(iLayer)
+                if poLayer is None:
+                    print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer)
+                    return False
+
+                papszLayers[iLayer] = poLayer.GetName()
+        else:
+            if bSrcIsOSM:
+                osInterestLayers = "SET interest_layers ="
+                for iLayer in range(len(papszLayers)):
+                    if iLayer != 0:
+                        osInterestLayers = osInterestLayers + ","
+                    osInterestLayers = osInterestLayers + papszLayers[iLayer]
+
+                poDS.ExecuteSQL(osInterestLayers, None, None)
+
+# --------------------------------------------------------------------
+#      First pass to set filters and create target layers.
+# --------------------------------------------------------------------
+        for iLayer in range(nSrcLayerCount):
+            poLayer = poDS.GetLayer(iLayer)
+            if poLayer is None:
+                print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer)
+                return False
+
+            pasAssocLayers[iLayer].poSrcLayer = poLayer
+
+            if CSLFindString(papszLayers, poLayer.GetName()) >= 0:
+                if pszWHERE is not None:
+                    if poLayer.SetAttributeFilter( pszWHERE ) != 0:
+                        print("FAILURE: SetAttributeFilter(%s) on layer '%s' failed.\n" % (pszWHERE, poLayer.GetName()) )
+                        if not bSkipFailures:
+                            return False
+
+                if poSpatialFilter is not None:
+                    poLayer.SetSpatialFilter( poSpatialFilter )
+
+                psInfo = SetupTargetLayer( poDS, \
+                                           poLayer, \
+                                           poODS, \
+                                           papszLCO, \
+                                           pszNewLayerName, \
+                                           bTransform, \
+                                           poOutputSRS, \
+                                           bNullifyOutputSRS, \
+                                           poSourceSRS, \
+                                           papszSelFields, \
+                                           bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \
+                                           papszFieldTypesToString, \
+                                           bWrapDateline, \
+                                           bExplodeCollections, \
+                                           pszZField, \
+                                           pszWHERE )
+
+                if psInfo is None and not bSkipFailures:
+                    return False
+
+                pasAssocLayers[iLayer].psInfo = psInfo
+            else:
+                pasAssocLayers[iLayer].psInfo = None
+
+# --------------------------------------------------------------------
+#      Second pass to process features in a interleaved layer mode.
+# --------------------------------------------------------------------
+        bHasLayersNonEmpty = True
+        while bHasLayersNonEmpty:
+            bHasLayersNonEmpty = False
+
+            for iLayer in range(nSrcLayerCount):
+                poLayer = pasAssocLayers[iLayer].poSrcLayer
+                psInfo = pasAssocLayers[iLayer].psInfo
+                anReadFeatureCount = [0]
+
+                if psInfo is not None:
+                    if not TranslateLayer(psInfo, poDS, poLayer, poODS, \
+                                        poOutputSRS, bNullifyOutputSRS,  \
+                                        eGType, bPromoteToMulti, nCoordDim, \
+                                        eGeomOp, dfGeomOpParam,  \
+                                        0,  \
+                                        poClipSrc, poClipDst,  \
+                                        bExplodeCollections,  \
+                                        nSrcFileSize,  \
+                                        anReadFeatureCount, \
+                                        pfnProgress, pProgressArg ) \
+                        and not bSkipFailures:
+                        print(
+                                "Terminating translation prematurely after failed\n" + \
+                                "translation of layer " + poLayer.GetName() + " (use -skipfailures to skip errors)")
+
+                        return False
+                else:
+                    # No matching target layer : just consumes the features
+
+                    poFeature = poLayer.GetNextFeature()
+                    while poFeature is not None:
+                        anReadFeatureCount[0] = anReadFeatureCount[0] + 1
+                        poFeature = poLayer.GetNextFeature()
+
+                if anReadFeatureCount[0] != 0:
+                    bHasLayersNonEmpty = True
+
+    else:
+
+        nLayerCount = 0
+        papoLayers = []
+
+# --------------------------------------------------------------------
+#      Process each data source layer.
+# --------------------------------------------------------------------
+        if len(papszLayers) == 0:
+            nLayerCount = poDS.GetLayerCount()
+            papoLayers = [None for i in range(nLayerCount)]
+            iLayer = 0
+
+            for iLayer in range(nLayerCount):
+                poLayer = poDS.GetLayer(iLayer)
+
+                if poLayer is None:
+                    print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer)
+                    return False
+
+                papoLayers[iLayer] = poLayer
+                iLayer = iLayer + 1
+
+# --------------------------------------------------------------------
+#      Process specified data source layers.
+# --------------------------------------------------------------------
+        else:
+            nLayerCount = len(papszLayers)
+            papoLayers = [None for i in range(nLayerCount)]
+            iLayer = 0
+
+            for layername in papszLayers:
+                poLayer = poDS.GetLayerByName(layername)
+
+                if poLayer is None:
+                    print("FAILURE: Couldn't fetch advertised layer %s!" % layername)
+                    return False
+
+                papoLayers[iLayer] = poLayer
+                iLayer = iLayer + 1
+
+        panLayerCountFeatures = [0 for i in range(nLayerCount)]
+        nCountLayersFeatures = 0
+        nAccCountFeatures = 0
+
+        # First pass to apply filters and count all features if necessary
+        for iLayer in range(nLayerCount):
+            poLayer = papoLayers[iLayer]
+
+            if pszWHERE is not None:
+                if poLayer.SetAttributeFilter( pszWHERE ) != 0:
+                    print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE)
+                    if not bSkipFailures:
+                        return False
+
+            if poSpatialFilter is not None:
+                poLayer.SetSpatialFilter( poSpatialFilter )
+
+            if bDisplayProgress and not bSrcIsOSM:
+                if not poLayer.TestCapability(ogr.OLCFastFeatureCount):
+                    print("Progress turned off as fast feature count is not available.")
+                    bDisplayProgress = False
+                else:
+                    panLayerCountFeatures[iLayer] = poLayer.GetFeatureCount()
+                    nCountLayersFeatures += panLayerCountFeatures[iLayer]
+
+        # Second pass to do the real job
+        for iLayer in range(nLayerCount):
+            poLayer = papoLayers[iLayer]
+
+            if bDisplayProgress:
+                if bSrcIsOSM:
+                    pfnProgress = progress_func
+                    pProgressArg = progress_data
+                else:
+                    pfnProgress = ScaledProgressFunc
+                    pProgressArg = ScaledProgressObject( \
+                            nAccCountFeatures * 1.0 / nCountLayersFeatures, \
+                            (nAccCountFeatures + panLayerCountFeatures[iLayer]) * 1.0 / nCountLayersFeatures, \
+                            progress_func, progress_data)
+
+            nAccCountFeatures += panLayerCountFeatures[iLayer]
+
+# --------------------------------------------------------------------
+#      Special case to improve user experience when translating into
+#      single file shapefile and source has only one layer, and that
+#      the layer name isn't specified
+# --------------------------------------------------------------------
+            if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
+                nLayerCount == 1 and pszNewLayerName is None:
+                try:
+                    mode = os.stat(pszDestDataSource).st_mode
+                    if (mode & stat.S_IFDIR) == 0:
+                        pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0]
+                except:
+                    pass
+
+
+            psInfo = SetupTargetLayer( poDS, \
+                                       poLayer, \
+                                       poODS, \
+                                       papszLCO, \
+                                       pszNewLayerName, \
+                                       bTransform, \
+                                       poOutputSRS, \
+                                       bNullifyOutputSRS, \
+                                       poSourceSRS, \
+                                       papszSelFields, \
+                                       bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \
+                                       papszFieldTypesToString, \
+                                       bWrapDateline, \
+                                       bExplodeCollections, \
+                                       pszZField, \
+                                       pszWHERE )
+
+            poLayer.ResetReading()
+
+            if (psInfo is None or \
+                not TranslateLayer( psInfo, poDS, poLayer, poODS, \
+                                    poOutputSRS, bNullifyOutputSRS, \
+                                    eGType, bPromoteToMulti, nCoordDim, \
+                                    eGeomOp, dfGeomOpParam, \
+                                    panLayerCountFeatures[iLayer], \
+                                    poClipSrc, poClipDst, \
+                                    bExplodeCollections, \
+                                    nSrcFileSize, None, \
+                                    pfnProgress, pProgressArg )) \
+                and not bSkipFailures:
+                print(
+                        "Terminating translation prematurely after failed\n" + \
+                        "translation of layer " + poLayer.GetLayerDefn().GetName() + " (use -skipfailures to skip errors)")
+
+                return False
+
+# --------------------------------------------------------------------
+#      Close down.
+# --------------------------------------------------------------------
+    # We must explicitly destroy the output dataset in order the file
+    # to be properly closed !
+    poODS.Destroy()
+    poDS.Destroy()
+
+    return True
+
+#**********************************************************************
+#                               Usage()
+#**********************************************************************
+
+def Usage():
+
+    print( "Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update] [-gt n]\n" + \
+            "               [-select field_list] [-where restricted_where] \n" + \
+            "               [-progress] [-sql <sql statement>] \n" + \
+            "               [-spat xmin ymin xmax ymax] [-preserve_fid] [-fid FID]\n" + \
+            "               [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]\n" + \
+            "               [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]\n" + \
+            "               [-simplify tolerance]\n" + \
+            #// "               [-segmentize max_dist] [-fieldTypeToString All|(type1[,type2]*)]\n" + \
+            "               [-fieldTypeToString All|(type1[,type2]*)] [-explodecollections] \n" + \
+            "               dst_datasource_name src_datasource_name\n" + \
+            "               [-lco NAME=VALUE] [-nln name] [-nlt type] [-dim 2|3] [layer [layer ...]]\n" + \
+            "\n" + \
+            " -f format_name: output file format name, possible values are:")
+
+    for iDriver in range(ogr.GetDriverCount()):
+        poDriver = ogr.GetDriver(iDriver)
+
+        if poDriver.TestCapability( ogr.ODrCCreateDataSource ):
+            print( "     -f \"" + poDriver.GetName() + "\"" )
+
+    print( " -append: Append to existing layer instead of creating new if it exists\n" + \
+            " -overwrite: delete the output layer and recreate it empty\n" + \
+            " -update: Open existing output datasource in update mode\n" + \
+            " -progress: Display progress on terminal. Only works if input layers have the \"fast feature count\" capability\n" + \
+            " -select field_list: Comma-delimited list of fields from input layer to\n" + \
+            "                     copy to the new layer (defaults to all)\n" + \
+            " -where restricted_where: Attribute query (like SQL WHERE)\n" + \
+            " -sql statement: Execute given SQL statement and save result.\n" + \
+            " -skipfailures: skip features or layers that fail to convert\n" + \
+            " -gt n: group n features per transaction (default 200)\n" + \
+            " -spat xmin ymin xmax ymax: spatial query extents\n" + \
+            " -simplify tolerance: distance tolerance for simplification.\n" + \
+            #//" -segmentize max_dist: maximum distance between 2 nodes.\n" + \
+            #//"                       Used to create intermediate points\n" + \
+            " -dsco NAME=VALUE: Dataset creation option (format specific)\n" + \
+            " -lco  NAME=VALUE: Layer creation option (format specific)\n" + \
+            " -nln name: Assign an alternate name to the new layer\n" + \
+            " -nlt type: Force a geometry type for new layer.  One of NONE, GEOMETRY,\n" + \
+            "      POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT,\n" + \
+            "      MULTIPOLYGON, or MULTILINESTRING.  Add \"25D\" for 3D layers.\n" + \
+            "      Default is type of source layer.\n" + \
+            " -dim dimension: Force the coordinate dimension to the specified value.\n" + \
+            " -fieldTypeToString type1,...: Converts fields of specified types to\n" + \
+            "      fields of type string in the new layer. Valid types are : \n" + \
+            "      Integer, Real, String, Date, Time, DateTime, Binary, IntegerList, RealList,\n" + \
+            "      StringList. Special value All can be used to convert all fields to strings.")
+
+    print(" -a_srs srs_def: Assign an output SRS\n"
+        " -t_srs srs_def: Reproject/transform to this SRS on output\n"
+        " -s_srs srs_def: Override source SRS\n"
+        "\n"
+        " Srs_def can be a full WKT definition (hard to escape properly),\n"
+        " or a well known definition (i.e. EPSG:4326) or a file with a WKT\n"
+        " definition." )
+
+    return False
+
+def CSLFindString(v, mystr):
+    i = 0
+    for strIter in v:
+        if EQUAL(strIter, mystr):
+            return i
+        i = i + 1
+    return -1
+
+def IsNumber( pszStr):
+    try:
+        (float)(pszStr)
+        return True
+    except:
+        return False
+
+def LoadGeometry( pszDS, pszSQL, pszLyr, pszWhere):
+    poGeom = None
+
+    poDS = ogr.Open( pszDS, False )
+    if poDS is None:
+        return None
+
+    if pszSQL is not None:
+        poLyr = poDS.ExecuteSQL( pszSQL, None, None )
+    elif pszLyr is not None:
+        poLyr = poDS.GetLayerByName(pszLyr)
+    else:
+        poLyr = poDS.GetLayer(0)
+
+    if poLyr is None:
+        print("Failed to identify source layer from datasource.")
+        poDS.Destroy()
+        return None
+
+    if pszWhere is not None:
+        poLyr.SetAttributeFilter(pszWhere)
+
+    poFeat = poLyr.GetNextFeature()
+    while poFeat is not None:
+        poSrcGeom = poFeat.GetGeometryRef()
+        if poSrcGeom is not None:
+            eType = wkbFlatten(poSrcGeom.GetGeometryType())
+
+            if poGeom is None:
+                poGeom = ogr.Geometry( ogr.wkbMultiPolygon )
+
+            if eType == ogr.wkbPolygon:
+                poGeom.AddGeometry( poSrcGeom )
+            elif eType == ogr.wkbMultiPolygon:
+                for iGeom in range(poSrcGeom.GetGeometryCount()):
+                    poGeom.AddGeometry(poSrcGeom.GetGeometryRef(iGeom) )
+
+            else:
+                print("ERROR: Geometry not of polygon type." )
+                if pszSQL is not None:
+                    poDS.ReleaseResultSet( poLyr )
+                poDS.Destroy()
+                return None
+
+        poFeat = poLyr.GetNextFeature()
+
+    if pszSQL is not None:
+        poDS.ReleaseResultSet( poLyr )
+    poDS.Destroy()
+
+    return poGeom
+
+
+def wkbFlatten(x):
+    return x & (~ogr.wkb25DBit)
+
+#**********************************************************************
+#                               SetZ()
+#**********************************************************************
+
+def SetZ (poGeom, dfZ ):
+
+    if poGeom is None:
+        return
+
+    eGType = wkbFlatten(poGeom.GetGeometryType())
+    if eGType == ogr.wkbPoint:
+        poGeom.SetPoint(0, poGeom.GetX(), poGeom.GetY(), dfZ)
+
+    elif eGType == ogr.wkbLineString or \
+         eGType == ogr.wkbLinearRing:
+        for i in range(poGeom.GetPointCount()):
+            poGeom.SetPoint(i, poGeom.GetX(i), poGeom.GetY(i), dfZ)
+
+    elif eGType == ogr.wkbPolygon or \
+         eGType == ogr.wkbMultiPoint or \
+         eGType == ogr.wkbMultiLineString or \
+         eGType == ogr.wkbMultiPolygon or \
+         eGType == ogr.wkbGeometryCollection:
+        for i in range(poGeom.GetGeometryCount()):
+            SetZ(poGeom.GetGeometryRef(i), dfZ)
+
+#**********************************************************************
+#                         SetupTargetLayer()
+#**********************************************************************
+
+def SetupTargetLayer( poSrcDS, poSrcLayer, poDstDS, papszLCO, pszNewLayerName, \
+                    bTransform,  poOutputSRS, bNullifyOutputSRS, poSourceSRS, papszSelFields, \
+                    bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \
+                    papszFieldTypesToString, bWrapDateline, \
+                    bExplodeCollections, pszZField, pszWHERE) :
+
+    if pszNewLayerName is None:
+        pszNewLayerName = poSrcLayer.GetLayerDefn().GetName()
+
+# --------------------------------------------------------------------
+#      Setup coordinate transformation if we need it.
+# --------------------------------------------------------------------
+    poCT = None
+
+    if bTransform:
+        if poSourceSRS is None:
+            poSourceSRS = poSrcLayer.GetSpatialRef()
+
+        if poSourceSRS is None:
+            print("Can't transform coordinates, source layer has no\n" + \
+                    "coordinate system.  Use -s_srs to set one." )
+            return None
+
+        poCT = osr.CoordinateTransformation( poSourceSRS, poOutputSRS )
+        if gdal.GetLastErrorMsg().find( 'Unable to load PROJ.4 library' ) != -1:
+            poCT = None
+
+        if poCT is None:
+            pszWKT = None
+
+            print("Failed to create coordinate transformation between the\n" + \
+                "following coordinate systems.  This may be because they\n" + \
+                "are not transformable, or because projection services\n" + \
+                "(PROJ.4 DLL/.so) could not be loaded." )
+
+            pszWKT = poSourceSRS.ExportToPrettyWkt( 0 )
+            print( "Source:\n" + pszWKT )
+
+            pszWKT = poOutputSRS.ExportToPrettyWkt( 0 )
+            print( "Target:\n" + pszWKT )
+            return None
+
+# --------------------------------------------------------------------
+#      Get other info.
+# --------------------------------------------------------------------
+    poSrcFDefn = poSrcLayer.GetLayerDefn()
+
+    if poOutputSRS is None and not bNullifyOutputSRS:
+        poOutputSRS = poSrcLayer.GetSpatialRef()
+
+# --------------------------------------------------------------------
+#      Find the layer.
+# --------------------------------------------------------------------
+
+    # GetLayerByName() can instantiate layers that would have been
+    # 'hidden' otherwise, for example, non-spatial tables in a
+    # PostGIS-enabled database, so this apparently useless command is
+    # not useless. (#4012)
+    gdal.PushErrorHandler('CPLQuietErrorHandler')
+    poDstLayer = poDstDS.GetLayerByName(pszNewLayerName)
+    gdal.PopErrorHandler()
+    gdal.ErrorReset()
+
+    iLayer = -1
+    if poDstLayer is not None:
+        nLayerCount = poDstDS.GetLayerCount()
+        for iLayer in range(nLayerCount):
+            poLayer = poDstDS.GetLayer(iLayer)
+            # The .cpp version compares on pointers directly, but we cannot
+            # do this with swig object, so just compare the names.
+            if poLayer is not None \
+                and poLayer.GetName() == poDstLayer.GetName():
+                break
+
+        if (iLayer == nLayerCount):
+            # Shouldn't happen with an ideal driver
+            poDstLayer = None
+
+# --------------------------------------------------------------------
+#      If the user requested overwrite, and we have the layer in
+#      question we need to delete it now so it will get recreated
+#      (overwritten).
+# --------------------------------------------------------------------
+    if poDstLayer is not None and bOverwrite:
+        if poDstDS.DeleteLayer( iLayer ) != 0:
+            print("DeleteLayer() failed when overwrite requested." )
+            return None
+
+        poDstLayer = None
+
+# --------------------------------------------------------------------
+#      If the layer does not exist, then create it.
+# --------------------------------------------------------------------
+    if poDstLayer is None:
+        if eGType == -2:
+            eGType = poSrcFDefn.GetGeomType()
+
+            n25DBit = eGType & ogr.wkb25DBit
+            if bPromoteToMulti:
+                if wkbFlatten(eGType) == ogr.wkbLineString:
+                    eGType = ogr.wkbMultiLineString | n25DBit
+                elif wkbFlatten(eGType) == ogr.wkbPolygon:
+                    eGType = ogr.wkbMultiPolygon | n25DBit
+
+            if bExplodeCollections:
+                if wkbFlatten(eGType) == ogr.wkbMultiPoint:
+                    eGType = ogr.wkbPoint | n25DBit
+                elif wkbFlatten(eGType) == ogr.wkbMultiLineString:
+                    eGType = ogr.wkbLineString | n25DBit
+                elif wkbFlatten(eGType) == ogr.wkbMultiPolygon:
+                    eGType = ogr.wkbPolygon | n25DBit
+                elif wkbFlatten(eGType) == ogr.wkbGeometryCollection:
+                    eGType = ogr.wkbUnknown | n25DBit
+
+            if pszZField is not None:
+                eGType = eGType | ogr.wkb25DBit
+
+        if nCoordDim == 2:
+            eGType = eGType & ~ogr.wkb25DBit
+        elif nCoordDim == 3:
+            eGType = eGType | ogr.wkb25DBit
+
+        if poDstDS.TestCapability( ogr.ODsCCreateLayer ) == False:
+            print("Layer " + pszNewLayerName + "not found, and CreateLayer not supported by driver.")
+            return None
+
+        gdal.ErrorReset()
+
+        poDstLayer = poDstDS.CreateLayer( pszNewLayerName, poOutputSRS, \
+                                            eGType, papszLCO )
+
+        if poDstLayer is None:
+            return None
+
+        bAppend = False
+
+# --------------------------------------------------------------------
+#      Otherwise we will append to it, if append was requested.
+# --------------------------------------------------------------------
+    elif not bAppend:
+        print("FAILED: Layer " + pszNewLayerName + "already exists, and -append not specified.\n" + \
+                            "        Consider using -append, or -overwrite.")
+        return None
+    else:
+        if len(papszLCO) > 0:
+            print("WARNING: Layer creation options ignored since an existing layer is\n" + \
+                    "         being appended to." )
+
+# --------------------------------------------------------------------
+#      Add fields.  Default to copy all field.
+#      If only a subset of all fields requested, then output only
+#      the selected fields, and in the order that they were
+#      selected.
+# --------------------------------------------------------------------
+
+    # Initialize the index-to-index map to -1's
+    nSrcFieldCount = poSrcFDefn.GetFieldCount()
+    panMap = [ -1 for i in range(nSrcFieldCount) ]
+
+    poDstFDefn = poDstLayer.GetLayerDefn()
+
+    if papszSelFields is not None and not bAppend:
+
+        nDstFieldCount = 0
+        if poDstFDefn is not None:
+            nDstFieldCount = poDstFDefn.GetFieldCount()
+
+        for iField in range(len(papszSelFields)):
+
+            iSrcField = poSrcFDefn.GetFieldIndex(papszSelFields[iField])
+            if iSrcField >= 0:
+                poSrcFieldDefn = poSrcFDefn.GetFieldDefn(iSrcField)
+                oFieldDefn = ogr.FieldDefn( poSrcFieldDefn.GetNameRef(),
+                                            poSrcFieldDefn.GetType() )
+                oFieldDefn.SetWidth( poSrcFieldDefn.GetWidth() )
+                oFieldDefn.SetPrecision( poSrcFieldDefn.GetPrecision() )
+
+                if papszFieldTypesToString is not None and \
+                    (CSLFindString(papszFieldTypesToString, "All") != -1 or \
+                    CSLFindString(papszFieldTypesToString, \
+                                ogr.GetFieldTypeName(poSrcFieldDefn.GetType())) != -1):
+
+                    oFieldDefn.SetType(ogr.OFTString)
+
+                # The field may have been already created at layer creation
+                iDstField = -1
+                if poDstFDefn is not None:
+                    iDstField = poDstFDefn.GetFieldIndex(oFieldDefn.GetNameRef())
+                if iDstField >= 0:
+                    panMap[iSrcField] = iDstField
+                elif poDstLayer.CreateField( oFieldDefn ) == 0:
+                    # now that we've created a field, GetLayerDefn() won't return NULL
+                    if poDstFDefn is None:
+                        poDstFDefn = poDstLayer.GetLayerDefn()
+
+                    # Sanity check : if it fails, the driver is buggy
+                    if poDstFDefn is not None and \
+                        poDstFDefn.GetFieldCount() != nDstFieldCount + 1:
+                        print("The output driver has claimed to have added the %s field, but it did not!" %  oFieldDefn.GetNameRef() )
+                    else:
+                        panMap[iSrcField] = nDstFieldCount
+                        nDstFieldCount = nDstFieldCount + 1
+
+            else:
+                print("Field '" + papszSelFields[iField] + "' not found in source layer.")
+                if not bSkipFailures:
+                    return None
+
+        # --------------------------------------------------------------------
+        # Use SetIgnoredFields() on source layer if available
+        # --------------------------------------------------------------------
+
+        # Here we differ from the ogr2ogr.cpp implementation since the OGRFeatureQuery
+        # isn't mapped to swig. So in that case just don't use SetIgnoredFields()
+        # to avoid issue raised in #4015
+        if poSrcLayer.TestCapability(ogr.OLCIgnoreFields) and pszWHERE is None:
+            papszIgnoredFields = []
+            for iSrcField in range(nSrcFieldCount):
+                pszFieldName = poSrcFDefn.GetFieldDefn(iSrcField).GetNameRef()
+                bFieldRequested = False
+                for iField in range(len(papszSelFields)):
+                    if EQUAL(pszFieldName, papszSelFields[iField]):
+                        bFieldRequested = True
+                        break
+
+                if pszZField is not None and EQUAL(pszFieldName, pszZField):
+                    bFieldRequested = True
+
+                # If source field not requested, add it to ignored files list
+                if not bFieldRequested:
+                    papszIgnoredFields.append(pszFieldName)
+
+            poSrcLayer.SetIgnoredFields(papszIgnoredFields)
+
+    elif not bAppend:
+
+        nDstFieldCount = 0
+        if poDstFDefn is not None:
+            nDstFieldCount = poDstFDefn.GetFieldCount()
+
+        for iField in range(nSrcFieldCount):
+
+            poSrcFieldDefn = poSrcFDefn.GetFieldDefn(iField)
+            oFieldDefn = ogr.FieldDefn( poSrcFieldDefn.GetNameRef(),
+                                        poSrcFieldDefn.GetType() )
+            oFieldDefn.SetWidth( poSrcFieldDefn.GetWidth() )
+            oFieldDefn.SetPrecision( poSrcFieldDefn.GetPrecision() )
+
+            if papszFieldTypesToString is not None and \
+                (CSLFindString(papszFieldTypesToString, "All") != -1 or \
+                CSLFindString(papszFieldTypesToString, \
+                            ogr.GetFieldTypeName(poSrcFieldDefn.GetType())) != -1):
+
+                oFieldDefn.SetType(ogr.OFTString)
+
+            # The field may have been already created at layer creation
+            iDstField = -1
+            if poDstFDefn is not None:
+                 iDstField = poDstFDefn.GetFieldIndex(oFieldDefn.GetNameRef())
+            if iDstField >= 0:
+                panMap[iField] = iDstField
+            elif poDstLayer.CreateField( oFieldDefn ) == 0:
+                # now that we've created a field, GetLayerDefn() won't return NULL
+                if poDstFDefn is None:
+                    poDstFDefn = poDstLayer.GetLayerDefn()
+
+                # Sanity check : if it fails, the driver is buggy
+                if poDstFDefn is not None and \
+                    poDstFDefn.GetFieldCount() != nDstFieldCount + 1:
+                    print("The output driver has claimed to have added the %s field, but it did not!" %  oFieldDefn.GetNameRef() )
+                else:
+                    panMap[iField] = nDstFieldCount
+                    nDstFieldCount = nDstFieldCount + 1
+
+    else:
+        # For an existing layer, build the map by fetching the index in the destination
+        # layer for each source field
+        if poDstFDefn is None:
+            print( "poDstFDefn == NULL.\n" )
+            return None
+
+        for iField in range(nSrcFieldCount):
+            poSrcFieldDefn = poSrcFDefn.GetFieldDefn(iField)
+            iDstField = poDstFDefn.GetFieldIndex(poSrcFieldDefn.GetNameRef())
+            if iDstField >= 0:
+                panMap[iField] = iDstField
+
+    iSrcZField = -1
+    if pszZField is not None:
+        iSrcZField = poSrcFDefn.GetFieldIndex(pszZField)
+
+    psInfo = TargetLayerInfo()
+    psInfo.poDstLayer = poDstLayer
+    psInfo.poCT = poCT
+    #psInfo.papszTransformOptions = papszTransformOptions
+    psInfo.panMap = panMap
+    psInfo.iSrcZField = iSrcZField
+
+    return psInfo
+
+#**********************************************************************
+#                           TranslateLayer()
+#**********************************************************************
+
+def TranslateLayer( psInfo, poSrcDS, poSrcLayer, poDstDS,  \
+                    poOutputSRS, bNullifyOutputSRS, \
+                    eGType, bPromoteToMulti, nCoordDim, eGeomOp, dfGeomOpParam, \
+                    nCountLayerFeatures, \
+                    poClipSrc, poClipDst, bExplodeCollections, nSrcFileSize, \
+                    pnReadFeatureCount, pfnProgress, pProgressArg) :
+
+    bForceToPolygon = False
+    bForceToMultiPolygon = False
+    bForceToMultiLineString = False
+
+    poDstLayer = psInfo.poDstLayer
+    #papszTransformOptions = psInfo.papszTransformOptions
+    poCT = psInfo.poCT
+    panMap = psInfo.panMap
+    iSrcZField = psInfo.iSrcZField
+
+    if poOutputSRS is None and not bNullifyOutputSRS:
+        poOutputSRS = poSrcLayer.GetSpatialRef()
+
+    if wkbFlatten(eGType) == ogr.wkbPolygon:
+        bForceToPolygon = True
+    elif wkbFlatten(eGType) == ogr.wkbMultiPolygon:
+        bForceToMultiPolygon = True
+    elif wkbFlatten(eGType) == ogr.wkbMultiLineString:
+        bForceToMultiLineString = True
+
+# --------------------------------------------------------------------
+#      Transfer features.
+# --------------------------------------------------------------------
+    nFeaturesInTransaction = 0
+    nCount = 0
+
+    if nGroupTransactions > 0:
+        poDstLayer.StartTransaction()
+
+    while True:
+        poDstFeature = None
+
+        if nFIDToFetch != ogr.NullFID:
+
+            #// Only fetch feature on first pass.
+            if nFeaturesInTransaction == 0:
+                poFeature = poSrcLayer.GetFeature(nFIDToFetch)
+            else:
+                poFeature = None
+
+        else:
+            poFeature = poSrcLayer.GetNextFeature()
+
+        if poFeature is None:
+            break
+
+        nParts = 0
+        nIters = 1
+        if bExplodeCollections:
+            poSrcGeometry = poFeature.GetGeometryRef()
+            if poSrcGeometry is not None:
+                eSrcType = wkbFlatten(poSrcGeometry.GetGeometryType())
+                if eSrcType == ogr.wkbMultiPoint or \
+                   eSrcType == ogr.wkbMultiLineString or \
+                   eSrcType == ogr.wkbMultiPolygon or \
+                   eSrcType == ogr.wkbGeometryCollection:
+                        nParts = poSrcGeometry.GetGeometryCount()
+                        nIters = nParts
+                        if nIters == 0:
+                            nIters = 1
+
+        for iPart in range(nIters):
+            nFeaturesInTransaction = nFeaturesInTransaction + 1
+            if nFeaturesInTransaction == nGroupTransactions:
+                poDstLayer.CommitTransaction()
+                poDstLayer.StartTransaction()
+                nFeaturesInTransaction = 0
+
+            gdal.ErrorReset()
+            poDstFeature = ogr.Feature( poDstLayer.GetLayerDefn() )
+
+            if poDstFeature.SetFromWithMap( poFeature, 1, panMap ) != 0:
+
+                if nGroupTransactions > 0:
+                    poDstLayer.CommitTransaction()
+
+                print("Unable to translate feature %d from layer %s" % (poFeature.GetFID() , poSrcLayer.GetName() ))
+
+                return False
+
+            if bPreserveFID:
+                poDstFeature.SetFID( poFeature.GetFID() )
+
+            poDstGeometry = poDstFeature.GetGeometryRef()
+            if poDstGeometry is not None:
+
+                if nParts > 0:
+                    # For -explodecollections, extract the iPart(th) of the geometry
+                    poPart = poDstGeometry.GetGeometryRef(iPart).Clone()
+                    poDstFeature.SetGeometryDirectly(poPart)
+                    poDstGeometry = poPart
+
+                if iSrcZField != -1:
+                    SetZ(poDstGeometry, poFeature.GetFieldAsDouble(iSrcZField))
+                    # This will correct the coordinate dimension to 3
+                    poDupGeometry = poDstGeometry.Clone()
+                    poDstFeature.SetGeometryDirectly(poDupGeometry)
+                    poDstGeometry = poDupGeometry
+
+
+                if nCoordDim == 2 or nCoordDim == 3:
+                    poDstGeometry.SetCoordinateDimension( nCoordDim )
+
+                if eGeomOp == GeomOperation.SEGMENTIZE:
+                    pass
+                    #if (poDstFeature.GetGeometryRef() is not None and dfGeomOpParam > 0)
+                    #    poDstFeature.GetGeometryRef().segmentize(dfGeomOpParam);
+                elif eGeomOp == GeomOperation.SIMPLIFY_PRESERVE_TOPOLOGY and dfGeomOpParam > 0:
+                    poNewGeom = poDstGeometry.SimplifyPreserveTopology(dfGeomOpParam)
+                    if poNewGeom is not None:
+                        poDstFeature.SetGeometryDirectly(poNewGeom)
+                        poDstGeometry = poNewGeom
+
+                if poClipSrc is not None:
+                    poClipped = poDstGeometry.Intersection(poClipSrc)
+                    if poClipped is None or poClipped.IsEmpty():
+                        # Report progress
+                        nCount = nCount +1
+                        if pfnProgress is not None:
+                            pfnProgress(nCount * 1.0 / nCountLayerFeatures, "", pProgressArg)
+                        continue
+
+                    poDstFeature.SetGeometryDirectly(poClipped)
+                    poDstGeometry = poClipped
+
+                if poCT is not None:
+                    eErr = poDstGeometry.Transform( poCT )
+                    if eErr != 0:
+                        if nGroupTransactions > 0:
+                            poDstLayer.CommitTransaction()
+
+                        print("Failed to reproject feature %d (geometry probably out of source or destination SRS)." % poFeature.GetFID())
+                        if not bSkipFailures:
+                            return False
+
+                elif poOutputSRS is not None:
+                    poDstGeometry.AssignSpatialReference(poOutputSRS)
+
+                if poClipDst is not None:
+                    poClipped = poDstGeometry.Intersection(poClipDst)
+                    if poClipped is None or poClipped.IsEmpty():
+                        continue
+
+                    poDstFeature.SetGeometryDirectly(poClipped)
+                    poDstGeometry = poClipped
+
+                if bForceToPolygon:
+                    poDstFeature.SetGeometryDirectly(ogr.ForceToPolygon(poDstGeometry))
+
+                elif bForceToMultiPolygon or \
+                        (bPromoteToMulti and wkbFlatten(poDstGeometry.GetGeometryType()) == ogr.wkbPolygon):
+                    poDstFeature.SetGeometryDirectly(ogr.ForceToMultiPolygon(poDstGeometry))
+
+                elif bForceToMultiLineString or \
+                        (bPromoteToMulti and wkbFlatten(poDstGeometry.GetGeometryType()) == ogr.wkbLineString):
+                    poDstFeature.SetGeometryDirectly(ogr.ForceToMultiLineString(poDstGeometry))
+
+            gdal.ErrorReset()
+            if poDstLayer.CreateFeature( poDstFeature ) != 0 and not bSkipFailures:
+                if nGroupTransactions > 0:
+                    poDstLayer.RollbackTransaction()
+
+                return False
+
+        # Report progress
+        nCount = nCount  + 1
+        if pfnProgress is not None:
+            if nSrcFileSize != 0:
+                if (nCount % 1000) == 0:
+                    poFCLayer = poSrcDS.ExecuteSQL("GetBytesRead()", None, None)
+                    if poFCLayer is not None:
+                        poFeat = poFCLayer.GetNextFeature()
+                        if poFeat is not None:
+                            pszReadSize = poFeat.GetFieldAsString(0)
+                            nReadSize = int(pszReadSize)
+                            pfnProgress(nReadSize * 1.0 / nSrcFileSize, "", pProgressArg)
+                    poSrcDS.ReleaseResultSet(poFCLayer)
+            else:
+                pfnProgress(nCount * 1.0 / nCountLayerFeatures, "", pProgressArg)
+
+        if pnReadFeatureCount is not None:
+            pnReadFeatureCount[0] = nCount
+
+    if nGroupTransactions > 0:
+        poDstLayer.CommitTransaction()
+
+    return True
+
+if __name__ == '__main__':
+    version_num = int(gdal.VersionInfo('VERSION_NUM'))
+    if version_num < 1800: # because of ogr.GetFieldTypeName
+        print('ERROR: Python bindings of GDAL 1.8.0 or later required')
+        sys.exit(1)
+
+    if not main(sys.argv):
+        sys.exit(1)
+    else:
+        sys.exit(0)

+ 80 - 0
pb_tool.cfg

@@ -0,0 +1,80 @@
+#/***************************************************************************
+# Atlas
+#
+# Configuration file for plugin builder tool (pb_tool)
+# Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+#                            -------------------
+#       begin               : 2019-02-15
+#       copyright           : (C) 2019 by jan vrobel
+#       email               : vrobel.jan@seznam.cz
+# ***************************************************************************/
+#
+#/***************************************************************************
+# *                                                                         *
+# *   This program is free software; you can redistribute it and/or modify  *
+# *   it under the terms of the GNU General Public License as published by  *
+# *   the Free Software Foundation; either version 2 of the License, or     *
+# *   (at your option) any later version.                                   *
+# *                                                                         *
+# ***************************************************************************/
+# 
+# 
+# You can install pb_tool using:
+#  pip install http://geoapt.net/files/pb_tool.zip
+# 
+# Consider doing your development (and install of pb_tool) in a virtualenv.
+# 
+# For details on setting up and using pb_tool, see:
+#  http://g-sherman.github.io/plugin_build_tool/
+#
+# Issues and pull requests here:
+# https://github.com/g-sherman/plugin_build_tool:
+# 
+# Sane defaults for your plugin generated by the Plugin Builder are
+# already set below.
+# 
+# As you add Python source files and UI files to your plugin, add
+# them to the appropriate [files] section below.
+
+[plugin]
+# Name of the plugin. This is the name of the directory that will
+# be created in .qgis2/python/plugins
+name: Atlas
+
+# Full path to where you want your plugin directory copied. If empty,
+# the QGIS default path will be used. Don't include the plugin name in
+# the path.
+plugin_path:
+
+[files]
+# Python  files that should be deployed with the plugin
+python_files: __init__.py Atlas.py Atlas_dockwidget.py
+
+# The main dialog file that is loaded (not compiled)
+main_dialog: Atlas_dockwidget_base.ui
+
+# Other ui files for dialogs you create (these will be compiled)
+compiled_ui_files: 
+
+# Resource file(s) that will be compiled
+resource_files: resources.qrc
+
+# Other files required for the plugin
+extras: metadata.txt icon.png
+
+# Other directories to be deployed with the plugin.
+# These must be subdirectories under the plugin directory
+extra_dirs:
+
+# ISO code(s) for any locales (translations), separated by spaces.
+# Corresponding .ts files must exist in the i18n directory
+locales:
+
+[help]
+# the built help directory that should be deployed with the plugin
+dir: help/build/html
+# the name of the directory to target in the deployed plugin 
+target: help
+
+
+

+ 111 - 0
plugin_upload.py

@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+# coding=utf-8
+"""This script uploads a plugin package to the plugin repository.
+        Authors: A. Pasotti, V. Picavet
+        git sha              : $TemplateVCSFormat
+"""
+
+import sys
+import getpass
+import xmlrpc.client
+from optparse import OptionParser
+
+standard_library.install_aliases()
+
+# Configuration
+PROTOCOL = 'https'
+SERVER = 'plugins.qgis.org'
+PORT = '443'
+ENDPOINT = '/plugins/RPC2/'
+VERBOSE = False
+
+
+def main(parameters, arguments):
+    """Main entry point.
+
+    :param parameters: Command line parameters.
+    :param arguments: Command line arguments.
+    """
+    address = "{protocol}://{username}:{password}@{server}:{port}{endpoint}".format(
+        protocol=PROTOCOL,
+        username=parameters.username,
+        password=parameters.password,
+        server=parameters.server,
+        port=parameters.port,
+        endpoint=ENDPOINT)
+    print("Connecting to: %s" % hide_password(address))
+
+    server = xmlrpc.client.ServerProxy(address, verbose=VERBOSE)
+
+    try:
+        with open(arguments[0], 'rb') as handle:
+            plugin_id, version_id = server.plugin.upload(
+                xmlrpc.client.Binary(handle.read()))
+        print("Plugin ID: %s" % plugin_id)
+        print("Version ID: %s" % version_id)
+    except xmlrpc.client.ProtocolError as err:
+        print("A protocol error occurred")
+        print("URL: %s" % hide_password(err.url, 0))
+        print("HTTP/HTTPS headers: %s" % err.headers)
+        print("Error code: %d" % err.errcode)
+        print("Error message: %s" % err.errmsg)
+    except xmlrpc.client.Fault as err:
+        print("A fault occurred")
+        print("Fault code: %d" % err.faultCode)
+        print("Fault string: %s" % err.faultString)
+
+
+def hide_password(url, start=6):
+    """Returns the http url with password part replaced with '*'.
+
+    :param url: URL to upload the plugin to.
+    :type url: str
+
+    :param start: Position of start of password.
+    :type start: int
+    """
+    start_position = url.find(':', start) + 1
+    end_position = url.find('@')
+    return "%s%s%s" % (
+        url[:start_position],
+        '*' * (end_position - start_position),
+        url[end_position:])
+
+
+if __name__ == "__main__":
+    parser = OptionParser(usage="%prog [options] plugin.zip")
+    parser.add_option(
+        "-w", "--password", dest="password",
+        help="Password for plugin site", metavar="******")
+    parser.add_option(
+        "-u", "--username", dest="username",
+        help="Username of plugin site", metavar="user")
+    parser.add_option(
+        "-p", "--port", dest="port",
+        help="Server port to connect to", metavar="80")
+    parser.add_option(
+        "-s", "--server", dest="server",
+        help="Specify server name", metavar="plugins.qgis.org")
+    options, args = parser.parse_args()
+    if len(args) != 1:
+        print("Please specify zip file.\n")
+        parser.print_help()
+        sys.exit(1)
+    if not options.server:
+        options.server = SERVER
+    if not options.port:
+        options.port = PORT
+    if not options.username:
+        # interactive mode
+        username = getpass.getuser()
+        print("Please enter user name [%s] :" % username, end=' ')
+
+        res = input()
+        if res != "":
+            options.username = res
+        else:
+            options.username = username
+    if not options.password:
+        # interactive mode
+        options.password = getpass.getpass()
+    main(options, args)

+ 281 - 0
pylintrc

@@ -0,0 +1,281 @@
+[MASTER]
+
+# Specify a configuration file.
+#rcfile=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Profiled execution.
+profile=no
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=CVS
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+
+[MESSAGES CONTROL]
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time. See also the "--disable" option for examples.
+#enable=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once).You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use"--disable=all --enable=classes
+# --disable=W"
+# see http://stackoverflow.com/questions/21487025/pylint-locally-defined-disables-still-give-warnings-how-to-suppress-them
+disable=locally-disabled,C0103
+
+
+[REPORTS]
+
+# Set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html. You can also give a reporter class, eg
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Put messages in a separate file for each module / package specified on the
+# command line instead of printing them on stdout. Reports (if any) will be
+# written in a file name "pylint_global.[txt|html]".
+files-output=no
+
+# Tells whether to display a full report or only the messages
+reports=yes
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Add a comment according to your evaluation note. This is used by the global
+# evaluation report (RP0004).
+comment=no
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details
+#msg-template=
+
+
+[BASIC]
+
+# Required attributes for module, separated by a comma
+required-attributes=
+
+# List of builtins function names that should not be used, separated by a comma
+bad-functions=map,filter,apply,input
+
+# Regular expression which should only match correct module names
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Regular expression which should only match correct module level names
+const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
+
+# Regular expression which should only match correct class names
+class-rgx=[A-Z_][a-zA-Z0-9]+$
+
+# Regular expression which should only match correct function names
+function-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct method names
+method-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct instance attribute names
+attr-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct argument names
+argument-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct variable names
+variable-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct attribute names in class
+# bodies
+class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
+
+# Regular expression which should only match correct list comprehension /
+# generator expression variable names
+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=i,j,k,ex,Run,_
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=foo,bar,baz,toto,tutu,tata
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=__.*__
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,XXX,TODO
+
+
+[TYPECHECK]
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# List of classes names for which member attributes should not be checked
+# (useful for classes with attributes dynamically set).
+ignored-classes=SQLObject
+
+# When zope mode is activated, add a predefined set of Zope acquired attributes
+# to generated-members.
+zope=no
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E0201 when accessed. Python regular
+# expressions are accepted.
+generated-members=REQUEST,acl_users,aq_parent
+
+
+[VARIABLES]
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# A regular expression matching the beginning of the name of dummy variables
+# (i.e. not used).
+dummy-variables-rgx=_$|dummy
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+
+[FORMAT]
+
+# Maximum number of characters on a single line.
+max-line-length=80
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )?<?https?://\S+>?$
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+# List of optional constructs for which whitespace checking is disabled
+no-space-check=trailing-comma,dict-separator
+
+# Maximum number of lines in a module
+max-module-lines=1000
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string='    '
+
+
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+
+[IMPORTS]
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,TERMIOS,Bastion,rexec
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled)
+int-import-graph=
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=5
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore
+ignored-argument-names=_.*
+
+# Maximum number of locals for function / method body
+max-locals=15
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of branch for function / method body
+max-branches=12
+
+# Maximum number of statements in function / method body
+max-statements=50
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+
+[CLASSES]
+
+# List of interface methods to ignore, separated by a comma. This is used for
+# instance to not check methods defines in Zope's Interface base class.
+ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,__new__,setUp
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=mcs
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "Exception"
+overgeneral-exceptions=Exception

+ 128 - 0
resources.py

@@ -0,0 +1,128 @@
+# -*- coding: utf-8 -*-
+
+# Resource object code
+#
+# Created by: The Resource Compiler for PyQt5 (Qt v5.11.2)
+#
+# WARNING! All changes made in this file will be lost!
+
+from PyQt5 import QtCore
+
+qt_resource_data = b"\
+\x00\x00\x04\x0a\
+\x89\
+\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
+\x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\
+\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
+\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\
+\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\
+\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd9\x02\x15\
+\x16\x11\x2c\x9d\x48\x83\xbb\x00\x00\x03\x8a\x49\x44\x41\x54\x48\
+\xc7\xad\x95\x4b\x68\x5c\x55\x18\xc7\x7f\xe7\xdc\x7b\x67\xe6\xce\
+\x4c\x66\x26\x49\xd3\x24\x26\xa6\xc6\xf8\x40\x21\xa5\x04\xb3\x28\
+\xda\x98\x20\xa5\x0b\xad\x55\xa8\x2b\xc5\x50\x1f\xa0\x6e\x34\x2b\
+\x45\x30\x14\x02\xba\x52\x69\x15\x17\x66\x63\x45\x97\x95\xa0\xad\
+\x0b\xfb\xc0\x06\x25\xb6\x71\x61\x12\x41\x50\xdb\x2a\x21\xd1\xe2\
+\x24\xf3\x9e\xc9\xcc\xbd\xe7\x1c\x17\x35\x43\x1e\x33\x21\xb6\xfd\
+\x56\x87\xf3\x9d\xfb\xfb\x1e\xf7\xff\x9d\x23\x8c\x31\x43\x95\xf4\
+\x85\x1e\x3f\x3b\x35\xac\xfd\xcc\x43\xdc\xa4\x49\x3b\xfe\x9d\x1d\
+\xdb\x7b\x22\x90\x78\xf8\xb2\x28\xa7\xbe\x7d\xc1\x4b\x9d\x79\xdf\
+\x18\x15\xe5\x16\x99\x10\x56\xde\x69\xdc\x3f\x22\xfd\xec\xd4\xf0\
+\xad\x04\x03\x18\xa3\xa2\x7e\x76\x6a\x58\xde\x68\x2b\xb4\x36\xf8\
+\xbe\xc6\x18\x53\xdb\xef\xe7\xfa\xec\xed\x67\x63\x10\x42\x00\xf0\
+\xfb\xd5\x65\x2a\x15\x45\xc7\x6d\x0d\x00\xc4\xa2\xc1\xaa\x6f\x0d\
+\x3e\x6c\xab\xc2\x1c\x56\xa4\x77\x4b\xb0\xf2\x35\x15\x5f\x21\x85\
+\xe0\xc8\x6b\x5f\x92\x2d\x37\x33\x39\xf9\x03\x27\x8e\x1f\xa2\xf7\
+\xbe\x9d\x04\x1c\x0b\x37\xe4\xac\xff\xa6\x30\x87\xbd\xba\x00\x6a\
+\x06\x79\xe5\xf5\xaf\x89\xd9\x92\xc5\xcc\x0a\xd9\x7c\x19\xcf\xe9\
+\xe2\xe4\xa9\x2f\x78\x7c\xff\x01\x72\x85\x0a\x2b\x65\x1f\xa5\x4c\
+\xb5\xb2\x55\x16\x80\xbd\x31\xda\xda\x20\x1f\x7d\x3e\xcd\xc2\xfd\
+\x59\xa6\x93\x39\x92\xd1\x22\xea\x9b\x16\xce\x9d\x3f\xce\xe0\x83\
+\x03\x24\x82\x59\x3a\xdb\x7b\x88\xc7\x82\x68\x63\x58\xc9\xcc\x62\
+\x8c\x21\x18\xb0\x6a\xc3\x37\x06\x49\x16\xff\x24\x6b\xa5\x49\xbb\
+\x25\xbc\xa2\xa6\x21\xbb\x40\x7f\xdf\x00\x83\xbd\x01\x8e\x3c\xd5\
+\x45\xd7\x8e\x6b\x9c\x9c\x98\x25\x1a\xb6\xe8\xbe\x3d\xc2\xdd\x77\
+\x44\x48\xc4\x1c\x22\xe1\xeb\x58\x59\xaf\xcf\xd3\x33\x29\x2e\x34\
+\x2d\x91\x93\x3e\xbe\x34\x78\x01\xc5\xe2\x61\xc5\xae\x72\x8e\x70\
+\xc8\xc2\x0d\x5a\xbc\xf5\xee\x2f\x9c\xfa\x3e\x86\x69\x7a\x8e\xcf\
+\x26\xe6\xf9\x63\xa1\x44\xa1\xa4\xd0\xda\x6c\x0d\x2f\x15\x7c\xb4\
+\x67\x28\x59\x0a\xcf\xd6\x54\xe2\x06\x13\x87\x2b\x6f\x68\xa6\x27\
+\xaf\x31\x32\x36\xc7\xb2\x7f\x17\xef\x7d\x7c\x8c\x33\x67\xcf\x12\
+\x70\x24\x4a\x69\xd6\x6a\x46\xd6\xd3\x70\x72\xa9\x82\x67\x34\x45\
+\xad\x28\xdb\x1a\x15\x34\x98\xff\x46\xed\xef\x37\x0d\x99\xbf\x4a\
+\x3c\x30\x38\xc0\xc8\x4b\xaf\x92\x5a\x9c\xe2\xe0\x23\x6d\x74\xb4\
+\xba\x84\x5d\x0b\x29\x45\x7d\xb8\x94\x82\x96\xb6\x10\xf3\xc5\x12\
+\x2a\xef\x53\x11\x1a\x63\xad\x3f\x93\x19\x85\xf1\xb1\x77\x58\x5a\
+\xf8\x99\x97\x9f\xe9\xa6\x75\x47\x90\xc6\xb8\x43\xd8\xb5\xb6\xce\
+\xfc\xfa\xfd\x00\xfb\x3e\xf4\xc8\x05\x35\xba\x5e\xeb\x46\x21\xf9\
+\xcf\x0a\xa9\x8c\x87\xe3\x48\xdc\x90\xb5\x6e\x98\x6a\xaa\x65\xf2\
+\x52\x92\x43\x2f\x5e\xc2\x8c\x02\x1a\x10\xf5\x07\xac\xc3\x75\x70\
+\x83\x92\x80\xb3\xf9\xd0\x26\xf8\x8f\xb3\x29\xc6\x3e\xb8\x8c\x19\
+\x35\x75\x6b\x7b\x7e\x3c\xca\x45\x0c\x7e\x49\x31\xf4\x58\x3b\xf7\
+\xf6\x34\x90\x88\x39\x04\x1c\x59\x1f\xfe\xdb\xd5\x3c\x5f\x9d\x4b\
+\x32\xfd\x44\xb2\xba\xd7\xfa\xb6\x60\xcf\xde\x16\xdc\x90\x45\x4c\
+\x4a\x2a\x9e\x62\xfe\x4e\xc5\xc8\xc1\x4e\xda\x76\x86\xe8\xe9\x0a\
+\xe3\xd8\x92\x58\xd4\xc6\xb2\x44\x6d\x78\x2a\x53\xe1\xca\x7c\x99\
+\x63\x5d\xbf\x56\x9d\xbd\x9f\x44\x18\x7a\xba\x95\x27\x0f\xb4\xd3\
+\xdc\x18\xc0\xf3\x0d\x52\x40\xd8\xb5\xb0\xa4\x20\x14\xb2\x70\x6c\
+\x81\x63\xcb\xaa\x42\xd6\xfd\xb7\xf4\xec\xa3\x06\xa0\x50\x52\xd8\
+\x4e\x1b\x7e\x4a\xd3\x31\xf9\x29\xcf\xfe\xd4\x49\x7f\x5f\x13\xfb\
+\xfa\x9b\x71\x43\x92\x58\xd4\x21\x18\x90\xac\xde\xb0\x42\x50\x13\
+\x58\x33\xf3\x88\x6b\xa1\xfd\x65\x96\xf2\x79\xc6\x43\x7b\xd8\x75\
+\x38\xcc\x3d\xdd\xd1\xaa\xcf\x71\xe4\xff\x7f\x91\x56\x33\xaf\xea\
+\x37\xe7\xa1\x94\x21\x16\xb5\xd1\x06\x2c\x29\x36\xf5\x72\x9b\x96\
+\x95\xc0\xc4\xda\x9d\x78\x83\x43\x53\x22\x80\x65\x09\x1c\xfb\x86\
+\xc1\x00\xe7\x25\x70\x14\x48\x6f\x1e\x22\x51\xe3\x75\xd9\xb6\xa5\
+\x81\xa3\x32\xb1\xfb\xf4\x0c\x30\xb8\xb1\x82\x9b\xb0\x09\x60\x30\
+\xb1\xfb\xf4\xcc\xbf\xa0\xe9\x6e\xae\x5a\xdf\x4b\x81\x00\x00\x00\
+\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
+"
+
+qt_resource_name = b"\
+\x00\x07\
+\x07\x3b\xe0\xb3\
+\x00\x70\
+\x00\x6c\x00\x75\x00\x67\x00\x69\x00\x6e\x00\x73\
+\x00\x05\
+\x00\x48\xb2\x83\
+\x00\x41\
+\x00\x74\x00\x6c\x00\x61\x00\x73\
+\x00\x08\
+\x0a\x61\x5a\xa7\
+\x00\x69\
+\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\
+"
+
+qt_resource_struct_v1 = b"\
+\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
+\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
+\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
+\x00\x00\x00\x24\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
+"
+
+qt_resource_struct_v2 = b"\
+\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
+\x00\x00\x00\x00\x00\x00\x00\x00\
+\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
+\x00\x00\x00\x00\x00\x00\x00\x00\
+\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
+\x00\x00\x00\x00\x00\x00\x00\x00\
+\x00\x00\x00\x24\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
+\x00\x00\x01\x68\xb7\xf6\x72\x4d\
+"
+
+qt_version = [int(v) for v in QtCore.qVersion().split('.')]
+if qt_version < [5, 8, 0]:
+    rcc_version = 1
+    qt_resource_struct = qt_resource_struct_v1
+else:
+    rcc_version = 2
+    qt_resource_struct = qt_resource_struct_v2
+
+def qInitResources():
+    QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
+
+def qCleanupResources():
+    QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
+
+qInitResources()

+ 5 - 0
resources.qrc

@@ -0,0 +1,5 @@
+<RCC>
+    <qresource prefix="/plugins/Atlas" >
+        <file>icon.png</file>
+    </qresource>
+</RCC>

+ 12 - 0
scripts/compile-strings.sh

@@ -0,0 +1,12 @@
+#!/bin/bash
+LRELEASE=$1
+LOCALES=$2
+
+
+for LOCALE in ${LOCALES}
+do
+    echo "Processing: ${LOCALE}.ts"
+    # Note we don't use pylupdate with qt .pro file approach as it is flakey
+    # about what is made available.
+    $LRELEASE i18n/${LOCALE}.ts
+done

+ 28 - 0
scripts/run-env-linux.sh

@@ -0,0 +1,28 @@
+#!/bin/bash
+
+QGIS_PREFIX_PATH=/usr/local/qgis-2.0
+if [ -n "$1" ]; then
+    QGIS_PREFIX_PATH=$1
+fi
+
+echo ${QGIS_PREFIX_PATH}
+
+
+export QGIS_PREFIX_PATH=${QGIS_PREFIX_PATH}
+export QGIS_PATH=${QGIS_PREFIX_PATH}
+export LD_LIBRARY_PATH=${QGIS_PREFIX_PATH}/lib
+export PYTHONPATH=${QGIS_PREFIX_PATH}/share/qgis/python:${QGIS_PREFIX_PATH}/share/qgis/python/plugins:${PYTHONPATH}
+
+echo "QGIS PATH: $QGIS_PREFIX_PATH"
+export QGIS_DEBUG=0
+export QGIS_LOG_FILE=/tmp/inasafe/realtime/logs/qgis.log
+
+export PATH=${QGIS_PREFIX_PATH}/bin:$PATH
+
+echo "This script is intended to be sourced to set up your shell to"
+echo "use a QGIS 2.0 built in $QGIS_PREFIX_PATH"
+echo
+echo "To use it do:"
+echo "source $BASH_SOURCE /your/optional/install/path"
+echo
+echo "Then use the make file supplied here e.g. make guitest"

+ 56 - 0
scripts/update-strings.sh

@@ -0,0 +1,56 @@
+#!/bin/bash
+LOCALES=$*
+
+# Get newest .py files so we don't update strings unnecessarily
+
+CHANGED_FILES=0
+PYTHON_FILES=`find . -regex ".*\(ui\|py\)$" -type f`
+for PYTHON_FILE in $PYTHON_FILES
+do
+  CHANGED=$(stat -c %Y $PYTHON_FILE)
+  if [ ${CHANGED} -gt ${CHANGED_FILES} ]
+  then
+    CHANGED_FILES=${CHANGED}
+  fi
+done
+
+# Qt translation stuff
+# for .ts file
+UPDATE=false
+for LOCALE in ${LOCALES}
+do
+  TRANSLATION_FILE="i18n/$LOCALE.ts"
+  if [ ! -f ${TRANSLATION_FILE} ]
+  then
+    # Force translation string collection as we have a new language file
+    touch ${TRANSLATION_FILE}
+    UPDATE=true
+    break
+  fi
+
+  MODIFICATION_TIME=$(stat -c %Y ${TRANSLATION_FILE})
+  if [ ${CHANGED_FILES} -gt ${MODIFICATION_TIME} ]
+  then
+    # Force translation string collection as a .py file has been updated
+    UPDATE=true
+    break
+  fi
+done
+
+if [ ${UPDATE} == true ]
+# retrieve all python files
+then
+  echo ${PYTHON_FILES}
+  # update .ts
+  echo "Please provide translations by editing the translation files below:"
+  for LOCALE in ${LOCALES}
+  do
+    echo "i18n/"${LOCALE}".ts"
+    # Note we don't use pylupdate with qt .pro file approach as it is flakey
+    # about what is made available.
+    pylupdate4 -noobsolete ${PYTHON_FILES} -ts i18n/${LOCALE}.ts
+  done
+else
+  echo "No need to edit any translation files (.ts) because no python files"
+  echo "has been updated since the last update translation. "
+fi

+ 2 - 0
test/__init__.py

@@ -0,0 +1,2 @@
+# import qgis libs so that ve set the correct sip api version
+import qgis   # pylint: disable=W0611  # NOQA

+ 205 - 0
test/qgis_interface.py

@@ -0,0 +1,205 @@
+# coding=utf-8
+"""QGIS plugin implementation.
+
+.. note:: This program is free software; you can redistribute it and/or modify
+     it under the terms of the GNU General Public License as published by
+     the Free Software Foundation; either version 2 of the License, or
+     (at your option) any later version.
+
+.. note:: This source code was copied from the 'postgis viewer' application
+     with original authors:
+     Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk
+     Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org
+     Copyright (c) 2014 Tim Sutton, tim@linfiniti.com
+
+"""
+
+__author__ = 'tim@linfiniti.com'
+__revision__ = '$Format:%H$'
+__date__ = '10/01/2011'
+__copyright__ = (
+    'Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk and '
+    'Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org'
+    'Copyright (c) 2014 Tim Sutton, tim@linfiniti.com'
+)
+
+import logging
+from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
+from qgis.core import QgsMapLayerRegistry
+from qgis.gui import QgsMapCanvasLayer
+LOGGER = logging.getLogger('QGIS')
+
+
+#noinspection PyMethodMayBeStatic,PyPep8Naming
+class QgisInterface(QObject):
+    """Class to expose QGIS objects and functions to plugins.
+
+    This class is here for enabling us to run unit tests only,
+    so most methods are simply stubs.
+    """
+    currentLayerChanged = pyqtSignal(QgsMapCanvasLayer)
+
+    def __init__(self, canvas):
+        """Constructor
+        :param canvas:
+        """
+        QObject.__init__(self)
+        self.canvas = canvas
+        # Set up slots so we can mimic the behaviour of QGIS when layers
+        # are added.
+        LOGGER.debug('Initialising canvas...')
+        # noinspection PyArgumentList
+        QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
+        # noinspection PyArgumentList
+        QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer)
+        # noinspection PyArgumentList
+        QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers)
+
+        # For processing module
+        self.destCrs = None
+
+    @pyqtSlot('QStringList')
+    def addLayers(self, layers):
+        """Handle layers being added to the registry so they show up in canvas.
+
+        :param layers: list<QgsMapLayer> list of map layers that were added
+
+        .. note:: The QgsInterface api does not include this method,
+            it is added here as a helper to facilitate testing.
+        """
+        #LOGGER.debug('addLayers called on qgis_interface')
+        #LOGGER.debug('Number of layers being added: %s' % len(layers))
+        #LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers()))
+        current_layers = self.canvas.layers()
+        final_layers = []
+        for layer in current_layers:
+            final_layers.append(QgsMapCanvasLayer(layer))
+        for layer in layers:
+            final_layers.append(QgsMapCanvasLayer(layer))
+
+        self.canvas.setLayerSet(final_layers)
+        #LOGGER.debug('Layer Count After: %s' % len(self.canvas.layers()))
+
+    @pyqtSlot('QgsMapLayer')
+    def addLayer(self, layer):
+        """Handle a layer being added to the registry so it shows up in canvas.
+
+        :param layer: list<QgsMapLayer> list of map layers that were added
+
+        .. note: The QgsInterface api does not include this method, it is added
+                 here as a helper to facilitate testing.
+
+        .. note: The addLayer method was deprecated in QGIS 1.8 so you should
+                 not need this method much.
+        """
+        pass
+
+    @pyqtSlot()
+    def removeAllLayers(self):
+        """Remove layers from the canvas before they get deleted."""
+        self.canvas.setLayerSet([])
+
+    def newProject(self):
+        """Create new project."""
+        # noinspection PyArgumentList
+        QgsMapLayerRegistry.instance().removeAllMapLayers()
+
+    # ---------------- API Mock for QgsInterface follows -------------------
+
+    def zoomFull(self):
+        """Zoom to the map full extent."""
+        pass
+
+    def zoomToPrevious(self):
+        """Zoom to previous view extent."""
+        pass
+
+    def zoomToNext(self):
+        """Zoom to next view extent."""
+        pass
+
+    def zoomToActiveLayer(self):
+        """Zoom to extent of active layer."""
+        pass
+
+    def addVectorLayer(self, path, base_name, provider_key):
+        """Add a vector layer.
+
+        :param path: Path to layer.
+        :type path: str
+
+        :param base_name: Base name for layer.
+        :type base_name: str
+
+        :param provider_key: Provider key e.g. 'ogr'
+        :type provider_key: str
+        """
+        pass
+
+    def addRasterLayer(self, path, base_name):
+        """Add a raster layer given a raster layer file name
+
+        :param path: Path to layer.
+        :type path: str
+
+        :param base_name: Base name for layer.
+        :type base_name: str
+        """
+        pass
+
+    def activeLayer(self):
+        """Get pointer to the active layer (layer selected in the legend)."""
+        # noinspection PyArgumentList
+        layers = QgsMapLayerRegistry.instance().mapLayers()
+        for item in layers:
+            return layers[item]
+
+    def addToolBarIcon(self, action):
+        """Add an icon to the plugins toolbar.
+
+        :param action: Action to add to the toolbar.
+        :type action: QAction
+        """
+        pass
+
+    def removeToolBarIcon(self, action):
+        """Remove an action (icon) from the plugin toolbar.
+
+        :param action: Action to add to the toolbar.
+        :type action: QAction
+        """
+        pass
+
+    def addToolBar(self, name):
+        """Add toolbar with specified name.
+
+        :param name: Name for the toolbar.
+        :type name: str
+        """
+        pass
+
+    def mapCanvas(self):
+        """Return a pointer to the map canvas."""
+        return self.canvas
+
+    def mainWindow(self):
+        """Return a pointer to the main window.
+
+        In case of QGIS it returns an instance of QgisApp.
+        """
+        pass
+
+    def addDockWidget(self, area, dock_widget):
+        """Add a dock widget to the main window.
+
+        :param area: Where in the ui the dock should be placed.
+        :type area:
+
+        :param dock_widget: A dock widget to add to the UI.
+        :type dock_widget: QDockWidget
+        """
+        pass
+
+    def legendInterface(self):
+        """Get the legend."""
+        return self.canvas

+ 19 - 0
test/tenbytenraster.asc

@@ -0,0 +1,19 @@
+NCOLS 10
+NROWS 10
+XLLCENTER 1535380.000000
+YLLCENTER 5083260.000000
+DX 10
+DY 10
+NODATA_VALUE -9999
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+0 1 2 3 4 5 6 7 8 9
+CRS
+NOTES

+ 13 - 0
test/tenbytenraster.asc.aux.xml

@@ -0,0 +1,13 @@
+<PAMDataset>
+  <Metadata>
+    <MDI key="AREA_OR_POINT">Point</MDI>
+  </Metadata>
+  <PAMRasterBand band="1">
+    <Metadata>
+      <MDI key="STATISTICS_MAXIMUM">9</MDI>
+      <MDI key="STATISTICS_MEAN">4.5</MDI>
+      <MDI key="STATISTICS_MINIMUM">0</MDI>
+      <MDI key="STATISTICS_STDDEV">2.872281323269</MDI>
+    </Metadata>
+  </PAMRasterBand>
+</PAMDataset>

+ 1 - 0
test/tenbytenraster.keywords

@@ -0,0 +1 @@
+title: Tenbytenraster

+ 18 - 0
test/tenbytenraster.lic

@@ -0,0 +1,18 @@
+<?xml version='1.0' encoding='iso-8859-1'?>
+<ga_license_file>
+  <metadata>
+    <author>Tim Sutton, Linfiniti Consulting CC</author>
+  </metadata>
+
+  <datafile>
+    <filename>tenbytenraster.asc</filename>
+    <checksum>2700044251</checksum>
+    <publishable>Yes</publishable>
+    <accountable>Tim Sutton</accountable>
+    <source>Tim Sutton (QGIS Source Tree)</source>
+    <IP_owner>Tim Sutton</IP_owner>
+    <IP_info>This data is publicly available from QGIS Source Tree. The original
+    file was created and contributed to QGIS by Tim Sutton.</IP_info>
+  </datafile>
+
+</ga_license_file>

+ 1 - 0
test/tenbytenraster.prj

@@ -0,0 +1 @@
+GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]

+ 26 - 0
test/tenbytenraster.qml

@@ -0,0 +1,26 @@
+<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
+<qgis version="1.9.0-Master" minimumScale="-4.65661e-10" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0">
+  <pipe>
+    <rasterrenderer opacity="1" alphaBand="0" classificationMax="9" classificationMinMaxOrigin="MinMaxFullExtentExact" band="1" classificationMin="0" type="singlebandpseudocolor">
+      <rasterTransparency/>
+      <rastershader>
+        <colorrampshader colorRampType="INTERPOLATED" clip="0">
+          <item alpha="255" value="0" label="0.000000" color="#d7191c"/>
+          <item alpha="255" value="1" label="1.000000" color="#e75b3a"/>
+          <item alpha="255" value="2" label="2.000000" color="#f89d59"/>
+          <item alpha="255" value="3" label="3.000000" color="#fdc980"/>
+          <item alpha="255" value="4" label="4.000000" color="#feedaa"/>
+          <item alpha="255" value="5" label="5.000000" color="#ecf7b9"/>
+          <item alpha="255" value="6" label="6.000000" color="#c7e8ad"/>
+          <item alpha="255" value="7" label="7.000000" color="#9cd3a6"/>
+          <item alpha="255" value="8" label="8.000000" color="#63abb0"/>
+          <item alpha="255" value="9" label="9.000000" color="#2b83ba"/>
+        </colorrampshader>
+      </rastershader>
+    </rasterrenderer>
+    <brightnesscontrast brightness="0" contrast="0"/>
+    <huesaturation colorizeGreen="128" colorizeOn="0" colorizeRed="255" colorizeBlue="128" grayscaleMode="0" saturation="0" colorizeStrength="100"/>
+    <rasterresampler maxOversampling="2"/>
+  </pipe>
+  <blendMode>0</blendMode>
+</qgis>

+ 45 - 0
test/test_Atlas_dockwidget.py

@@ -0,0 +1,45 @@
+# coding=utf-8
+"""DockWidget test.
+
+.. note:: This program is free software; you can redistribute it and/or modify
+     it under the terms of the GNU General Public License as published by
+     the Free Software Foundation; either version 2 of the License, or
+     (at your option) any later version.
+
+"""
+
+__author__ = 'vrobel.jan@seznam.cz'
+__date__ = '2019-02-15'
+__copyright__ = 'Copyright 2019, jan vrobel'
+
+import unittest
+
+from PyQt5.QtGui import QDockWidget
+
+from Atlas_dockwidget import AtlasDockWidget
+
+from utilities import get_qgis_app
+
+QGIS_APP = get_qgis_app()
+
+
+class AtlasDockWidgetTest(unittest.TestCase):
+    """Test dockwidget works."""
+
+    def setUp(self):
+        """Runs before each test."""
+        self.dockwidget = AtlasDockWidget(None)
+
+    def tearDown(self):
+        """Runs after each test."""
+        self.dockwidget = None
+
+    def test_dockwidget_ok(self):
+        """Test we can click OK."""
+        pass
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(AtlasDialogTest)
+    runner = unittest.TextTestRunner(verbosity=2)
+    runner.run(suite)
+

+ 64 - 0
test/test_init.py

@@ -0,0 +1,64 @@
+# coding=utf-8
+"""Tests QGIS plugin init."""
+
+__author__ = 'Tim Sutton <tim@linfiniti.com>'
+__revision__ = '$Format:%H$'
+__date__ = '17/10/2010'
+__license__ = "GPL"
+__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
+__copyright__ += 'Disaster Reduction'
+
+import os
+import unittest
+import logging
+import configparser
+
+LOGGER = logging.getLogger('QGIS')
+
+
+class TestInit(unittest.TestCase):
+    """Test that the plugin init is usable for QGIS.
+
+    Based heavily on the validator class by Alessandro
+    Passoti available here:
+
+    http://github.com/qgis/qgis-django/blob/master/qgis-app/
+             plugins/validator.py
+
+    """
+
+    def test_read_init(self):
+        """Test that the plugin __init__ will validate on plugins.qgis.org."""
+
+        # You should update this list according to the latest in
+        # https://github.com/qgis/qgis-django/blob/master/qgis-app/
+        #        plugins/validator.py
+
+        required_metadata = [
+            'name',
+            'description',
+            'version',
+            'qgisMinimumVersion',
+            'email',
+            'author']
+
+        file_path = os.path.abspath(os.path.join(
+            os.path.dirname(__file__), os.pardir,
+            'metadata.txt'))
+        LOGGER.info(file_path)
+        metadata = []
+        parser = configparser.ConfigParser()
+        parser.optionxform = str
+        parser.read(file_path)
+        message = 'Cannot find a section named "general" in %s' % file_path
+        assert parser.has_section('general'), message
+        metadata.extend(parser.items('general'))
+
+        for expectation in required_metadata:
+            message = ('Cannot find metadata "%s" in metadata source (%s).' % (
+                expectation, file_path))
+
+            self.assertIn(expectation, dict(metadata), message)
+
+if __name__ == '__main__':
+    unittest.main()

+ 60 - 0
test/test_qgis_environment.py

@@ -0,0 +1,60 @@
+# coding=utf-8
+"""Tests for QGIS functionality.
+
+
+.. note:: This program is free software; you can redistribute it and/or modify
+     it under the terms of the GNU General Public License as published by
+     the Free Software Foundation; either version 2 of the License, or
+     (at your option) any later version.
+
+"""
+__author__ = 'tim@linfiniti.com'
+__date__ = '20/01/2011'
+__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
+                 'Disaster Reduction')
+
+import os
+import unittest
+from qgis.core import (
+    QgsProviderRegistry,
+    QgsCoordinateReferenceSystem,
+    QgsRasterLayer)
+
+from .utilities import get_qgis_app
+QGIS_APP = get_qgis_app()
+
+
+class QGISTest(unittest.TestCase):
+    """Test the QGIS Environment"""
+
+    def test_qgis_environment(self):
+        """QGIS environment has the expected providers"""
+
+        r = QgsProviderRegistry.instance()
+        self.assertIn('gdal', r.providerList())
+        self.assertIn('ogr', r.providerList())
+        self.assertIn('postgres', r.providerList())
+
+    def test_projection(self):
+        """Test that QGIS properly parses a wkt string.
+        """
+        crs = QgsCoordinateReferenceSystem()
+        wkt = (
+            'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",'
+            'SPHEROID["WGS_1984",6378137.0,298.257223563]],'
+            'PRIMEM["Greenwich",0.0],UNIT["Degree",'
+            '0.0174532925199433]]')
+        crs.createFromWkt(wkt)
+        auth_id = crs.authid()
+        expected_auth_id = 'EPSG:4326'
+        self.assertEqual(auth_id, expected_auth_id)
+
+        # now test for a loaded layer
+        path = os.path.join(os.path.dirname(__file__), 'tenbytenraster.asc')
+        title = 'TestRaster'
+        layer = QgsRasterLayer(path, title)
+        auth_id = layer.crs().authid()
+        self.assertEqual(auth_id, expected_auth_id)
+
+if __name__ == '__main__':
+    unittest.main()

+ 44 - 0
test/test_resources.py

@@ -0,0 +1,44 @@
+# coding=utf-8
+"""Resources test.
+
+.. note:: This program is free software; you can redistribute it and/or modify
+     it under the terms of the GNU General Public License as published by
+     the Free Software Foundation; either version 2 of the License, or
+     (at your option) any later version.
+
+"""
+
+__author__ = 'vrobel.jan@seznam.cz'
+__date__ = '2019-02-15'
+__copyright__ = 'Copyright 2019, jan vrobel'
+
+import unittest
+
+from PyQt5.QtGui import QIcon
+
+
+
+class AtlasDialogTest(unittest.TestCase):
+    """Test rerources work."""
+
+    def setUp(self):
+        """Runs before each test."""
+        pass
+
+    def tearDown(self):
+        """Runs after each test."""
+        pass
+
+    def test_icon_png(self):
+        """Test we can click OK."""
+        path = ':/plugins/Atlas/icon.png'
+        icon = QIcon(path)
+        self.assertFalse(icon.isNull())
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(AtlasResourcesTest)
+    runner = unittest.TextTestRunner(verbosity=2)
+    runner.run(suite)
+
+
+

+ 55 - 0
test/test_translations.py

@@ -0,0 +1,55 @@
+# coding=utf-8
+"""Safe Translations Test.
+
+.. note:: This program is free software; you can redistribute it and/or modify
+     it under the terms of the GNU General Public License as published by
+     the Free Software Foundation; either version 2 of the License, or
+     (at your option) any later version.
+
+"""
+from .utilities import get_qgis_app
+
+__author__ = 'ismailsunni@yahoo.co.id'
+__date__ = '12/10/2011'
+__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
+                 'Disaster Reduction')
+import unittest
+import os
+
+from PyQt5.QtCore import QCoreApplication, QTranslator
+
+QGIS_APP = get_qgis_app()
+
+
+class SafeTranslationsTest(unittest.TestCase):
+    """Test translations work."""
+
+    def setUp(self):
+        """Runs before each test."""
+        if 'LANG' in iter(os.environ.keys()):
+            os.environ.__delitem__('LANG')
+
+    def tearDown(self):
+        """Runs after each test."""
+        if 'LANG' in iter(os.environ.keys()):
+            os.environ.__delitem__('LANG')
+
+    def test_qgis_translations(self):
+        """Test that translations work."""
+        parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir)
+        dir_path = os.path.abspath(parent_path)
+        file_path = os.path.join(
+            dir_path, 'i18n', 'af.qm')
+        translator = QTranslator()
+        translator.load(file_path)
+        QCoreApplication.installTranslator(translator)
+
+        expected_message = 'Goeie more'
+        real_message = QCoreApplication.translate("@default", 'Good morning')
+        self.assertEqual(real_message, expected_message)
+
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(SafeTranslationsTest)
+    runner = unittest.TextTestRunner(verbosity=2)
+    runner.run(suite)

Some files were not shown because too many files changed in this diff