Пример #1
0
class geopunt4QgisAboutDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self, None)
        self.setWindowFlags( self.windowFlags() & ~Qt.WindowContextHelpButtonHint )
        self.setWindowFlags( self.windowFlags() | Qt.WindowStaysOnTopHint)

        # initialize locale
        locale = QSettings().value("locale/userLocale", "en")
        if not locale: locale == 'en' 
        else: locale = locale[0:2]
        localePath = os.path.join(os.path.dirname(__file__), 'i18n', 
                  'geopunt4qgis_{}.qm'.format(locale))
        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)
            QCoreApplication.installTranslator(self.translator)
            
        if 'en' in locale: 
            self.htmlFile = os.path.join(os.path.dirname(__file__), 'i18n', 'about-en.html')
        else:
            #dutch is default
            self.htmlFile = os.path.join(os.path.dirname(__file__), 'i18n', 'about-nl.html') 
        self._initGui()
    
    
    def _initGui(self):
      # Set up the user interface from Designer.
      self.ui = Ui_aboutDlg() 
      self.ui.setupUi(self)
      self.ui.buttonBox.addButton( QPushButton("Sluiten"), QDialogButtonBox.RejectRole  )
      with open(self.htmlFile,'r', encoding="utf-8") as html:
           self.ui.aboutText.setHtml( html.read() )
Пример #2
0
class Cadastre(object):

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = str(Path(__file__).resolve().parent)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n', 'cadastre_{}.qm'.format(locale))

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)


    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(
            QIcon(":/plugins/cadastre/icon.png"),
            u"Cadastre", self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(u"&Cadastre", self.action)

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(u"&Cadastre", self.action)
        self.iface.removeToolBarIcon(self.action)
Пример #3
0
class QScatterPlugin:
    def __init__(self, iface):
        self.iface = iface

        overrideLocale = QSettings().value('locale/overrideFlag', False, bool)
        if not overrideLocale:
            locale = QLocale.system().name()[:2]
        else:
            locale = QSettings().value('locale/userLocale', '')

        qmPath = '{}/i18n/qscatter_{}.qm'.format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        self.actionRun = QAction(
            self.tr('QScatter'), self.iface.mainWindow())
        self.actionRun.setIcon(
            QIcon(os.path.join(pluginPath, 'icons', 'qscatter.svg')))
        self.actionRun.setWhatsThis(
            self.tr('Interactive scatter plot'))
        self.actionRun.setObjectName('runQScatter')

        self.actionAbout = QAction(
            self.tr('About...'), self.iface.mainWindow())
        self.actionAbout.setIcon(
            QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.actionAbout.setWhatsThis(self.tr('About QScatter'))
        self.actionRun.setObjectName('aboutQScatter')

        self.iface.addPluginToVectorMenu(
            self.tr('QScatter'), self.actionRun)
        self.iface.addPluginToVectorMenu(
            self.tr('QScatter'), self.actionAbout)
        self.iface.addVectorToolBarIcon(self.actionRun)

        self.actionRun.triggered.connect(self.run)
        self.actionAbout.triggered.connect(self.about)

    def unload(self):
        self.iface.removePluginVectorMenu(
            self.tr('QScatter'), self.actionRun)
        self.iface.removePluginVectorMenu(
            self.tr('QScatter'), self.actionAbout)
        self.iface.removeVectorToolBarIcon(self.actionRun)

    def run(self):
        dlg = QScatterDialog(self.iface)
        dlg.show()
        dlg.exec_()

    def about(self):
        dlg = AboutDialog()
        dlg.exec_()

    def tr(self, text):
        return QCoreApplication.translate('QScatter', text)
Пример #4
0
def getTranslate(namePlugin, nameDir=None):
    if nameDir is None:
      nameDir = namePlugin

    pluginPath = os.path.join('python', 'plugins', nameDir)

    userPath = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
    userPluginPath = os.path.join(userPath, pluginPath)
    
    systemPath = QgsApplication.prefixPath()
    systemPluginPath = os.path.join(systemPath, pluginPath)

    overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
    localeFullName = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '')

    qmPathFile = os.path.join('i18n', '{0}_{1}.qm'.format(namePlugin, localeFullName))
    pp = userPluginPath if QFileInfo(userPluginPath).exists() else systemPluginPath
    translationFile = os.path.join(pp, qmPathFile)

    if QFileInfo(translationFile).exists():
        translator = QTranslator()
        translator.load(translationFile)
        QCoreApplication.installTranslator(translator)
        QgsApplication.messageLog().logMessage(('Installed translation file {}'.format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
        return translator
    else:
        QgsApplication.messageLog().logMessage(
            ("translationFile {} didn't exist, no translation file installed!".format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/qgiscloud/icon.png"), \
            "Cloud Settings", self.iface.mainWindow())
        self.action.triggered.connect(self.showHideDockWidget)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu("&Cloud", self.action)

        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale_short = QSettings().value("locale/userLocale", type=str)[0:2]
        locale_long = QSettings().value("locale/userLocale", type=str)
                
        if QFileInfo(self.plugin_dir).exists():            
            if QFileInfo(self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_short + ".qm").exists():
                self.translator = QTranslator()
                self.translator.load( self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_short + ".qm")            
                if qVersion() > '4.3.3':
                    QCoreApplication.installTranslator(self.translator)
            elif QFileInfo(self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_long + ".qm").exists():
                self.translator = QTranslator()
                self.translator.load( self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_long + ".qm")          
                if qVersion() > '4.3.3':
                    QCoreApplication.installTranslator(self.translator)                
                
#        # dock widget
        self.dockWidget = QgisCloudPluginDialog(self.iface, self.version)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget)                
Пример #6
0
class QConsolidatePlugin:
    def __init__(self, iface):
        self.iface = iface

        locale = QgsApplication.locale()
        qmPath = '{}/i18n/qconsolidate_{}.qm'.format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        self.actionRun = QAction(self.tr('QConsolidate'), self.iface.mainWindow())
        self.actionRun.setIcon(QIcon(os.path.join(pluginPath, 'icons', 'qconsolidate.svg')))
        self.actionRun.setObjectName('runQConsolidate')

        self.actionAbout = QAction(self.tr('About QConsolidate…'), self.iface.mainWindow())
        self.actionAbout.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.actionRun.setObjectName('aboutQConsolidate')

        self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionRun)
        self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionAbout)
        self.iface.addToolBarIcon(self.actionRun)

        self.actionRun.triggered.connect(self.run)
        self.actionAbout.triggered.connect(self.about)

        self.taskManager = QgsApplication.taskManager()

    def unload(self):
        self.iface.removePluginMenu(self.tr('QConsolidate'), self.actionRun)
        self.iface.removePluginMenu(self.tr('QConsolidate'), self.actionAbout)
        self.iface.removeToolBarIcon(self.actionRun)

    def run(self):
        dlg = QConsolidateDialog()
        if dlg.exec_():
            task = dlg.task()
            task.consolidateComplete.connect(self.completed)
            task.errorOccurred.connect(self.errored)

            self.taskManager.addTask(task)

    def about(self):
        d = AboutDialog()
        d.exec_()

    def tr(self, text):
        return QCoreApplication.translate('QConsolidate', text)

    def completed(self):
        self.iface.messageBar().pushSuccess(self.tr('QConsolidate'), self.tr('Project consolidated successfully.'))

    def errored(self, error):
        self.iface.messageBar().pushWarning(self.tr('QConsolidate'), error)
Пример #7
0
class SeptimaGeoSearch(object):

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/" + __package__

        # initialize locale. Default to Danish
        self.config = QSettings()
        localePath = ""
        try:
            locale = self.config.value("locale/userLocale")[0:2]
        except:
            locale = 'da'

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/" + locale + ".qt.qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QgsApplication.installTranslator(self.translator)
        
        # new config method
        self.settings = Settings()
        self.options_factory = OptionsFactory(self.settings)
        self.options_factory.setTitle('Geosearch DK')
        iface.registerOptionsWidgetFactory(self.options_factory)

    def initGui(self):
        # create the widget to display information
        self.searchwidget = SearchBox(self.iface)
        # create the dockwidget with the correct parent and add the valuewidget
        self.searchdockwidget = QDockWidget(
            "Geosearch DK", self.iface.mainWindow()
        )
        self.searchdockwidget.setObjectName("Geosearch DK")
        self.searchdockwidget.setWidget(self.searchwidget)
        # add the dockwidget to iface
        self.iface.addDockWidget(
            Qt.TopDockWidgetArea, self.searchdockwidget
        )
        # Make changed settings apply immediately
        self.settings.settings_updated.connect(self.searchwidget.readconfig)

    def unload(self):
        self.searchwidget.unload() # try to avoid processing events, when QGIS is closing
        self.iface.removeDockWidget(self.searchdockwidget)
        self.iface.unregisterOptionsWidgetFactory(self.options_factory)
    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)
Пример #9
0
    def test_qgis_translations(self):
        """Test for qgis translations."""
        file_path = safe_dir('i18n/inasafe_id.qm')
        translator = QTranslator()
        translator.load(file_path)
        QCoreApplication.installTranslator(translator)

        expected_message = (
            'Tidak ada informasi gaya yang ditemukan pada lapisan %s')
        real_message = QCoreApplication.translate(
            '@default', 'No styleInfo was found for layer %s')
        message = 'expected %s but got %s' % (expected_message, real_message)
        self.assertEqual(expected_message, real_message, message)
Пример #10
0
class QgisCloudPlugin(object):

    def __init__(self, iface, version):
        # Save reference to the QGIS interface
        self.iface = iface
        self.version = version
        

    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/qgiscloud/icon.png"), \
            "Cloud Settings", self.iface.mainWindow())
        self.action.triggered.connect(self.showHideDockWidget)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu("&Cloud", self.action)

        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale_short = QSettings().value("locale/userLocale", type=str)[0:2]
        locale_long = QSettings().value("locale/userLocale", type=str)
                
        if QFileInfo(self.plugin_dir).exists():            
            if QFileInfo(self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_short + ".qm").exists():
                self.translator = QTranslator()
                self.translator.load( self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_short + ".qm")            
                if qVersion() > '4.3.3':
                    QCoreApplication.installTranslator(self.translator)
            elif QFileInfo(self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_long + ".qm").exists():
                self.translator = QTranslator()
                self.translator.load( self.plugin_dir + "/i18n/qgiscloudplugin_" + locale_long + ".qm")          
                if qVersion() > '4.3.3':
                    QCoreApplication.installTranslator(self.translator)                
                
#        # dock widget
        self.dockWidget = QgisCloudPluginDialog(self.iface, self.version)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget)                

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu("&Cloud",self.action)
        self.iface.removeToolBarIcon(self.action)
        self.dockWidget.unload()
        self.iface.removeDockWidget(self.dockWidget)

    def showHideDockWidget(self):
        if self.dockWidget.isVisible():
            self.dockWidget.hide()
        else:
            self.dockWidget.show()
Пример #11
0
class NavTablePlugin(QObject):

    def __init__(self, iface):
        super().__init__()
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n', 'navtable_{}.qm'.format(locale))

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        # Create action that will start plugin configuration
        icon_path = os.path.join(self.plugin_dir, 'icon', 'icon.png')
        self.action = QAction(
            QIcon(icon_path),
            u"Navtable", self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(u"&Navtable", self.action)

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(u"&Navtable", self.action)
        self.iface.removeToolBarIcon(self.action)

    def run(self):

        self.layer = self.iface.activeLayer()

        # Comprobamos si existe alguna capa y si esta es vectorial
        if self.layer is None or not isinstance(self.layer, QgsVectorLayer):
            self.iface.messageBar().pushMessage("Invalid Layer",
                                                "NavTable only works on a vector layer",
                                                level=Qgis.Warning)
        else:
            self.dlg = NTMainPanel(self.iface, self.layer)
            self.dlg.show()

            self.dlg.exec_()
Пример #12
0
    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__)
        # initialize locale
        locale = QLocale(QSettings().value('locale/userLocale'))
        locale_path = os.path.join(self.plugin_dir, 'i18n')
        self.translator = QTranslator()
        self.translator.load(locale, 'QFieldSync', '_', locale_path)

        QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&QFieldSync')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QFieldSync')
        self.toolbar.setObjectName(u'QFieldSync')

        # instance of the QgsOfflineEditing
        self.offline_editing = QgsOfflineEditing()
        self.preferences = Preferences()

        QgsProject.instance().readProject.connect(self.update_button_enabled_status)

        # store warnings from last run
        self.last_action_warnings = []
Пример #13
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/" + __package__

        # initialize locale. Default to Danish
        self.config = QSettings()
        localePath = ""
        try:
            locale = self.config.value("locale/userLocale")[0:2]
        except:
            locale = 'da'

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/" + locale + ".qt.qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QgsApplication.installTranslator(self.translator)
        
        # new config method
        self.settings = Settings()
        self.options_factory = OptionsFactory(self.settings)
        self.options_factory.setTitle('Geosearch DK')
        iface.registerOptionsWidgetFactory(self.options_factory)
Пример #14
0
    def __init__(self, iface):
        if not valid:
            return

        # Save reference to the QGIS interface
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

        if QGis.QGIS_VERSION[0:3] < "1.5":
            # For i18n support
            userPluginPath = qgis.utils.home_plugin_path + "/GdalTools"
            systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools"

            overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool)
            if not overrideLocale:
                localeFullName = QLocale.system().name()
            else:
                localeFullName = QSettings().value("locale/userLocale", "", type=str)

            if QFileInfo(userPluginPath).exists():
                translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"
            else:
                translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"

            self.localePath = translationPath
            if QFileInfo(self.localePath).exists():
                self.translator = QTranslator()
                self.translator.load(self.localePath)
                QCoreApplication.installTranslator(self.translator)

        # The list of actions added to menus, so we can remove them when unloading the plugin
        self._menuActions = []
    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
        pluginPath = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            pluginPath,
            'i18n',
            #'ThinGreyscale_{}.qm'.format(locale))
            '{}.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)

        # Create the dialog (after translation) and keep reference
        self.dlg = ThinGreyscaleDialog(self.iface)

        # Declare instance attributes
        self.THINGRAYSCALE = self.tr(u'&Thin greyscale image to skeleton')
        self.THINGRAYSCALEAMP = self.tr('&ThinGreyscale')
        self.menu = self.THINGRAYSCALE
Пример #16
0
    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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'MapsPrinter_{}.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)

        # Create the dialog (after translation) and keep reference
        self.dlg = MapsPrinterDialog()

        self.arret = False
Пример #17
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.outdir = ''
        self.ilayers = QgsProject.instance()
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'KuwaharaFilter_{}.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'&Kuwahara Filter')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None
Пример #18
0
    def __init__(self, iface):
        'initialize'
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        
        # initialize locale
        locale = QSettings().value("locale/userLocale", "nl")
        if not locale: locale == 'nl' 
        else: locale = locale[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n', 'geopunt4qgis_{}.qm'.format(locale))
        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)
            QCoreApplication.installTranslator(self.translator)

        #version check
        if locale == 'nl':  
           vc = versionChecker()
           if not vc.isUptoDate():
              QMessageBox.warning(self.iface.mainWindow(), QCoreApplication.translate("geopunt4Qgis", "Waarschuwing"), QCoreApplication.translate("geopunt4Qgis", 
          "Je versie van <a href='http://plugins.qgis.org/plugins/geopunt4Qgis' >geopunt4qgis</a> is niet meer up to date. <br/>Je kunt deze upgraden via het menu:<br/> "+
          "<strong>Plugins > Beheer en installeer Plugins > Op te waarderen.</strong><br/>Klik daarna op <strong>Plugin opwaarderen</strong>"))

        # Create the dialogs (after translation) and keep reference
        self.adresdlg = geopunt4QgisAdresDialog(self.iface)
        self.batchgeoDlg = geopunt4QgisBatcGeoCodeDialog(self.iface) 
        self.poiDlg = geopunt4QgisPoidialog(self.iface)        
        self.gipodDlg = geopunt4QgisGipodDialog(self.iface)
        self.settingsDlg = geopunt4QgisSettingsDialog()
        if mathplotlibWorks : self.elevationDlg = geopunt4QgisElevationDialog(self.iface)
        self.datacatalogusDlg = geopunt4QgisDataCatalog(self.iface)
        self.parcelDlg = geopunt4QgisParcelDlg(self.iface)
        self.aboutDlg = geopunt4QgisAboutDialog()
class Translate():
  def __init__(self, pluginName):
    def getFile():
      overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
      localeFullName = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '')
      qmPathFile = "i18n/{0}_{1}.qm".format( pluginName, localeFullName )
      pluginPath = os.path.dirname(__file__)
      translationFile = "{}/{}".format( pluginPath, qmPathFile )
      return translationFile

    self.translator = None
    translationFile = getFile()
    if QFileInfo( translationFile ).exists():
        self.translator = QTranslator()
        self.translator.load( translationFile )
        QCoreApplication.installTranslator( self.translator )
    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 a reference to the QGIS interface
        self.iface = iface
        # initialize the plugin directory
        pluginPath = os.path.dirname(__file__)
        # initialize the locale using the QGIS locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            pluginPath,
            'i18n',
            '{}.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)

        # Create the dialog (after translation) and keep the reference
        self.dlg = linedirectionhistogramDialog(self.iface)

        # Declare instance attributes
        self.menuname = self.tr(u'&Line Direction Histogram')
Пример #21
0
    def __init__(self, iface):
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            os.path.dirname(__file__),
            'i18n',
            'qdraw_{}.qm'.format(locale))

        self.translator = None
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.iface = iface
        self.sb = self.iface.statusBarIface()
        self.tool = None
        self.toolname = None

        self.bGeom = None

        self.actions = []
        self.menu = '&Qdraw'
        self.toolbar = self.iface.addToolBar('Qdraw')
        self.toolbar.setObjectName('Qdraw')

        self.settings = QdrawSettings()
    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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GBIFOccurrences_{}.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)

        # Create the dialog (after translation) and keep reference
        self.dlg = GBIFOccurrencesDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&GBIF Occurrences')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'GBIFOccurrences')
        self.toolbar.setObjectName(u'GBIFOccurrences')
Пример #23
0
    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 a reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'NNJoin_{}.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.NNJOIN = self.tr('NNJoin')
        self.NNJOINAMP = self.tr('&NNJoin')
        self.toolbar = None
Пример #24
0
class StatistPlugin:
    def __init__(self, iface):
        self.iface = iface

        locale = QgsApplication.locale()
        qmPath = "{}/i18n/statist_{}.qm".format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        self.actionRun = QAction(self.tr("Statist"), self.iface.mainWindow())
        self.actionRun.setIcon(QIcon(os.path.join(pluginPath, "icons", "statist.png")))
        self.actionRun.setObjectName("runStatist")
        self.iface.registerMainWindowAction(self.actionRun, "Shift+S")

        self.actionAbout = QAction(self.tr("About Statist…"), self.iface.mainWindow())
        self.actionAbout.setIcon(QgsApplication.getThemeIcon("/mActionHelpContents.svg"))
        self.actionRun.setObjectName("aboutStatist")

        self.iface.addPluginToVectorMenu(self.tr("Statist"), self.actionRun)
        self.iface.addPluginToVectorMenu(self.tr("Statist"), self.actionAbout)
        self.iface.addVectorToolBarIcon(self.actionRun)

        self.actionRun.triggered.connect(self.run)
        self.actionAbout.triggered.connect(self.about)

    def unload(self):
        self.iface.unregisterMainWindowAction(self.actionRun)

        self.iface.removePluginVectorMenu(self.tr("Statist"), self.actionRun)
        self.iface.removePluginVectorMenu(self.tr("Statist"), self.actionAbout)
        self.iface.removeVectorToolBarIcon(self.actionRun)

    def run(self):
        dlg = StatistDialog()
        dlg.show()
        dlg.exec_()

    def about(self):
        d = AboutDialog()
        d.exec_()

    def tr(self, text):
        return QCoreApplication.translate("Statist", text)
Пример #25
0
    def __init__(self, iface):
        self.iface = iface

        locale = QgsApplication.locale()
        qmPath = "{}/i18n/statist_{}.qm".format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)
    def __init__(self, iface):
        self.iface = iface

        locale = QgsApplication.locale()
        qmPath = "{}/i18n/rastertransparency_{}.qm".format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)

        self.factory = TransparencyPanelFactory()
Пример #27
0
    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

        setup_logger('QuickOSM')

        # initialize plugin directory
        self.plugin_dir = dirname(__file__)
        # initialize locale
        # noinspection PyBroadException
        try:
            locale = QgsSettings().value('locale/userLocale', 'en')[0:2]
        except AttributeError:
            # Fallback to english #132
            LOGGER.warning('Fallback to English as default language for the plugin')
            locale = 'en'
        locale_path = join(
            self.plugin_dir,
            'i18n',
            'QuickOSM_{0}.qm'.format(locale))

        if exists(locale_path):
            LOGGER.info('Translation to {}'.format(locale))
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        self.provider = None

        # Add the toolbar
        self.toolbar = self.iface.addToolBar('QuickOSM')
        self.toolbar.setObjectName('QuickOSM')

        self.quickosm_menu = None
        self.vector_menu = None
        self.mainWindowAction = None
        self.osmFileAction = None
        self.osmFileDockWidget = None
        self.queryAction = None
        self.queryDockWidget = None
        self.quickQueryAction = None
        self.quickQueryDockWidget = None
        self.josmAction = None
Пример #28
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n', 'opeNoise_{}.qm'.format(locale))

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
class RasterTransparencyPlugin:

    def __init__(self, iface):
        self.iface = iface

        locale = QgsApplication.locale()
        qmPath = "{}/i18n/rastertransparency_{}.qm".format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)

        self.factory = TransparencyPanelFactory()

    def initGui(self):
        self.actionAbout = QAction(self.tr("About RasterTransparency…"), self.iface.mainWindow())
        self.actionAbout.setIcon(QgsApplication.getThemeIcon("/mActionHelpContents.svg"))
        self.actionAbout.setObjectName("aboutRasterTransparency")
        self.actionAbout.triggered.connect(self.about)

        self.iface.addPluginToRasterMenu(self.tr("Raster transparency"), self.actionAbout)

        self.iface.registerMapLayerConfigWidgetFactory(self.factory)

    def unload(self):
        self.iface.removePluginRasterMenu(self.tr("Raster transparency"), self.actionAbout)

        self.iface.unregisterMapLayerConfigWidgetFactory(self.factory)

    def about(self):
        d = AboutDialog()
        d.exec_()

    def tr(self, text):
        return QCoreApplication.translate("RasterTransparency", text)
Пример #30
0
    def __init__(self, iface):
        self.iface = iface

        overrideLocale = QSettings().value('locale/overrideFlag', False, bool)
        if not overrideLocale:
            locale = QLocale.system().name()[:2]
        else:
            locale = QSettings().value('locale/userLocale', '')

        qmPath = '{}/i18n/qscatter_{}.qm'.format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)
Пример #31
0
class Level2_Forecasting:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'Level2_Forecasting_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Level 2 Forecasting')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('Level2_Forecasting', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/level2_forecasting/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Level 2 Forecasting'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Level 2 Forecasting'),
                                        action)
            self.iface.removeToolBarIcon(action)

    #==================================================
    #==================================================
    #==================================================

    def get_output_directory(self):
        output_directory = str(
            QFileDialog.getExistingDirectory(None, "Select Directory"))
        self.dlg.lineEdit.setText(output_directory)

    def get_shape_file(self):
        shape_file_name, _filter = QFileDialog.getOpenFileName(
            self.dlg, "Select shape file", "", "*.shp")
        self.dlg.lineEdit_2.setText(shape_file_name)

    def get_pc_series(self):
        series_name, _filter = QFileDialog.getOpenFileName(
            self.dlg, "Select time series for pc", "", "*.tif")
        self.dlg.lineEdit_8.setText(series_name)

    def get_lst_series(self):
        series_name, _filter = QFileDialog.getOpenFileName(
            self.dlg, "Select time series for lst", "", "*.tif")
        self.dlg.lineEdit_9.setText(series_name)

    def get_evi_series(self):
        series_name, _filter = QFileDialog.getOpenFileName(
            self.dlg, "Select time series for evi", "", "*.tif")
        self.dlg.lineEdit_13.setText(series_name)

    def get_normalization_directory(self):
        directory, _filter = str(
            QFileDialog.getExistingDirectory(None, "Select Directory"))
        self.dlg.lineEdit_11.setText(directory)

    def interpolation_method_pc(self):
        if self.dlg.radioButton_9.isChecked():
            return 'CubicSpline'
        elif self.dlg.radioButton_10.isChecked():
            return 'polynomial'
        elif self.dlg.radioButton_11.isChecked():
            return 'linear'

    def interpolation_method_lst(self):
        if self.dlg.radioButton_12.isChecked():
            return 'CubicSpline'
        elif self.dlg.radioButton_13.isChecked():
            return 'polynomial'
        elif self.dlg.radioButton_14.isChecked():
            return 'linear'

    def interpolation_method_evi(self):
        if self.dlg.radioButton_20.isChecked():
            return 'CubicSpline'
        elif self.dlg.radioButton_21.isChecked():
            return 'polynomial'
        elif self.dlg.radioButton_22.isChecked():
            return 'linear'

    def choose_method(self):
        if self.dlg.radioButton_17.isChecked():
            return 'RUSL'
        elif self.dlg.radioButton_18.isChecked():
            return 'WRF'
        elif self.dlg.radioButton_19.isChecked():
            return 'CNN'

    def clipper_select(self):
        if self.dlg.radioButton.isChecked():
            return [self.dlg.lineEdit_2.text(), 'shape']

        elif self.dlg.radioButton_2.isChecked():
            coords = self.read_coordinates()
            return [coords, 'coords']

    def read_interpolate_year(self):
        date = self.dlg.dateEdit_3.date().toPyDate()
        date = str(date)
        year = date.split('-')[-1]
        return year

    def meta_data_master(self, name, output_directory):
        data_name = name.split('/')[-1]
        data_name = data_name.split('.')[0]
        data = gdal.Open(name)
        data_array = data.GetRasterBand(1).ReadAsArray()
        with open(output_directory + '/' + data_name + '_metadata.txt',
                  'w') as file:
            file.write(data_name)
            file.write('\n\nmax\t->\t' + str(np.max(data_array)))
            file.write('\nmin\t->\t' + str(np.min(data_array)))
            file.write('\nmean\t->\t' + str(np.mean(data_array)))
        iface.messageBar().pushMessage("Success",
                                       "Metadata file saved",
                                       duration=1.5)

    def meta_data_1(self):
        name = str(self.dlg.lineEdit_8.text())
        output_directory = str(self.dlg.lineEdit.text())
        self.meta_data_master(name, output_directory)

    def meta_data_2(self):
        name = str(self.dlg.lineEdit_9.text())
        output_directory = str(self.dlg.lineEdit.text())
        self.meta_data_master(name, output_directory)

    def meta_data_3(self):
        name = str(self.dlg.lineEdit_13.text())
        output_directory = str(self.dlg.lineEdit.text())
        self.meta_data_master(name, output_directory)

    def get_scenario(self):
        scenario_file, _filter = QFileDialog.getOpenFileName(
            self.dlg, "Select LU scenario", "", "*.shx")
        self.dlg.lineEdit_12.setText(scenario_file)

    def user_scenario(self):
        w = User_Scenario.MyWnd(self.iface.activeLayer())
        return w

    def user_scenario_temp(self):
        w = self.user_scenario()
        w.show()

    def user_scenario_shp(self):
        if self.dlg.radioButton_24.isChecked():
            return str(self.dlg.lineEdit_12.text())
        else:
            return False

    def final(self):

        clipper = self.clipper_select()

        method_pc = self.interpolation_method_pc()
        method_lst = self.interpolation_method_lst()
        method_evi = self.interpolation_method_evi()

        forcasting_method = self.choose_method()

        if self.dlg.radioButton_15.isChecked():
            normalization_directory = str(self.dlg.lineEdit_11.text())
        else:
            normalization_directory = False

    #  output_data_reso = float(self.dlg.lineEdit_12.text())

    # project_name = self.dlg.lineEdit_3.text()

        interpolate_year = self.read_interpolate_year()
        pc_directory = self.dlg.lineEdit_8.text()
        lst_directory = self.dlg.lineEdit_9.text()
        evi_directory = self.dlg.lineEdit_13.text()
        output_directory = self.dlg.lineEdit.text()
        user_scenario = self.user_scenario_shp()

        if user_scenario:
            lst_dir = output_directory + '/interpolated_lst_LU.tif'
            evi_dir = output_directory + '/interpolated_evi_LU.tif'
            pc_dir = output_directory + '/pc_file.tif'
        else:
            lst_dir = output_directory + '/interpolated_lst.tif'
            evi_dir = output_directory + '/interpolated_evi.tif'
            pc_dir = output_directory + '/pc_file.tif'

        iscript.interpolate(interpolate_year, method_lst, pc_directory,
                            output_directory, normalization_directory,
                            user_scenario)
        iscript.interpolate(interpolate_year, method_lst, lst_directory,
                            output_directory, normalization_directory,
                            user_scenario)
        iscript.interpolate(interpolate_year, method_evi, evi_directory,
                            output_directory, normalization_directory,
                            user_scenario)

        path_temp = str(__file__).split("\\")[:-1]
        path_temp = '\\'.join(path_temp)
        model_path = path_temp + '/erosion.hdf5'

        if forcasting_method == 'CNN':
            image = pred_ero.generate_input(pc_directory, lst_dir, evi_dir,
                                            output_directory)
            result = pred_ero.predict_image(image, model_path,
                                            output_directory)

        self.iface.addRasterLayer(result)

    def end(self):
        self.dlg.lineEdit.clear()
        self.dlg.lineEdit_2.clear()
        self.dlg.textEdit.clear()
        self.dlg.textEdit_2.clear()
        self.dlg.textEdit_3.clear()
        self.dlg.textEdit_4.clear()
        self.dlg.close()

    def run(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.dlg = Level2_ForecastingDialog()

        # show the dialog
        self.dlg.show()

        self.dlg.pushButton_3.clicked.connect(self.get_output_directory)
        self.dlg.pushButton_4.clicked.connect(self.get_shape_file)

        self.dlg.pushButton_10.clicked.connect(self.get_pc_series)
        self.dlg.pushButton_11.clicked.connect(self.get_lst_series)
        self.dlg.pushButton_12.clicked.connect(self.get_evi_series)

        self.dlg.pushButton_2.clicked.connect(self.get_normalization_directory)

        self.dlg.pushButton_7.clicked.connect(self.meta_data_1)
        self.dlg.pushButton_8.clicked.connect(self.meta_data_2)
        self.dlg.pushButton_9.clicked.connect(self.meta_data_3)

        self.dlg.pushButton_15.clicked.connect(self.get_scenario)
        self.dlg.pushButton.clicked.connect(self.user_scenario_temp)
        self.dlg.pushButton_5.clicked.connect(self.end)

        self.dlg.pushButton_6.clicked.connect(self.final)

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Пример #32
0
class GoogleEarthEnginePlugin(object):
    """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__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GoogleEarthEnginePlugin_{}.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)

        self.menu_name_plugin = self.tr("Google Earth Engine Plugin")

    # 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('GoogleEarthEngine', message)

    def initGui(self):
        ### Main dockwidget menu
        # Create action that will start plugin configuration
        icon_path = ':/plugins/ee_plugin/icons/earth_engine.svg'
        self.dockable_action = QAction(
            QIcon(icon_path), "User Guide", self.iface.mainWindow())
        # connect the action to the run method
        self.dockable_action.triggered.connect(self.run)
        # Add menu item
        self.iface.addPluginToMenu(self.menu_name_plugin, self.dockable_action)
        # Register signal to initialize EE layers on project load
        self.iface.projectRead.connect(self.updateLayers)
         

    def run(self):
        # open user guide in external web browser
        webbrowser.open_new(
            "http://qgis-ee-plugin.appspot.com/user-guide")

    def check_version(self):
        global version_checked
        
        if version_checked:
            return

        try:
            latest_version = requests.get('https://qgis-ee-plugin.appspot.com/get_latest_version').text

            if __version__ != latest_version:
                self.iface.messageBar().pushMessage(u'Earth Engine plugin says', u'Hey there, there is a more recent version of the ee_plugin available {0} and you have {1}, please upgrade!'.format(latest_version, __version__), duration=6)
        except: 
            print('Error occurrend when checking for recent plugin version, skipping ...')

        finally:
            version_checked = True


    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(
            self.menu_name_plugin, self.dockable_action)

    def updateLayers(self):
        layers = QgsProject.instance().mapLayers().values()

        for l in filter(lambda layer: layer.customProperty('ee-layer'), layers):
            ee_script = l.customProperty('ee-script')

            image = ee.deserializer.fromJSON(ee_script)
            utils.update_ee_image_layer(image, l)
Пример #33
0
class SelvansGeo():
    def __init__(self, iface):
        """
        Constructor of SelvanGeo. References to the
        """
        yaml_file = open(os.path.dirname(os.path.abspath(__file__)) + \
            "\\selvansgeo.yaml", 'r')
        self.conf = yaml.load(yaml_file)['vars']
        yaml_file.close()

        # Get reference to the QGIS interface
        self.iface = iface

        # A reference to our map canvas
        self.canvas = self.iface.mapCanvas()

        # Get reference to legend interface
        self.legendInterface = None  #self.iface.legendInterface()

        # Get reference to the legend interface
        self.layerRegistry = QgsProject.instance()

        # Create the GUI Dialog
        self.dlg = SelvansGeoDialog()

        # Initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # Get the QGIS message bar
        self.messageBar = self.iface.messageBar()

        # Initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n',
                                  'selvansgeo_{}.qm'.format(locale))

        # Globals
        self.currentRole = "init"
        self.credentialInstance = QgsCredentials.instance()
        self.readerPwd = self.conf['pg']['password']

        # Project paths
        self.defaultProjectPath = currentPath + "/qgisprj/" + \
            self.conf['default_project_qgis3']

        print(self.defaultProjectPath)
        s = QSettings()
        self.customProjectPath = s.value("SelvansGeo/customProject",
                                         self.defaultProjectPath)

        if self.customProjectPath == "":
            self.customProjectPath = self.defaultProjectPath

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

    def initGui(self):
        """
        Initialize the GUI, connect SIGNALS
        """

        self.action = QAction(QIcon(currentPath + "/icon.png"), u"SelvansGeo",
                              self.iface.mainWindow())

        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu("&SelvansGeo", self.action)

        # disable tabs until user is connected to db
        self.switchUiMode(True)
        # self.switchUiMode(False) # ==> switch on production

        # initialize connections to Application Databases - only reading access
        conf = self.conf
        self.pgdb = SitnDB(conf['pg']['dbname'], conf['pg']['host'],
                           conf['pg']['port'], conf['pg']['user'],
                           self.readerPwd, "postgres", self.iface)

        self.dlg.txtPassword.setText(self.readerPwd)

        # Connection to MSSQL
        self.msdb = SitnDB(conf['ms']['dbname'], conf['ms']['host'], "",
                           conf['ms']['user'], conf['ms']['password'], "mssql",
                           self.iface)
        self.qtmsdb, isMSOpened = self.msdb.createQtMSDB()
        # HANDLE MISSING CONNECTION HERE !!!
        # Thematic Analysis tools
        self.thematicanalysis = ThematicAnalysis(self.iface, self.dlg,
                                                 self.pgdb, self.qtmsdb)

        # SelvansGeo navigation tools
        self.tabularNavigation = tabularNavigation(self.dlg, self.pgdb,
                                                   self.canvas, self.iface)

        # Selvans cartographic tools
        self.fillAnalysisCombo()

        # *** Connect signals and slot***

        # Project
        self.dlg.btLoadProject.clicked.connect(self.openSelvansGeoProject)
        self.dlg.btDefineDefaultProject.clicked.connect(
            self.defineDefaultProject)
        self.dlg.btResetDefaultProject.clicked.connect(
            self.resetDefaultProject)

        # Connection
        self.dlg.btConnection.clicked.connect(self.connectionsInit)

        # self.switchUiMode(True)# DEBUG MODE. COMMENT IN PRODUCTION

        self.dlg.cmbConnection.currentIndexChanged.connect(
            self.setConnectionPwdTxt)
        # Help
        self.dlg.btQgisPrintComposerHelp.clicked.connect(
            self.openQgisPrintHelp)
        self.dlg.btQgisHelp.clicked.connect(self.openQgisHelp)
        self.dlg.btSelvansGeoHelp.clicked.connect(self.openSelvansGeoHelp)

        # Navigation tools
        self.dlg.listArr.itemClicked.connect(
            self.tabularNavigation.selectAdministration)
        self.dlg.listAdm.itemClicked.connect(
            self.tabularNavigation.selectDivision)
        self.dlg.listAdm.itemDoubleClicked.connect(
            self.tabularNavigation.zoomToSelectedAdministration)
        self.dlg.listDiv.itemDoubleClicked.connect(
            self.tabularNavigation.zoomToSelectedDivision)

        # Thematic analysis
        self.dlg.btAnalysis.clicked.connect(
            self.thematicanalysis.createAnalysis)
        self.dlg.btAdvancedUserMode.clicked.connect(
            self.analysisAdvancedUserMode)
        self.dlg.cmbAnalysis.currentIndexChanged.connect(
            self.thematicanalysis.getQueryStringFromDb)
        self.dlg.chkSaveAnalysisResult.stateChanged.connect(
            self.thematicanalysis.openFileDialog)
        self.dlg.chkLastSurvey.stateChanged.connect(
            self.thematicanalysis.checkLastSurvey)

        self.dlg.lnYearStart.setValidator(QIntValidator())
        self.dlg.lnYearStart.setMaxLength(4)
        self.dlg.lnYearEnd.setValidator(QIntValidator())
        self.dlg.lnYearEnd.setMaxLength(4)
        self.dlg.lnCoupeType.setValidator(QIntValidator())
        self.analysisAdvancedUserMode()
        self.dlg.frameIcon.setStyleSheet("image: url(" + currentPath +
                                         "/icon.png)")

        # Set default visibility of some GUI items
        self.dlg.lnYearStart.hide()
        self.dlg.lblDateStart.hide()
        self.dlg.chkLastSurvey.hide()
        self.dlg.txtAnalysisName.hide()
        self.dlg.lnCoupeType.hide()
        self.dlg.lblCoupeType.hide()
        self.dlg.lnYearEnd.hide()
        self.dlg.lblDateEnd.hide()
        self.dlg.chkSaveAnalysisResult.show()

        # Set label about project paths
        self.dlg.lblCurrentProject.setText(self.customProjectPath)

    # Define custom SelvanGeo Project path in user settings
    def defineDefaultProject(self):
        filename = QFileDialog.getOpenFileName(None, 'Choisir un projet')
        s = QSettings()
        s.setValue("SelvansGeo/customProject", filename[0])
        self.customProjectPath = filename[0]

        # Set label about project path
        self.dlg.lblCurrentProject.setText(self.customProjectPath)

    def resetDefaultProject(self):
        s = QSettings()
        s.setValue("SelvansGeo/customProject", self.defaultProjectPath)
        self.customProjectPath = self.defaultProjectPath
        # Set label about project paths
        self.dlg.lblCurrentProject.setText(self.customProjectPath)

    # reset QLine edit text box containing password
    def setConnectionPwdTxt(self):

        if self.dlg.cmbConnection.currentText() == "Edition":
            # writer credentials are stored in user profile once
            s = QSettings()
            writerCredentials = s.value("SelvansGeo/writerCredentials")
            if writerCredentials:
                self.dlg.txtPassword.setText(writerCredentials)
            else:
                self.dlg.txtPassword.setText("")
        elif self.dlg.cmbConnection.currentText() == "Consultation":
            self.dlg.txtPassword.setText(self.readerPwd)

    # Create connection to SFFN PostGIS DB
    def connectionsInit(self):

        conf = self.conf
        roleSelected = self.dlg.cmbConnection.currentText()

        # Connection string to Postgis db
        connectionInfo = "dbname='" + conf['pg']['dbname'] + "' "
        connectionInfo += "host=" + conf['pg']['host'] + " "
        connectionInfo += "port=" + conf['pg']['port'] + " "
        connectionInfo += "sslmode=disable"

        if roleSelected == 'Edition':
            user = conf["pg"]["editor"]
            pwd = self.dlg.txtPassword.text()
            if pwd == '':
                return
            else:
                s = QSettings()
                s.setValue("SelvansGeo/writerCredentials", pwd)
                # Setup QGIS credentials dialog
                checkdb = QSqlDatabase.addDatabase("QPSQL")
                checkdb.setHostName(conf['pg']['host'])
                checkdb.setDatabaseName(conf['pg']['dbname'])
                checkdb.setPort(int(conf['pg']['port']))
                checkdb.setUserName(user)
                checkdb.setPassword(pwd)

                if checkdb.open():
                    self.credentialInstance.put(connectionInfo, user, pwd)
                else:
                    self.messageBar.pushCritical("Erreur",
                                                 str("Mauvais mot de passe"))
                    self.dlg.txtPassword.setText("")
                    return

        elif roleSelected == 'Consultation':
            self.credentialInstance.put(
                connectionInfo,
                conf['pg']['user'],
                conf['pg']['password'],
            )

        self.switchUiMode(True)

        self.messageBar.pushMessage(str(u"Vous êtes connecté en mode ") +
                                    roleSelected,
                                    level=Qgis.Info)
        self.openSelvansGeoProject()

        # store the current role
        self.currentRole = roleSelected

        # check that MS Connection is still valid. It seems that the credential manager
        # somehow resets the connections when reconnecting to PG.
        if self.qtmsdb.isValid() is False:
            self.qtmsdb, isMSOpened = self.msdb.createQtMSDB()

    # Desactivate all UI except connection part
    def switchUiMode(self, mode):

        self.dlg.tabPanel.setTabEnabled(1, mode)
        self.dlg.tabPanel.setTabEnabled(2, mode)
        self.dlg.grpProjects.setEnabled(True)
        self.dlg.btLoadProject.setEnabled(mode)

    def openSelvansGeoProject(self):
        """
        Load the default SelvansGeo QGIS Project
        """
        warningTxt = str("Ceci annulera les modifications non sauvegardées " +
                         "du projet QGIS ouvert actuellement")

        reply = QMessageBox.question(self.dlg, 'Avertissement!', warningTxt,
                                     QMessageBox.Ok | QMessageBox.Cancel,
                                     QMessageBox.Cancel)
        if reply == QMessageBox.Ok:
            self.iface.addProject(self.customProjectPath)
            self.iface.actionOpenProject()

    def openQgisPrintHelp(self):
        """
        Link to QGIS print help
        """
        webbrowser.open("https://docs.qgis.org/2.8/en/docs/user_manual/" +
                        "print_composer/print_composer.html")

    def openQgisHelp(self):
        """
        Link to QGIS main help
        """
        webbrowser.open("http://docs.qgis.org/2.10/fr/docs/user_manual/")

    def openSelvansGeoHelp(self):
        """
        Link to SelvansGeo help
        """
        webbrowser.open("https://sitnintra.ne.ch/projects/qgis_repository/" +
                        "manuel_utilisateur.pdf")

    def setDesactivateLayerTool(self):
        if self.dlg.btDesactivateLayer.isChecked():
            self.desactivateLayerTool = \
                DesactivateLayerMapTool(self.canvas,
                                        self.legendInterface,
                                        self.dlg, self.iface,
                                        self.layerRegistry)

            self.canvas.setMapTool(self.desactivateLayerTool)
        else:
            self.iface.actionPan().trigger()
            self.dlg.btDesactivateLayer.setChecked(False)

    def analysisAdvancedUserMode(self):
        """
        Set up which buttons are shown when advanced user mode is selected
        """
        if self.dlg.btAdvancedUserMode.isChecked():
            self.dlg.txtMssqlQuery.show()
            self.dlg.lblSql.show()
        else:
            self.dlg.txtMssqlQuery.hide()
            self.dlg.lblSql.hide()

    def fillAnalysisCombo(self):
        """
        Fill the QComboBox with the list of analysis available
        """
        self.dlg.cmbAnalysis.clear()
        query = "(select oid, analysis_name, id from " + \
            self.conf["configuration_table"] + " order by id asc)"

        pgLayer = self.pgdb.getLayer("", query, None, "", "Analysis list",
                                     "oid")

        iter = pgLayer.getFeatures()
        for feature in iter:
            attrs = feature.attributes()
            idx = pgLayer.fields().indexFromName("analysis_name")
            analysis_name = attrs[idx]
            idx = pgLayer.fields().indexFromName("id")
            id = attrs[idx]
            self.dlg.cmbAnalysis.addItem(analysis_name, str(id))

    def fillAdminFilterCombo(self):
        """
        Fill the QComboBox with the list of administrations
        """
        self.dlg.cmbAdminFilter.clear()
        query = "(select idobj, adm from" + \
            "parcellaire.administrations order by adm asc)"
        pgLayer = self.pgdb.getLayer("", query, None, "",
                                     "Administration list", "idobj")

        iter = pgLayer.getFeatures()
        for feature in iter:
            attrs = feature.attributes()
            idx = pgLayer.fields().indexFromName("adm")
            administration_name = attrs[idx]
            idx = pgLayer.fields().indexFromName("idobj")
            id = attrs[idx]
            self.dlg.cmbAdminFilter.addItem(administration_name, str(idobj))

    def fillLayersCombo(self):
        """
        Fill the QComboBox with the list of geometric layers
        """
        self.dlg.comboLayers.clear()
        layers = QgsProject.instance().layers()
        for layer in layers:
            # Load only vector layers
            if layer.type() == 0 and layer.name() != 'Noeuds':
                if layer.hasGeometryType():
                    self.dlg.comboLayers.addItem(layer.originalName(), layer)

    def unload(self):
        """
        Remove the plugin menu item and icon
        """
        self.iface.removePluginMenu("&SelvansGeo", self.action)
        self.iface.removeToolBarIcon(self.action)

    # run method that performs all the real work
    def run(self):
        """
        show the dialog
        """
        self.dlg.show()
        # CALL THIS, REALLY ???
        #self.fillLayersCombo()
        # Run the dialog event loop
        self.dlg.exec_()
class CartogramUserInterfaceMixIn:
    """Distort a polygon map so that its area represent a field value."""
    def __init__(self):
        """Distort a polygon map so that its area represent a field value."""
        super(CartogramUserInterfaceMixIn, self).__init__()
        self.actions = []
        self.init_translations()

    def add_action(self,
                   icon_path,
                   text,
                   callback,
                   enabled=True,
                   add_to_menu=True,
                   add_to_toolbar=True,
                   status_tip=None,
                   whats_this=None,
                   parent=None):
        """
        Add a toolbar icon to the toolbar.

        Arguments
        ---------
        icon_path : str
            Path to the icon for this action.
        text : str
            Text that should be shown in menu items for this action.
        callback : function
            Function to be called when the action is triggered.
        enabled_flag : bool
            Should the action should be enabled? Default: True.
        add_to_menu : bool
            Should the action should be added to the menu? Default: True.
        add_to_toolbar : bool
            Should the action be added to the toolbar? Default: True.
        status_tip : str
            Show in a popup when mouse pointer hovers over the action.
        parent : QWidget
            Parent widget for the new action. Default: None.
        whats_this : str
            Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        Returns
        -------
        QAction: The action that was created. Note that the action is also
            added to self.actions list.
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled)

        if status_tip:
            action.setStatusTip(status_tip)
        if whats_this:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.iface.addToolBarIcon(action)
        if add_to_menu:
            self.iface.addPluginToVectorMenu(self.menu, action)

        self.actions.append(action)

        return action

    def add_result_layer_to_map_canvas(self, layer, field):
        layer_style = QDomDocument()
        self.input_layer.exportNamedStyle(layer_style)
        name = self.tr("Cartogram of {:s}, distorted using ‘{:s}’").format(
            self.input_layer.name(), field)
        layer.importNamedStyle(layer_style)
        layer.setName(name)
        QgsProject.instance().addMapLayer(layer)
        (QgsProject.instance().layerTreeRoot().findLayer(
            self.input_layer).setItemVisibilityChecked(False))
        self.clean_up_ui()

    def add_sample_dataset_clicked(self, message_bar_item=None):
        try:
            self.iface.messageBar().popWidget(message_bar_item)
        except TypeError:
            pass
        QgsProject.instance().addMapLayer(self.sample_layer())

    def clean_up_ui(self):
        try:
            del self._progress_bar
            del self._cancel_button
            self.iface.messageBar().popWidget(
                self._progress_bar_message_bar_item)
        except (AttributeError,
                RuntimeError):  # ‘wrapped C/C++ object has been deleted’
            pass

    def disable_cancel_button(self):
        try:
            self._cancel_button.setText(self.tr("Cancelled"))
            self._cancel_button.setEnabled(False)
        except (AttributeError,
                RuntimeError):  # ‘wrapped C/C++ object has been deleted’
            pass

    def confirm_if_geographic_crs(self, input_layer):
        if input_layer.sourceCrs().isGeographic():
            return (QMessageBox.question(
                None, self.tr("Geographic CRS"),
                self.tr("Computing a cartogram for a layer with a " +
                        "geographic CRS might not yield best results " +
                        "(consider reprojecting the layer to a " +
                        "projected coordinate system). \n\n" +
                        "Do you want to proceed?")) == QMessageBox.Yes)
        else:
            return True

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.menu = self.tr("&Cartogram")
        self.dialog = CartogramDialog()

        icon_path = os.path.join(self.plugin_dir, "img", "icon.png")

        self.add_action(icon_path,
                        text=self.tr("Compute cartogram"),
                        callback=self.show_dialog,
                        parent=self.iface.mainWindow())
        self.add_action(None,
                        text=self.tr("Add sample dataset"),
                        callback=self.add_sample_dataset_clicked,
                        add_to_toolbar=False,
                        parent=self.iface.mainWindow())

    def init_translations(self):
        userLocale = QSettings().value("locale/userLocale")[0:2]
        locale_path = os.path.join(
            self.plugin_dir, "i18n",
            "{:s}_{:s}.qm".format(self.PLUGIN_NAME, userLocale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

    def offer_to_add_sample_dataset(self):
        """Display an error message in message bar that offers to add a sample dataset."""
        message_bar_item = self.iface.messageBar().createMessage(
            self.tr("Error"))

        label = QLabel(
            self.
            tr("You need at least one polygon vector layer to create a cartogram."
               ))
        label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        message_bar_item.layout().addWidget(label)

        button = QPushButton(self.tr("Add sample dataset"))
        button.clicked.connect(
            functools.partial(self.add_sample_dataset_clicked,
                              message_bar_item=message_bar_item))
        message_bar_item.layout().addWidget(button)

        self.iface.messageBar().pushWidget(message_bar_item, Qgis.Critical)

    @property
    def progress_bar(self):
        try:
            return self._progress_bar
        except AttributeError:
            message_bar_item = QgsMessageBarItem("")

            label = QLabel(self.tr("Computing cartogram"))
            label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            message_bar_item.layout().addWidget(label)

            progress_bar = QProgressBar()
            progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            progress_bar.setMaximum(100)
            message_bar_item.layout().addWidget(progress_bar)

            cancel_button = QPushButton(self.tr("Cancel"))
            cancel_button.clicked.connect(self.cancel_task)
            message_bar_item.layout().addWidget(cancel_button)

            self.iface.messageBar().pushWidget(message_bar_item)
            self._progress_bar_message_bar_item = message_bar_item
            self._progress_bar = progress_bar
            self._cancel_button = cancel_button

            return self._progress_bar

    def project_has_polygon_layers(self):
        """Check whether the user added at least one polygon layer."""
        for layer in QgsProject.instance().mapLayers().values():
            if (layer.type() == QgsMapLayer.VectorLayer
                    and layer.geometryType() == QgsWkbTypes.PolygonGeometry):
                return True
        return False

    def remove_actions(self):
        """Remove the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.menu, action)
            self.iface.removeToolBarIcon(action)

    def save_input_layer_metadata(self, layer):
        """Remember the style xml of a layer."""
        layer_style = QDomDocument()
        layer.exportNamedStyle(layer_style)
        self.input_layer_style = layer_style

    def show_dialog(self):
        """Show the main dialog of this plugin."""
        if not self.is_task_running():
            if self.project_has_polygon_layers():
                self.dialog.show()
                if self.dialog.exec_():
                    input_layer = self.dialog.layerComboBox.currentLayer()
                    selected_fields = self.dialog.fieldListView.selectedFields(
                    )
                    max_iterations = self.dialog.iterationsSpinBox.value()
                    max_average_error = self.dialog.averageErrorDoubleSpinBox.value(
                    )

                    if self.confirm_if_geographic_crs(input_layer):
                        self.update_progress_bar(0)
                        self.start_task(input_layer, selected_fields[0],
                                        max_iterations, max_average_error)
                        # remember, so we can later copy metadata etc.
                        self.input_layer = input_layer
            else:
                self.offer_to_add_sample_dataset()

    def update_progress_bar(self, value):
        try:
            self.progress_bar.setValue(int(value))
        except RuntimeError:  # ‘wrapped C/C++ object has been deleted’
            pass

    def tr(self, message):
        """
        Retrieve the translation for a string using Qt translation API.

        Arguments
        ---------
        message : str
            The text to be translated

        Returns
        -------
        str:
            The translated text
        """
        return QCoreApplication.translate(self.__class__.__name__, message)
class MCDM:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'MCDM_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Multi Criteria Decision Maker')
        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('MCDM', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/MCDM/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'MCDM'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Multi Criteria Decision Maker'), action)
            self.iface.removeToolBarIcon(action)

    def select_output_file(self):
        filename, _filter = QFileDialog.getSaveFileName(
            self.dlg, "Select output file ", "", '*.tif')
        self.dlg.lineEdit.setText(filename)

    def layerAsArray(self, layer):
        gd = gdal.Open(str(layer.source()))
        Array = gd.ReadAsArray()
        return Array

    def run(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.dlg = MCDMDialog()
            self.dlg.pushButton.clicked.connect(self.select_output_file)

        # Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children()
        # Clear the contents of the comboBox and lineedit from previous runs
        self.dlg.mMapLayerComboBox_1.clear()
        #self.dlg.lineEdit.clear()
        # Populate the comboBoxes with names of all the loaded layers
        self.dlg.mMapLayerComboBox_1.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox_2.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox_3.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox_4.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox_5.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox_6.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox_7.addItems(
            [layer.name() for layer in layers])
        self.dlg.mMapLayerComboBox.addItems([layer.name() for layer in layers])

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            #getting the boundary
            Boundary = self.dlg.mMapLayerComboBox.currentText()
            V_Boundary = QgsProject().instance().mapLayersByName(Boundary)[0]

            #getting the browsed file name
            filename = self.dlg.lineEdit.text()

            #getting the final output resolution
            PixelSize = int(self.dlg.spinBox_8.value())

            # Road network

            #Retrieving values from interface
            Road = self.dlg.mMapLayerComboBox_1.currentText()
            V_Road = QgsProject().instance().mapLayersByName(Road)[0]
            Road_O = str(self.dlg.comboBox.currentText())
            Road_W = int(self.dlg.spinBox.value())
            name = 'Road'

            #Applying tools
            V_Road_Clip = VectorClip(V_Road, V_Boundary)
            R_Road, Location = Rasterize(V_Road_Clip, V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            R_Road_distance = RasterDistance(R_Road)
            R_Road_D_Clip = RasterClip(R_Road_distance, V_Boundary)
            RRoadDC_Reclass, Location = Reclassify(R_Road_D_Clip, Road_O)
            #Display to check the process
            #self.iface.addRasterLayer(Location, "reclassify")

            # Transmission lines
            #Retrieving values from interface
            Transmission = self.dlg.mMapLayerComboBox_2.currentText()
            V_Transmission = QgsProject().instance().mapLayersByName(
                Transmission)[0]
            Transmis_O = str(self.dlg.comboBox_2.currentText())
            Transmis_W = int(self.dlg.spinBox_2.value())
            name = 'Transmission'

            #Applying tools
            V_Transmission_Clip = VectorClip(V_Transmission, V_Boundary)
            R_Trasmission, Location = Rasterize(V_Transmission_Clip,
                                                V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            RT_Distance = RasterDistance(R_Trasmission)
            RTD_Clip = RasterClip(RT_Distance, V_Boundary)
            RTrans_DC_Reclass, Location = Reclassify(RTD_Clip, Transmis_O)

            #Display to check the process
            #self.iface.addRasterLayer(Location, "reclassify")

            # Restrcited Lands
            #Retrieving values from interface

            Restric_Land = self.dlg.mMapLayerComboBox_3.currentText()
            V_Restric_Land = QgsProject().instance().mapLayersByName(
                Restric_Land)[0]
            name = 'RestrictLand'

            #Applying tools
            V_Restric_Land_Clip = VectorClip(V_Restric_Land, V_Boundary)
            R_Restric_Land, Location = Rasterize(V_Restric_Land_Clip,
                                                 V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            R_Restric_Land_clip = RasterClip(R_Restric_Land, V_Boundary)

            # Land Cover
            #Retrieving values from interface
            LandCover = self.dlg.mMapLayerComboBox_4.currentText()
            V_LandCover = QgsProject().instance().mapLayersByName(LandCover)[0]
            LandC_O = str(self.dlg.comboBox_4.currentText())
            LandC_W = int(self.dlg.spinBox_4.value())
            name = 'LandCover'

            #Applying tools
            R_LandCo, Location = Rasterize(V_LandCover, V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            R_LandCo_reclass, Location = LC_Reclassify(R_LandCo, LandC_O)
            #self.iface.addRasterLayer(Location, "reclassify")

            # Population density
            #Retrieving values from interface
            Pop_De = self.dlg.mMapLayerComboBox_5.currentText()
            V_PopDe = QgsProject().instance().mapLayersByName(Pop_De)[0]
            PopDe_O = str(self.dlg.comboBox_5.currentText())
            PopDe_W = int(self.dlg.spinBox_5.value())
            name = 'PopDe'

            #Applying tools
            R_PopDe, Location = Rasterize(V_PopDe, V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            R_PopDe_Reclass, Location = Reclassify(R_PopDe, PopDe_O)

            #Display to check the process
            #self.iface.addRasterLayer(Location, "reclassify")

            # Solar resource potential
            #Retrieving values from interface
            Solar = self.dlg.mMapLayerComboBox_6.currentText()
            V_Solar = QgsProject().instance().mapLayersByName(Solar)[0]
            Solar_O = str(self.dlg.comboBox_6.currentText())
            Solar_W = int(self.dlg.spinBox_6.value())
            name = 'Solar'

            #Applying tools
            R_Solar, Location = Rasterize(V_Solar, V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            R_Solar_Mex = RasterClip(R_Solar, V_Boundary)
            R_Solar_Reclass, Location = Reclassify(R_Solar_Mex, Solar_O)

            #Display to check the process
            #self.iface.addRasterLayer(Location, "reclassify")

            #City centroids
            #Retrieving values from interface
            City = self.dlg.mMapLayerComboBox_7.currentText()
            V_City = QgsProject().instance().mapLayersByName(City)[0]
            City_O = str(self.dlg.comboBox_7.currentText())
            City_W = int(self.dlg.spinBox_7.value())
            name = 'CityCen'

            #Applying tools
            R_City, Location = Rasterize(V_City, V_Boundary, name)
            #self.iface.addRasterLayer(Location, "Rasterisation")
            RCdistance = RasterDistance(R_City)
            RCD_clip = RasterClip(RCdistance, V_Boundary)
            RCDC_reclassify, Location = Reclassify(RCD_clip, City_O)

            #Display to check the process
            #self.iface.addRasterLayer(Location, "reclassify")

            #Call weighted Overlay

            #make a list with final reclassified layers and weights

            a = [
                RRoadDC_Reclass, RTrans_DC_Reclass, R_LandCo_reclass,
                R_PopDe_Reclass, R_Solar_Reclass, RCDC_reclassify
            ]
            b = [Road_W, Transmis_W, LandC_W, PopDe_W, Solar_W, City_W]

            #Convert qgs Raster Layers to numpy arrays
            A_Road = self.layerAsArray(RRoadDC_Reclass)
            A_Transmission = self.layerAsArray(RTrans_DC_Reclass)
            A_LandCo = self.layerAsArray(R_LandCo_reclass)
            A_PopDe = self.layerAsArray(R_PopDe_Reclass)
            A_Solar = self.layerAsArray(R_Solar_Reclass)
            A_CityCe = self.layerAsArray(RCDC_reclassify)
            A_Restrict = self.layerAsArray(R_Restric_Land_clip)

            #Sum of weights
            Total_weight = (Road_W + Transmis_W + LandC_W + PopDe_W + Solar_W +
                            City_W)

            #Weighted sum
            A_Final = (Road_W * A_Road + Transmis_W * A_Transmission +
                       LandC_W * A_LandCo + PopDe_W * A_PopDe +
                       A_Solar * Solar_W + City_W * A_CityCe) / Total_weight

            #Remove restricted Lands from weighted overlay
            rows = A_Final.shape[0]
            cols = A_Final.shape[1]
            Final = np.zeros(shape=(rows, cols))
            for x in range(0, rows):
                for y in range(0, cols):
                    if A_Restrict[x, y] == 1:
                        Final[x, y] = 0
                    else:
                        Final[x, y] = A_Final[x, y]

    #Create new file to write the numpy output as a raster
            gdal_RCDC_reclassify = gdal.Open(RCDC_reclassify.source())
            driver = gdal.GetDriverByName("GTiff")
            file2 = driver.Create(filename, RCDC_reclassify.width(),
                                  RCDC_reclassify.height(), 1)

            #Fetching the spatial refrence and Geo transforms to new file
            file2.SetGeoTransform(gdal_RCDC_reclassify.GetGeoTransform())
            spatial_reference = osr.SpatialReference()
            spatial_reference.ImportFromEPSG(4151)
            file2.SetProjection(spatial_reference.ExportToWkt())
            file2.GetRasterBand(1).WriteArray(Final)

            #Displaying Final Layer in qgs interface
            rlayer = QgsRasterLayer(filename, "MCDM output")
            QgsProject.instance().addMapLayer(rlayer)
            #self.iface.addRasterLayer(rlayer)

            #End of the program
            self.iface.messageBar().pushMessage("Success",
                                                "Output file written at " +
                                                filename,
                                                level=Qgis.Success,
                                                duration=3)
Пример #36
0
class ExcelSync:
    """QGIS Plugin Implementation."""
    def setUpSyncerTest(self, excelName, excelKeyName, shpName, shpKeyName):
        """Test the setup"""
        exps = {
            "Flaeche_ha": "area( $geometry )/10000",
            "FEE_Nr": "y( $geometry )"
        }
        s = Settings(excelName, "Tabelle1", excelKeyName, 1, shpName,
                     shpKeyName, exps)
        self.syncer = Syncer(s)

    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
        self.syncer = None
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   '{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            QCoreApplication.installTranslator(self.translator)

        self.dlg = None

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&ExcelSync')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'excel_sync')
        self.toolbar.setObjectName(u'excel_sync')
        self.initProject()

    def initProject(self):
        """ initialize project related connections """
        self.iface.projectRead.connect(self.readSettings)
        self.iface.newProjectCreated.connect(self.reset)
        QgsProject.instance().writeProject.connect(self.writeSettings)

    def reset(self):
        del self.syncer
        self.syncer = None

    def readSettings(self):
        # "Settings","excelName excelSheetName excelKeyName skipLines shpName
        # shpKeyName expressions")
        self.reset()
        metasettings = OrderedDict()
        metasettings["excelName"] = (str, None)
        metasettings["excelSheetName"] = (str, None)
        metasettings["excelKeyName"] = (str, None)
        metasettings["skipLines"] = (int, None)
        metasettings["shpKeyName"] = (str, None)
        metasettings["shpName"] = (str, None)
        metasettings["expressions"] = (list, [])
        metasettings["hideDialog"] = (bool, False)
        settings_dict = ProjectHandler.readSettings("SHPSYNC", metasettings)
        if "excelName" not in settings_dict or \
           settings_dict["excelName"] == '':
            return
        else:
            exps = settings_dict["expressions"]
            exps_dict = {}
            for exp in exps:
                kv = exp.split(":::")
                exps_dict[kv[0]] = kv[1]
            settings = Settings(
                settings_dict["excelName"], settings_dict["excelSheetName"],
                settings_dict["excelKeyName"], settings_dict["skipLines"],
                settings_dict["shpName"], settings_dict["shpKeyName"],
                exps_dict, settings_dict['hideDialog'])
            self.initSyncer(settings)

    def writeSettings(self, doc):
        if self.syncer is None:
            return
        settings = self.syncer.s._asdict()
        settings["expressions"] = [
            "{}:::{}".format(k, v) for k, v in settings["expressions"].items()
        ]
        ProjectHandler.writeSettings("SHPSYNC", settings)

    # 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('excel_sync', 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."""

        dir_path = os.path.dirname(os.path.realpath(__file__))

        icon_path = os.path.join(dir_path, 'gui/icon.png')
        self.add_action(icon_path,
                        text=self.tr(u'Set up ExcelSync'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&ExcelSync'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        if self.dlg is not None:
            del self.dlg
        self.dlg = excel_syncDialog()
        self.dlg.buttonBox.accepted.connect(self.parseSettings)
        self.dlg.buttonBox.rejected.connect(self.hideDialog)
        if self.syncer is None:
            for i in range(3):
                self.dlg.addExpressionWidget()
            self.dlg.exps[0].setField("x($geometry)")
            self.dlg.exps[1].setField("y($geometry)")
            self.dlg.exps[2].setField("area($geometry)/10000")
        else:
            self.dlg.restoreSettings(self.syncer.s)
        self.dlg.show()

    def parseSettings(self):
        exps = self.dlg.getExpressionsDict()
        excelName = self.dlg.comboBox_slave.currentText()
        excelKeyName = self.dlg.comboBox_slave_key.currentText()
        shpName = self.dlg.comboBox_master.currentText()
        shpKeyName = self.dlg.comboBox_master_key.currentText()
        excelSheetName = self.dlg.lineEdit_sheetName.text()
        skipLines = self.dlg.spinBox.value()
        hideDialog = self.dlg.checkBox.isChecked()
        s = Settings(excelName, excelSheetName, excelKeyName, skipLines,
                     shpName, shpKeyName, exps, hideDialog)
        self.initSyncer(s)
        self.hideDialog()

    def initSyncer(self, settings):
        if self.syncer is not None:
            del self.syncer
        self.syncer = Syncer(settings)

    def hideDialog(self):
        self.dlg.hide()
Пример #37
0
class PipelinePlanner:
    """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
        self.canvas = self.iface.mapCanvas()
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        self.addPipelinePoint = QgsMapToolEmitPoint(self.canvas)
        self.rbPipeline = QgsRubberBand(self.canvas)
        self.rbPipeline.setColor(Qt.red)
        self.rbPipeline.setWidth(4)
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'PipelinePlanner_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Pipeline Planner')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None
        self.dlg = PipelinePlannerDialog()
        self.dlg.tblImpacts.setColumnWidth(1, 75)
        self.dlg.tblImpacts.setColumnWidth(2, 250)
        self.dlg.tblImpacts.setColumnWidth(3, 75)

    # 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('PipelinePlanner', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToVectorMenu(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/pipeline_planner/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Pipeline Planner'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True
        self.addPipelinePoint.canvasClicked.connect(self.evaluatePipeline)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.tr(u'&Pipeline Planner'),
                                              action)
            self.iface.removeToolBarIcon(action)

    def run(self):
        """Run method that performs all the real work"""
        self.canvas.setMapTool(self.addPipelinePoint)

    def evaluatePipeline(self, point, button):
        if button == Qt.LeftButton:
            self.rbPipeline.addPoint(point)
            self.rbPipeline.show()
        elif button == Qt.RightButton:
            pipeline = self.rbPipeline.asGeometry()
            self.dlg.tblImpacts.setRowCount(0)

            lyrRaptor = QgsProject.instance().mapLayersByName(
                "Raptor Buffer")[0]
            raptors = lyrRaptor.getFeatures(pipeline.boundingBox())
            for raptor in raptors:
                valConstraint = raptor.attribute("recentspec")
                valID = raptor.attribute("Nest_ID")
                valStatus = raptor.attribute("recentstat")
                valDistance = pipeline.distance(raptor.geometry().centroid())
                if raptor.geometry().intersects(pipeline):
                    row = self.dlg.tblImpacts.rowCount()
                    self.dlg.tblImpacts.insertRow(row)
                    self.dlg.tblImpacts.setItem(
                        row, 0, QTableWidgetItem(valConstraint))
                    self.dlg.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(str(valID)))
                    self.dlg.tblImpacts.setItem(row, 2,
                                                QTableWidgetItem(valStatus))
                    self.dlg.tblImpacts.setItem(
                        row, 3,
                        QTableWidgetItem("{:4.5f}".format(valDistance)))

            lyrEagle = QgsProject.instance().mapLayersByName("BAEA Buffer")[0]
            eagles = lyrEagle.getFeatures(pipeline.boundingBox())
            for eagle in eagles:
                valConstraint = "BAEA Nest"
                valID = eagle.attribute("nest_id")
                valStatus = eagle.attribute("status")
                valDistance = pipeline.distance(eagle.geometry().centroid())
                if eagle.geometry().intersects(pipeline):
                    row = self.dlg.tblImpacts.rowCount()
                    self.dlg.tblImpacts.insertRow(row)
                    self.dlg.tblImpacts.setItem(
                        row, 0, QTableWidgetItem(valConstraint))
                    self.dlg.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(str(valID)))
                    self.dlg.tblImpacts.setItem(row, 2,
                                                QTableWidgetItem(valStatus))
                    self.dlg.tblImpacts.setItem(
                        row, 3,
                        QTableWidgetItem("{:4.5f}".format(valDistance)))

            lyrBUOWL = QgsProject.instance().mapLayersByName("BUOWL Buffer")[0]
            buowls = lyrBUOWL.getFeatures(pipeline.boundingBox())
            for buowl in buowls:
                valConstraint = "BUOWL Habitat"
                valID = buowl.attribute("habitat_id")
                valStatus = buowl.attribute("recentstat")
                valDistance = pipeline.distance(buowl.geometry().buffer(
                    -0.001, 5))
                if buowl.geometry().intersects(pipeline):
                    row = self.dlg.tblImpacts.rowCount()
                    self.dlg.tblImpacts.insertRow(row)
                    self.dlg.tblImpacts.setItem(
                        row, 0, QTableWidgetItem(valConstraint))
                    self.dlg.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(str(valID)))
                    self.dlg.tblImpacts.setItem(row, 2,
                                                QTableWidgetItem(valStatus))
                    self.dlg.tblImpacts.setItem(
                        row, 3,
                        QTableWidgetItem("{:4.5f}".format(valDistance)))

            self.dlg.show()

            self.rbPipeline.reset()
class PetroProfile:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'PetroProfile_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&geoCore')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None
        self.dlg = None

    # 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('geoCore', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/geoCore/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Show drilling profile'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&geoCore'),
                action)
            self.iface.removeToolBarIcon(action)


    def run(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:
            self.first_start = False
            self.dlg = PetroProfileDialog(self.iface)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Пример #39
0
class HTPGeoprocessor(object): 

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n', 'htpgeoprocessor_{}.qm'.format(locale))

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

    def initGui(self):  
        # Create action that will start plugin configuration
        icon = QIcon(":/plugins/htpgeoprocessor/icon.png")
        self.createmap = QAction(icon,u"Map Creator", self.iface.mainWindow())
        self.preprocess = QAction(icon,u"Preprocessor", self.iface.mainWindow())
        self.geoprocess = QAction(icon,u"Geoprocessor", self.iface.mainWindow())
        self.helpme = QAction(icon, u"Help", self.iface.mainWindow())
        
        # connect the action to a method
        self.createmap.triggered.connect(self.CreateMap)
        self.preprocess.triggered.connect(self.Preprocess)
        self.geoprocess.triggered.connect(self.Geoprocess)
        self.helpme.triggered.connect(self.Help)
         
        # Add toolbar button and menu item
        self.iface.addPluginToMenu(u"&HTP Geoprocessor", self.createmap)
        self.iface.addPluginToMenu(u"&HTP Geoprocessor", self.preprocess)
        self.iface.addPluginToMenu(u"&HTP Geoprocessor", self.geoprocess)
        self.iface.addPluginToMenu(u"&HTP Geoprocessor", self.helpme)
                
    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(u"&HTP Geoprocessor", self.createmap)
        self.iface.removePluginMenu(u"&HTP Geoprocessor", self.preprocess)
        self.iface.removePluginMenu(u"&HTP Geoprocessor", self.geoprocess)
        self.iface.removePluginMenu(u"&HTP Geoprocessor", self.helpme)
        
    # run methods that perform all the real work
    def CreateMap(self):
        dlg = MapCreatorDlg(self.iface)
        dlg.exec_()
    
    def Preprocess(self):
        dlg = PreprocessorDlg()
        dlg.exec_()
          
    def Geoprocess(self): 
        # create and show the dialog 
        dlg = GeoprocessorDlg(self.iface) 
        # show the dialog
        #dlg.show() #Modeless dialog
        dlg.exec_() #Modal dialog
        
    def Help(self):
        path = os.path.dirname(sys.modules[__name__].__file__)
        if sys.platform[:-1] == 'linux':
            os.system(path+"//HTP Geoprocessor README.pdf")
        elif sys.platform == 'darwin':
            os.system(path+"//HTP Geoprocessor README.pdf")
        elif sys.platform == 'win32' or 'win64':
            os.startfile(path+"\\HTP Geoprocessor README.pdf")
        else:
            QMessageBox.critical(self.iface.mainWindow(),'Help','Error opening document. Look in plug-in install directory for PDF.')
class Point2One:
    """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__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'Point2One_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Point2One')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'Point2One')
        self.toolbar.setObjectName(u'Point2One')

        #print "** INITIALIZING Point2One"

        self.pluginIsActive = False
        self.dockwidget = None

    # 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('Point2One', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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/Point2One/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Point2One'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    #--------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        #print "** CLOSING Point2One"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        #print "** UNLOAD Point2One"

        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Point2One'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    #--------------------------------------------------------------------------

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            #print "** STARTING Point2One"

            # 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 = Point2OneDockWidget()
                self.dockwidget.layers.setFilters(
                    QgsMapLayerProxyModel.PointLayer)
                self.dockwidget.OK.clicked.connect(self.Point2One)

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)
            self.dockwidget.layers.layerChanged.connect(
                self.dockwidget.SortVerticesBy.setLayer
            )  # setLayer is a native slot function
            self.dockwidget.layers.layerChanged.connect(
                self.dockwidget.GroupFeaturesBy.setLayer
            )  # setLayer is a native slot function
            self.dockwidget.SortVerticesBy.setLayer(
                self.dockwidget.layers.currentLayer())
            self.dockwidget.GroupFeaturesBy.setLayer(
                self.dockwidget.layers.currentLayer())
            self.dockwidget.output_dir.setStorageMode(
                QgsFileWidget.GetDirectory)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
            self.dockwidget.show()

    # The function loads input point layer
    def loadPointLayer(self):
        return self.dockwidget.layers.currentLayer()

    # The function creates linestring from point layer
    def createLinestringLayer(self, points, point_layer, closed):

        # create a new memory layer
        v_layer = QgsVectorLayer("LineString", "line", "memory")
        v_layer.setCrs(QgsCoordinateReferenceSystem(point_layer.crs()))
        pr = v_layer.dataProvider()

        # save features into layer
        for key in points.keys():
            # retrieve single grouped point list from dictionary
            PointList = points[key]

            verticies = PointList[1:len(PointList)]
            line_end = PointList[0]
            first_point = PointList[0]
            segments = []
            for point in verticies:
                # create a new feature
                seg = QgsFeature()
                line_start = line_end
                line_end = point
                seg.setGeometry(
                    QgsGeometry.fromPolylineXY([line_start, line_end]))
                # add the geometry to the layer
                segments.append(seg)

            # checkbox close, creating a line between the first and last point
            if closed:
                seg = QgsFeature()
                seg.setGeometry(
                    QgsGeometry.fromPolylineXY([line_end, first_point]))
                segments.append(seg)

            pr.addFeatures(segments)

        # update extent of the layer (not necessary)
        v_layer.updateExtents()

        return v_layer

    # The function creates polygons from point layer
    def createPolygonLayer(self, points, point_layer):

        layer = QgsVectorLayer('Polygon', 'poly', "memory")
        layer.setCrs(QgsCoordinateReferenceSystem(point_layer.crs()))
        pr = layer.dataProvider()
        poly = QgsFeature()

        for key in points.keys():
            # retrieve single grouped point list from dictionary
            PointList = points[key]
            poly.setGeometry(QgsGeometry.fromPolygonXY([PointList]))
            pr.addFeatures([poly])
            layer.updateExtents()

        return layer

    # The function saves the created layer to geopackage
    def saveGeopackage(self, save_layer):
        # load path from dockwidget
        path = self.dockwidget.output_dir.filePath()
        # load filename
        name_layer = self.dockwidget.Filename.text() + '.gpkg'

        if not path:
            iface.messageBar().pushMessage("Error",
                                           "set output",
                                           level=Qgis.Critical)
            return

        data_folder = os.path.join(path, name_layer)

        # create geopackage
        error = QgsVectorFileWriter.writeAsVectorFormat(
            save_layer, data_folder, "")
        if error[0] != QgsVectorFileWriter.NoError:
            iface.messageBar().pushMessage(
                "Error",
                "Creating of the geopackage is failed",
                level=Qgis.Critical)
            return

        # open layer
        vlayer = QgsVectorLayer(data_folder, self.dockwidget.Filename.text(),
                                "ogr")
        QgsProject.instance().addMapLayer(vlayer)

    # The function sorts by attributes and group by attributes
    def generatePoints(self, sortAttr, groupAttr, point_layer):
        points = {}
        features = list(point_layer.getFeatures())

        # sort by attributes
        if sortAttr:
            unique = []
            # testing a unique value in attribute
            for feature in features:
                attrValue = feature.attribute(sortAttr)
                if attrValue not in unique:
                    unique.append(attrValue)
                else:
                    iface.messageBar().pushMessage(
                        "Warning",
                        "values in the attribute are not unique ",
                        level=Qgis.Warning)

            features.sort(key=lambda a: a.attribute(sortAttr))

        # group by attributes
        if groupAttr:
            for feature in features:
                # get value of attribute by which we group
                attrValue = feature.attribute(groupAttr)

                if attrValue not in points.keys():
                    # if there isn't list of points for given attribute value, we create empty list
                    points[attrValue] = []

                # append this point to list
                points[attrValue].append(feature.geometry().asPoint())
        else:
            points["all"] = []
            for feature in features:
                points["all"].append(feature.geometry().asPoint())

        return points

    def Point2One(self):
        #self.iface.messageBar().pushMessage(
        #"Warning", "It may take a while! Don't close QGIS!", level=Qgis.Warning
        #)

        # load point layer into map canvas
        point_layer = self.loadPointLayer()

        # get input parameters
        if self.dockwidget.checkSortVertices.isChecked():
            sortAttr = self.dockwidget.SortVerticesBy.currentField()
            if sortAttr == "":
                iface.messageBar().pushMessage(
                    "Error",
                    "You have to select attribute to sort by",
                    level=Qgis.Critical)
        else:
            sortAttr = None
        if self.dockwidget.checkGroupBy.isChecked():
            groupAttr = self.dockwidget.GroupFeaturesBy.currentField()
            if groupAttr == "":
                iface.messageBar().pushMessage(
                    "Error",
                    "You have to select attribute to group by",
                    level=Qgis.Critical)
        else:
            groupAttr = None

        # generate vertices for linestrings/polygons
        points = self.generatePoints(sortAttr, groupAttr, point_layer)

        # selection of line or polygon
        # if you choose line
        if self.dockwidget.create_lines.isChecked():
            closed = self.dockwidget.closed.isChecked()

            output_layer = self.createLinestringLayer(points, point_layer,
                                                      closed)

        # if you choose polygon
        elif self.dockwidget.create_polygon.isChecked():

            output_layer = self.createPolygonLayer(points, point_layer)

        # if is not selected line or polygon
        else:
            iface.messageBar().pushMessage("Error",
                                           "Choose lines or polygon",
                                           level=Qgis.Critical)
            return

        # if is check geopackage
        if self.dockwidget.Output_geopackage.isChecked():
            self.saveGeopackage(output_layer)

        # if isn't check geopackage, created layer in opened into map canvas
        else:
            QgsProject.instance().addMapLayers([output_layer])
Пример #41
0
class QFieldSync(object):
    """QGIS Plugin Implementation."""
    QFIELD_SCOPE = "QFieldSync"

    push_dlg = None

    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__)
        # initialize locale
        locale_str = QSettings().value('locale/userLocale')
        if isinstance(locale_str, str):
            locale = QLocale(locale_str)
        else:
            locale = QLocale()

        locale_path = os.path.join(self.plugin_dir, 'i18n')
        self.translator = QTranslator()
        self.translator.load(locale, 'qfieldsync', '_', locale_path)

        QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr('&QFieldSync')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar('QFieldSync')
        self.toolbar.setObjectName('QFieldSync')

        # instance of the map config widget factory, shown in layer properties
        self.mapLayerConfigWidgetFactory = MapLayerConfigWidgetFactory('QField', QIcon(os.path.join(os.path.dirname(__file__), 'resources/icon.png')))

        # instance of the QgsOfflineEditing
        self.offline_editing = QgsOfflineEditing()
        self.preferences = Preferences()

        QgsProject.instance().readProject.connect(self.update_button_enabled_status)

        # store warnings from last run
        self.last_action_warnings = []

    # 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('QFieldSync', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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."""

        self.push_action = self.add_action(
            os.path.join(os.path.dirname(__file__), 'resources/refresh.png'),
            text=self.tr('Package for QField'),
            callback=self.show_package_dialog,
            parent=self.iface.mainWindow())

        self.add_action(
            os.path.join(os.path.dirname(__file__), 'resources/refresh-reverse.png'),
            text=self.tr('Synchronize from QField'),
            callback=self.show_synchronize_dialog,
            parent=self.iface.mainWindow())

        self.add_action(
            os.path.join(os.path.dirname(__file__), './resources/icon.png'),
            text=self.tr('Project Configuration'),
            callback=self.show_project_configuration_dialog,
            parent=self.iface.mainWindow(),
            add_to_toolbar=False
        )

        self.add_action(
            os.path.join(os.path.dirname(__file__), './resources/icon.png' ),
            text=self.tr('Preferences'),
            callback=self.show_preferences_dialog,
            parent=self.iface.mainWindow(),
            add_to_toolbar=False)

        self.iface.registerMapLayerConfigWidgetFactory(self.mapLayerConfigWidgetFactory)

        self.update_button_enabled_status()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr('&QFieldSync'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

        self.iface.unregisterMapLayerConfigWidgetFactory(self.mapLayerConfigWidgetFactory)

    def show_preferences_dialog(self):
        dlg = PreferencesDialog(self.iface.mainWindow())
        dlg.exec_()

    def show_synchronize_dialog(self):
        """
        Synchronize from QField
        """
        dlg = SynchronizeDialog(self.iface, self.offline_editing, self.iface.mainWindow())
        dlg.exec_()

    def show_package_dialog(self):
        """
        Push to QField
        """
        self.push_dlg = PackageDialog(self.iface, QgsProject.instance(), self.offline_editing,
                                      self.iface.mainWindow())
        self.push_dlg.setAttribute(Qt.WA_DeleteOnClose)
        self.push_dlg.setWindowFlags(self.push_dlg.windowFlags() | Qt.Tool)
        self.push_dlg.show()

        self.push_dlg.finished.connect(self.push_dialog_finished)
        self.update_button_enabled_status()

    def show_project_configuration_dialog(self):
        """
        Show the project configuration dialog.
        """
        dlg = ProjectConfigurationDialog(self.iface, self.iface.mainWindow())
        dlg.exec_()

    def action_start(self):
        self.clear_last_action_warnings()

    def clear_last_action_warnings(self):
        self.last_action_warnings = []

    def push_dialog_finished(self):
        """
        When the push dialog is closed, make sure it's no longer
        enabled before entering update_button_enabled_status()
        """
        try:
            self.push_dlg.setEnabled(False)
        except RuntimeError:
            pass
        self.update_button_enabled_status()

    def update_button_enabled_status(self):
        """
        Will update the plugin buttons according to open dialog and project properties.
        """
        try:
            dialog_is_enabled = self.push_dlg and self.push_dlg.isEnabled()
        except RuntimeError:
            dialog_is_enabled = False

        if self.offline_editing.isOfflineProject() or dialog_is_enabled:
            self.push_action.setEnabled(False)
        else:
            self.push_action.setEnabled(True)
class CircleCraters(object):
    """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
        self.canvas = self.iface.mapCanvas()

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'CircleCraters_{}.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)

        # Create the dialog (after translation) and keep reference
        self.export_dlg = ExportDialog()
        self.export_dlg.selected.connect(self.export)

        self.choose_counting_dlg = ChooseCountingLayerDialog()
        self.choose_counting_dlg.selected.connect(self.on_counting_layer_select)

        self.choose_raster_dlg = ChooseRasterLayerDialog()
        self.choose_raster_dlg.selected.connect(self.on_raster_layer_select)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Circle Craters')

        self.toolbar = self.iface.addToolBar(u'CircleCraters')
        self.toolbar.setObjectName(u'CircleCraters')

        self.tool = QgsMapToolEmitPoint(self.canvas)
        self.tool.canvasClicked.connect(self.handle_click)
        self.tool.deactivated.connect(self.reset_clicks)
        self.clicks = []

        self.layer = None
        self.raster_layer = None

    # 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('CircleCraters', message)

    def show_error(self, message, title='Error', **kwargs):
        # QgsMessageBar.CRITICAL
        self.iface.messageBar().pushMessage(
            title, message, level=4, **kwargs)

    def show_info(self, message, **kwargs):
        # QgsMessageBar.INFO -> Qgis::Info
        self.iface.messageBar().pushMessage(
            message, level=3, **kwargs)

    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
    ):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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):  # noqa
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        self.start_action = self.add_action(
            ':/plugins/CircleCraters/icons/ic_layers_48px.svg',
            text=self.tr(u'Select Crater Counting Layer'),
            callback=self.show_layer_select,
            parent=self.iface.mainWindow(),
        )

        self.stop_action = self.add_action(
            ':/plugins/CircleCraters/icons/ic_layers_clear_48px.svg',
            text=self.tr(u'Stop Crater Counting'),
            enabled_flag=False,
            callback=self.stop_tool,
            parent=self.iface.mainWindow(),
        )

        self.circle_action = self.add_action(
            ':/plugins/CircleCraters/icons/ic_add_circle_outline_48px.svg',
            text=self.tr(u'Circle Craters'),
            enabled_flag=False,
            callback=self.set_tool,
            parent=self.iface.mainWindow(),
        )

        self.export_action = self.add_action(
            ':/plugins/CircleCraters/icons/ic_archive_48px.svg',
            text=self.tr(u'Export Data'),
            callback=self.show_export_dialog,
            parent=self.iface.mainWindow(),
        )

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Circle Craters'),
                action)
            self.iface.removeToolBarIcon(action)

    def reset_clicks(self):
        self.clicks = []

    def handle_click(self, point, button):
        #self.clicks.append(Point(point.x(), point.y()))
        x, y = point.x(), point.y()
        r = 16
        #if len(self.clicks) != 3:
        #    return

        self.draw_circle(DetectedCircle(self.raster_layer, x, y, r_in=r))
        #self.reset_clicks()

    def set_tool(self):
        """Run method that performs all the real work"""
        if not self.layer:
            error = 'No crater counting layer selected. Please choose a layer.'
            self.show_error(error)
        self.canvas.setMapTool(self.tool)

    def stop_tool(self):
        """Run method that deactivates the crater counting tool"""
        self.canvas.unsetMapTool(self.tool)
        self.stop_action.setEnabled(False)
        self.circle_action.setEnabled(False)
        self.layer = None

    def is_polygon_vector_layer(self, layer):
        if layer.type() != QgsMapLayer.VectorLayer:
            return False

        return layer.geometryType() == QgsWkbTypes.PolygonGeometry

    def is_raster_layer(self, layer):
        if layer.type() != QgsMapLayer.RasterLayer:
            return False
        else:
            return True

    def get_counting_layer_choices(self):
        root = QgsProject.instance().layerTreeRoot()
        layers = root.findLayers()
        return [layer.layer() for layer in layers if self.is_polygon_vector_layer(layer.layer())]

    def get_raster_layer_choices(self):
        root = QgsProject.instance().layerTreeRoot()
        layers = root.findLayers()
        return [layer.layer() for layer in layers if self.is_raster_layer(layer.layer())]

    def show_layer_select(self):
        """ Run method that lets users choose raster layer.
        Sets self.raster_layer
        """
        try:
            self.choose_counting_dlg.show(self.get_counting_layer_choices())
        except CircleCraterError as error:
            self.show_error(error.message)
        try:
            self.choose_raster_dlg.show(self.get_raster_layer_choices())
        except CircleCraterError as error:
            self.show_error(error.message)

    def on_counting_layer_select(self, layer):
        self.layer = layer
        self.set_field_attributes()

        msg = 'The layer "{!s}" is set as the crater counting layer'
        self.show_info(msg.format(layer.name()))

        self.stop_action.setEnabled(True)
        self.circle_action.setEnabled(True)
        self.set_tool()

    def on_raster_layer_select(self, layer):
        self.raster_layer = layer

        msg = 'The layer "{!s}" is set as the raster layer'
        self.show_info(msg.format(layer.name()))

        self.stop_action.setEnabled(True)
        self.circle_action.setEnabled(True)
        self.set_tool()

    def set_field_attributes(self):
        self.layer.startEditing()

        # fieldNameIndex has been renamed to lookupField. 
        if self.layer.fields().lookupField('diameter') == -1:
            field_attribute = QgsField('diameter', QVariant.Double)
            self.layer.dataProvider().addAttributes([field_attribute])

        if self.layer.fields().lookupField('center_lon') == -1:
            field_attribute = QgsField('center_lon', QVariant.Double)
            self.layer.dataProvider().addAttributes([field_attribute])

        if self.layer.fields().lookupField('center_lat') == -1:
            field_attribute = QgsField('center_lat', QVariant.Double)
            self.layer.dataProvider().addAttributes([field_attribute])

        self.layer.updateFields()
        self.layer.commitChanges()

    def show_export_dialog(self):
        """ Run method that exports data to a file"""
        try:
            self.export_dlg.show(self.get_layer_choices())
        except CircleCraterError as error:
            self.show_error(error.message)

    def export(self, crater_layer, area_layer, filename):
        try:
            self.write_diam_file(crater_layer, area_layer, filename)
        except CircleCraterError as error:
            self.show_error(error.message)

    def create_diam_header(self, total_area, crater_layer):
        current_datetime = str(datetime.datetime.now())
        # a,b = self.get_a_and_b(self.layer)
        da = self.get_distance_area(self.layer)
        if da.willUseEllipsoid():
            header = [
                '# Diam file for Craterstats',
                '# Date of measurement export = {}'.format(current_datetime),
                '',
                'Ellipsoid {}'.format(da.ellipsoid()),
                '',
                'layer CRS: {}'.format(crater_layer.crs().description()),
                '',
                'Total Crater Area <km^2> = {}'.format(total_area),
                '',
                '# diameter(m), lon, lat',
                '',
            ]
        else:
            header = [
                '# Diam file for Craterstats',
                '# Date of measurement export = {}'.format(current_datetime),
                '',
                '# Ellipsoid is not available, Area and Diameter unit may not right.',
                '',
                'Total Crater Area = {}'.format(total_area),
                '',
                '# diameter, lon, lat',
                '',
            ]
        return '\n'.join(header)

    def write_diam_file(self, crater_layer, area_layer, filename):
        """Method writes crater data to a special formatted file."""
        total_area = self.compute_area(area_layer)
        km_squared = self.convert_square_meters_to_km(total_area)

        header = self.create_diam_header(km_squared, crater_layer)
        nested_list = self.format_diam_data(crater_layer, area_layer)

        # tab delimited datafile
        with open(filename, 'w') as fp:
            fp.write(header)
            fp.writelines('\t'.join(i) + '\n' for i in nested_list)

    def get_distance_area(self, layer):
        destination = layer.crs()

        # Using the general purpose distance and area calculator, 
        # capable of performing ellipsoid based calculations.
        distance_area = QgsDistanceArea()
        c = QgsCoordinateTransformContext()
        distance_area.setSourceCrs(layer.crs(), c )
        ellips = destination.ellipsoidAcronym()
        if ellips == '' :
            ellips = QgsProject.instance().ellipsoid()
        distance_area.setEllipsoid(ellips)
        # sets whether coordinates must be projected to ellipsoid before measuring
        # distance_area.setEllipsoidalMode(True)

        return distance_area

    def convert_meters_to_km(self, meters):
        return meters * 0.001

    def convert_square_meters_to_km(self, square_meters):
        return square_meters * 1.0e-6

    def measure(self, layer, geometry):
        return self.get_distance_area(layer).measureLength(geometry)

    def get_actual_area(self, feature, distance_area, xform):
        # TODO: distance_area and xform should probably be class variables
        QgsMessageLog.logMessage("message", "name")
        print("======>",feature.geometry()) 

        if feature.geometry().isMultipart(): # new part for multipolylines
           points = feature.geometry().asMultiPolygon()
           print("multipart:",len(points))
           print("First point: ",points[0][0])
           for p in points[0][0]:
              print(p)
           points = points[0][0]
        else:
           points = feature.geometry().asPolygon()
           points = points[0]
 
        transformed = [self.transform_point(xform, point) for point in points]
        new_polygon = QgsGeometry.fromPolygonXY([transformed])
        actual_area = distance_area.measureArea(new_polygon)
        return actual_area

    def compute_area(self, layer):
        """Returns values are in meters resp. square meters
        http://qgis.org/api/2.8/classQgsDistanceArea.html
        use measure() takes QgsGeometry as a parameter and calculates distance
        or area
        """
        destination = layer.crs()
        source = layer.crs()
        xform = self.crs_transform(source, destination)
        distance_area = self.get_distance_area(layer)

        features = list(layer.getFeatures())
        return sum([self.get_actual_area(f, distance_area, xform) for f in features])

    def get_fields(self, feature, diameter, lon, lat):
        """Retrieves fields from the attribute table in the order required
        for .diam file: diameter, lon, lat
        And casts as strings"""
        # diameter is in units of km
        attributes = feature.attributes()
        # fraction is always 1
        fraction = 1
        # refer to an attribute by its index
        field_list = [
            str(self.convert_meters_to_km(attributes[diameter])),
            #str(1),
            # fraction was in old craterstats
            # str(fraction),
            str(attributes[lon]),
            str(attributes[lat])
            #str(1)
        ]
        return field_list

    def crater_center(self, crater, lat, lon):
        print(crater)
        print("ATT:",crater.attributes(),lat,lon,crater.attributes()[lon],crater.attributes()[lat] )
        center_point = QgsPointXY(
            float(crater.attributes()[lon]),
            float(crater.attributes()[lat]),
        )

        return QgsGeometry.fromPointXY(center_point)

    def experiment(self, feature_geom, point_geom):
        """
        feature and point are geometrys
        Is a QgsPoint within an arbitrary QgsPolygon?
        """
        polygon = feature_geom.asPolygon()
        point = point_geom.asPoint()

        codes = []
        codes.append(Path.MOVETO)

        for i in range(0, len(polygon[0]) - 2):
            codes.append(Path.LINETO)

        codes.append(Path.CLOSEPOLY)
        path = Path(polygon[0], codes)

        if path.contains_point(point):
            return True
        else:
            return False

    def intersects(self, crater, area_geometries, lat, lon):
        # This geometry is in units of degrees
        center_geometry = self.crater_center(crater, lat, lon)
        # temp = any(center_geometry.within(a) for a in area_geometries)
        return any(self.experiment(a, center_geometry) for a in area_geometries)

    def format_diam_data(self, crater_layer, area_layer):
        """Formats crater diameter data for export as .diam file
        Checks to see if craters intersect with area polygons in area layer
        """
        diameter = crater_layer.fields().indexFromName('diameter')
        lon = crater_layer.fields().indexFromName('center_lon')
        lat = crater_layer.fields().indexFromName('center_lat')

        craters = list(crater_layer.getFeatures())
        areas = list(area_layer.getFeatures())

        # TODO: distance_area and xform should probably be class variables
        destination = crater_layer.crs()
        source = area_layer.crs()
        xform = self.crs_transform(source, destination)
        distance_area = self.get_distance_area(area_layer)
        # Get area geometry in units of degrees
        new_geometries = [self.get_transformed_polygon(a, distance_area, xform) for a in areas]

        # WARNING INTERSECTS 
        craters = [c for c in craters if self.intersects(c, new_geometries, lat, lon)]
        print("CRATERS: ",craters)
        # Craterstats 2.0 line is:
        # crater = {diam, fraction, lon, lat, topo_scale_factor
        # 12.0185588932   1       159.43028979    16.9521753319   1
        return [self.get_fields(c, diameter, lon, lat) for c in craters]

    def get_transformed_polygon(self, feature, distance_area, xform):
        """Returns transformd polygon geometry"""
        # TODO: distance_area and xform should probably be class variables
        if feature.geometry().isMultipart(): # new part for multipolylines
           points = feature.geometry().asMultiPolygon()
           print("multipart:",len(points))
           print("First point: ",points[0][0])
           for p in points[0][0]:
              print(p)
           points = points[0][0]
        else:
           points = feature.geometry().asPolygon()
           points = points[0]

        transformed = [self.transform_point(xform, point) for point in points]
        print("TRANSFORMED->",transformed)
        return QgsGeometry.fromPolygonXY( [transformed] )

    def crs_transform(self, source, destination):
        print(source, destination, QgsProject.instance()  )
        return QgsCoordinateTransform(source, destination, QgsProject.instance())

    def transform_point(self, xform, point):
        return xform.transform(point)

    def get_destination_crs(self):
        # moon = '+proj=longlat +a=1737400 +b=1737400 +no_defs'
        # destination = QgsCoordinateReferenceSystem()
        # destination.createFromProj4(moon)
        destination = self.layer.crs()
        return destination

    def get_latlong_srs(self):
        p = QgsProject.instance()
        e = p.ellipsoid()
        crs = p.crs()
        srs = osr.SpatialReference()
        srs.ImportFromProj4(crs.toProj4())
        a = srs.GetSemiMajor()
        b = srs.GetSemiMinor()
        proj4 = "+proj=latlong +a={} +b={}".format(a,b)
        srs_ll = osr.SpatialReference()
        srs_ll.ImportFromProj4(proj4)
        return srs_ll

    def get_srs(self):
        p = QgsProject.instance()
        e = p.ellipsoid()
        crs = p.crs()
        srs = osr.SpatialReference()
        srs.ImportFromProj4(crs.toProj4())
        return srs

    def get_a_and_b(self,layer):
        #this_crs = layer.crs()
        #wkt = this_crs.toWkt()
        #srs = osr.SpatialReference()
        #srs.importFromWkt(wkt)
        #print(srs)
        #print(dir(this_crs))
        p = QgsProject.instance()
        e = p.ellipsoid()
        crs = p.crs()
        srs = osr.SpatialReference()
        srs.ImportFromProj4(crs.toProj4())
        print("******",e)
        da = QgsDistanceArea()  
        da.willUseEllipsoid() # should be true
        a = srs.GetSemiMajor()
        b = srs.GetSemiMinor()
        return a,b

    def draw_circle(self, circle):
        polygon = [QgsPointXY(*point) for point in circle.to_polygon()]
        print(circle)
        print(polygon)
        print(type(polygon))

        #gPnt = QgsGeometry.fromPointXY(QgsPointXY(1,1))
        #gLine = QgsGeometry.fromPolyline([QgsPoint(1, 1), QgsPoint(2, 2)])
        #gPolygon = QgsGeometry.fromPolygonXY([[QgsPointXY(1, 1), QgsPointXY(2, 2), QgsPointXY(2, 1)]])

        #geometry = QgsGeometry.fromPolygon([polygon])
        geometry = QgsGeometry.fromPolygonXY([polygon])

        feature = QgsFeature()
        feature.setGeometry(geometry)
        feature.setFields(self.layer.fields())

        destination = self.layer.crs()
        source = self.layer.crs()
        xform = self.crs_transform(source, destination)

        #print circle.center.x, circle.center.y
        #print(circle.center.x, circle.center.y)

        #line = [
        #    QgsPointXY(circle.center.x, circle.center.y),
        #    QgsPointXY(circle.center.x + circle.radius, circle.center.y),
        #]

        line = [
            QgsPointXY(circle.a, circle.b),
            QgsPointXY(circle.a + circle.r, circle.b),
        ]

        transformed = [
            self.transform_point(xform, line[0]),
            self.transform_point(xform, line[1]),
        ]

        print("****",transformed)

        #new_line_geometry = QgsGeometry.fromPolyline( [ QgsGeometry.fromPointXY(transformed[0]), QgsGeometry.fromPointXY(transformed[1]) ]  )
        new_line_geometry = QgsGeometry.fromPolyline([QgsPoint(transformed[0][0], transformed[0][1]), QgsPoint(transformed[1][0], transformed[1][1])])

        distance_area = self.get_distance_area(self.layer)
        actual_line_distance = distance_area.measureLength(new_line_geometry)
        
        # Translate circle center to units of degrees
        center_in_degrees = xform.transform(circle.a, circle.b)

        # circle_feature.id() is NULL for .shp file
        # and assigned automaticly for .gpkg
        # order is id, diameter, lon, lat
        feature.setAttribute('diameter',circle.diameter)
        feature.setAttribute('center_lon',circle.a)
        feature.setAttribute('center_lat',circle.b)

        self.layer.startEditing()
        self.layer.dataProvider().addFeatures([feature])
        #self.layer.addFeature(feature, True)
        self.layer.commitChanges()

        # update layer's extent when new features have been added
        # because change of extent in provider is not propagated to the layer
        self.layer.updateExtents()
Пример #43
0
class geradorDeReleatorioIbram:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'geradorDeReleatorioIbram_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Gerador de Relatório - Ibram')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('geradorDeReleatorioIbram', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/gerador_relatório/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u''),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True
        self.dlg = geradorDeReleatorioIbramDialog()
        self.dlg.poligonal.clear()#adicionado por mim
        self.dlg.pushButton.clicked.connect(self.selecionar_poligono) #adicionado por mim


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Gerador de Relatório - Ibram'),
                action)
            self.iface.removeToolBarIcon(action)

    
    def selecionar_poligono(self):
        """ Função para obter o caminho onde será salvo o shapefile""" 
        poligonoCaminho = QFileDialog.getOpenFileName(self.dlg, "Selecionar Arquivo: ", "", "*.shp")
        self.dlg.poligonal.setText(poligonoCaminho[0])

    def run(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.dlg = geradorDeReleatorioIbramDialog()
            #self.dlg.poligonal.clear()#adicionado por mim """Teste""""
            #self.dlg.pushButton.clicked.connect(self.selecionar_poligono) #adicionado por mim """Teste""""



        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            localSalvo = self.dlg.poligonal.text() """Local onde será salvo o endereço da poligonal (ADA)"""

            buffers = [1, 2, 3, 5, 10] #Criei um vetor para armazenar o valor dos buffers selecionados. A variavel foi iniciada com um valor (1) para a possível produção de mapas, podendo ser alterada a qualquer momento  
 
            ## Condições para os checkboxs criados
            ## Verificando se todos estão marcados
            if not self.dlg.buffer2km.isChecked():
                buffers.remove(2)
            break
            if not self.dlg.buffer3km.isChecked():
                buffers.remove(3)
            break
            if not self.dlg.buffer5km.isChecked():
                buffers.remove(5)
            break
            if not self.dlg.buffer10km.isChecked():
                buffers.remove(10)
            break




               """print pnt_selection[0] + " esta na " + bh_selection[0]
             elif not self.dlg.checkBoxBH.isChecked():
               print u"O item Bacias Hidrográficas não foi selecionado."
             
            ## Segunda condição para avaliar se o ponto cai em alguma região de planejamento
             if self.dlg.checkBoxRP.isChecked():
               rp_rioPath = "C:/Users/ferna/Desktop/municipiosRJ/limite_RP_SIRGAS.shp" # Não esqueça de corrigir esse caminho no seu computador
               rp_rioLayer = QgsVectorLayer(rp_rioPath, "RP RJ", "ogr")
               for w in pnt_layer.getFeatures():
                 for s in rp_rioLayer.getFeatures():
                   if s.geometry().intersects(w.geometry()):
                     ## Número três foi usado pois o nome da região esta na quarta coluna (python começa a contar do zero)
                     rp_selection.append(s.attributes()[3])
                     pnt_selection.append(w.attributes()[0])
                     break
               print pnt_selection[0] + u" esta na região de " + rp_selection[0]
             elif not self.dlg.checkBoxRP.isChecked():
               print u"O item Região de Planejamento não foi selecionado."""
            
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Пример #44
0
class QgisSkimageMethods:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'QgisSkimageMethod{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Qgis Skimage Method')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None
        self.tm = QgsApplication.taskManager()

    # 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('Qgis Skimage Method', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToRasterMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        dir_path = os.path.dirname(os.path.realpath(__file__))
        icon_path = dir_path + "/icon.png"
        self.add_action(icon_path,
                        text=self.tr(u'get Module Functions'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        # try:
        #     file_path = self.dlg.OutputFile.text()
        #     file_name = self.get_save_file_name()
        # except:
        #     pass
        for action in self.actions:
            self.iface.removePluginRasterMenu(self.tr(u'&Qgis Skimage Method'),
                                              action)
            self.iface.removeToolBarIcon(action)

        # Method 1
        # iface.addRasterLayer(file_path, file_name)

        # Method 2
        # rlayer = QgsRasterLayer(file_path, file_name)
        # QgsProject.instance().addMapLayer(rlayer)

    def completed(self, exception, result=None):

        if exception is None:
            if result is None:
                QMessageBox.information(None, "Warning", str(exception))
            else:
                if self.dlg.checkBox.isChecked():
                    QMessageBox.information(None, "Completed",
                                            'Image processing completed')
                    self.iface.addRasterLayer(
                        result, "Result")  # TODO Fix add raster layer
        else:
            QMessageBox.warning(None, "Error", "{}".format(exception))
            raise exception

    def stopped(self, task):
        QgsMessageLog.logMessage(
            'Task "{name}" was canceled'.format(name=task.description()),
            "Wasting time", Qgis.Info)

    # Updates the method list for the chosen module
    def update_function_list(self):
        self.dlg.AvailableFunctionsBox.clear()

        # Reads file that has all the methods
        dir_path = os.path.dirname(os.path.realpath(__file__))
        method_file = open(dir_path + "\method_list.txt", "r")

        # Reads the chosen module
        chosen_method = "Filter"
        if (self.dlg.ModuleBox.currentIndex == 0):
            chosen_method = "Filter"
        elif (self.dlg.ModuleBox.currentIndex() == 1):
            chosen_method = "Exposure"
        elif (self.dlg.ModuleBox.currentIndex() == 2):
            chosen_method = "Segmentation"

        # Reads all the methods for the user chosen module
        allmethods = []
        methodFound = False
        for line in method_file:
            if (methodFound):
                if (line == "\n"):
                    break
                allmethods.append(line)
            if (line == chosen_method + "\n"):
                methodFound = True

        method_file.close()
        result_methods = []
        for x in range(len(allmethods)):
            allmethods[x] = allmethods[x].replace('\n', '')
            if (allmethods[x] != chosen_method):
                result_methods.append(allmethods[x])

        self.dlg.AvailableFunctionsBox.addItems(result_methods)

    def update_info_box(self):
        self.dlg.InfoBox.clear()
        method_doc = ""
        chosenMethod = self.dlg.AvailableFunctionsBox.currentText()
        try:
            if (self.dlg.ModuleBox.currentIndex() == 0):
                method_doc = inspect.getdoc(getattr(filters, chosenMethod))
            elif (self.dlg.ModuleBox.currentIndex() == 1):
                method_doc = inspect.getdoc(getattr(exposure, chosenMethod))
            elif (self.dlg.ModuleBox.currentIndex() == 2):
                method_doc = inspect.getdoc(getattr(segmentation,
                                                    chosenMethod))
        except AttributeError:
            pass

        parameter_line = False
        for line in method_doc.splitlines():
            if (line == "Parameters"):
                parameter_line = True
            if (line == "Returns"):
                parameter_line = False
            if (parameter_line):
                self.dlg.InfoBox.addItem(line)

    def get_arguments_for_method(self):
        # Gets the chosen method
        chosenMethod = self.dlg.AvailableFunctionsBox.currentText()
        method_info = ""
        try:
            if (self.dlg.ModuleBox.currentIndex() == 0):
                method_info = inspect.getfullargspec(
                    getattr(filters, chosenMethod))
            elif (self.dlg.ModuleBox.currentIndex() == 1):
                method_info = inspect.getfullargspec(
                    getattr(exposure, chosenMethod))
            elif (self.dlg.ModuleBox.currentIndex() == 2):
                method_info = inspect.getfullargspec(
                    getattr(segmentation, chosenMethod))

        except TypeError:
            self.dlg.Parameters.setText("No arguments for chosen function")
        except AttributeError:
            pass
        # Gets the parameters for method
        return method_info

    # Updates the parameters for the chosen method
    def update_parameters(self):
        method_info = self.get_arguments_for_method()
        try:
            methodArguments = method_info.args
            # Prints out the parameters in the LineEdit window
            methodArgumentsString = "= , "
            self.dlg.Parameters.setText(
                methodArgumentsString.join(methodArguments) + "= ")
        except AttributeError:
            pass

    def select_output_file(self):
        filename, _filter = QFileDialog.getSaveFileName(
            self.dlg, "Select output file ", "", "*.tif")
        self.dlg.OutputFile.setText(filename)

    def method_function_call_helper(self, methodCalled, parameterList,
                                    imageArgument):
        # if (methodCalled == "median"):
        #     return my_median(imageArgument, parameterList)
        if (methodCalled == "slic"):
            return my_slic(imageArgument, parameterList)
        elif (methodCalled == "gaussian"):
            return my_gaussian(imageArgument, parameterList)
        elif (methodCalled == "sobel"):
            return my_sobel(imageArgument, parameterList)
        elif (methodCalled == "sobel_h"):
            return my_sobel_h(imageArgument, parameterList)
        elif (methodCalled == "sobel_v"):
            return my_sobel_v(imageArgument, parameterList)
        elif (methodCalled == "threshold_local"):
            return my_threshold_local(imageArgument, parameterList)
        elif (methodCalled == "threshold_otsu"):
            return my_threshold_otsu(imageArgument, parameterList)
        elif (methodCalled == "unsharp_mask"):
            return my_unsharp_mask(imageArgument, parameterList)
        elif (methodCalled == "quickshift"):
            return my_quickshift(imageArgument, parameterList)
        elif (methodCalled == "find_boundaries"):
            return my_find_boundaries(imageArgument, parameterList)
        elif (methodCalled == "chan_vese"):
            return my_chan_vese(imageArgument, parameterList)
        elif (methodCalled == "felzenszwalb"):
            return my_felzenszwalb(imageArgument, parameterList)
        elif (methodCalled == "inverse_gaussian_gradient"):
            return my_inverse_gaussian_gradient(imageArgument, parameterList)
        elif (methodCalled == "prewitt"):
            return my_prewitt(imageArgument, parameterList)
        elif (methodCalled == "prewitt_h"):
            return my_prewitt_h(imageArgument, parameterList)
        elif (methodCalled == "prewitt_v"):
            return my_prewitt_v(imageArgument, parameterList)
        elif (methodCalled == "adjust_gamma"):
            return my_adjust_gamma(imageArgument, parameterList)
        elif (methodCalled == "adjust_log"):
            return my_adjust_log(imageArgument, parameterList)
        elif (methodCalled == "adjust_sigmoid"):
            return my_adjust_sigmoid(imageArgument, parameterList)
        elif (methodCalled == "equalize_hist"):
            return my_equalize_hist(imageArgument, parameterList)
        elif (methodCalled == "laplace"):
            return my_laplace(imageArgument, parameterList)

    # Does stuff with the image
    def method_function_call(self, imageArgument):
        methodChosen = self.dlg.AvailableFunctionsBox.currentText()

        # Takes the user parameters
        parameterString = self.dlg.Parameters.text()

        # Gets the list of methods parameter names and their default values
        parameter_list = self.get_parameter_list()
        parameter_names = get_list_of_names(parameterString)
        parameter_values = get_list_of_values(parameterString)
        parameter_list = set_parameter_values(parameter_list, parameter_names,
                                              parameter_values)

        return self.method_function_call_helper(methodChosen, parameter_list,
                                                imageArgument)

    def get_save_file_name(self):
        saveString = self.dlg.OutputFile.text()
        fullFileName = re.findall("(\w+[.]\w+)", saveString)
        file_name = ""
        for i in range(len(fullFileName)):
            if (fullFileName[i] != '.'):
                file_name += fullFileName[i]
            elif (fullFileName[i] == '.'):
                return file_name

    def get_parameter_list(self):
        method_info = self.get_arguments_for_method()
        argument_names = method_info.args
        default_values = method_info.defaults
        arg_val_size_diff = len(argument_names) - len(default_values)
        parameter_list = []

        for x in range(len(argument_names)):
            parameter_list.append([])
            parameter_list[x].append(argument_names[x])

        for x in range(len(default_values)):
            parameter_list[x + arg_val_size_diff].append(default_values[x])

        return parameter_list

    def user_manual_window(self):
        self.user_manual.show()
        # Reads user manual txt and outputs all the information to user info
        dir_path = os.path.dirname(os.path.realpath(__file__))
        user_manual_info = open(dir_path + "\manual.txt", "r")

        for line in user_manual_info:
            self.user_manual.userInfo.addItem(line)

        self.user_manual.closeButton.clicked.connect(self.close_user_manual)

    def close_user_manual(self):
        self.user_manual.close()

    def image_processing(self, task, wait_time):
        file_name = self.dlg.OutputFile.text()

        # Reads the path of the chosen Raster layer/Image
        layers = QgsProject.instance().mapLayersByName(
            self.dlg.RasterLayerBox.currentText())
        layer_path = layers[0].dataProvider().dataSourceUri()
        im = imread(layer_path)
        gdalIm = gdal.Open(layer_path)

        # The path where the user wants to save the image

        x_pixels = im.shape[1]
        y_pixels = im.shape[0]
        driver = gdal.GetDriverByName('GTiff')
        ## TODO Make it so its possible to pass a grayscale image
        if (self.dlg.AvailableFunctionsBox.currentText() == "slic"
                or self.dlg.AvailableFunctionsBox.currentText() == "chan_vese"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "felzenszwalb"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "inverse_gaussian_gradient"
                or self.dlg.AvailableFunctionsBox.currentText() == "prewitt"
                or self.dlg.AvailableFunctionsBox.currentText() == "prewitt_h"
                or self.dlg.AvailableFunctionsBox.currentText() == "prewitt_v"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "threshold_otsu"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "threshold_local"):
            im = imread(layer_path, as_gray=True)
            dataset = driver.Create(file_name, x_pixels, y_pixels, 1,
                                    gdal.GDT_Int32)

            resultArray = self.method_function_call(im)
            if (type(resultArray) == str):
                raise Exception(resultArray)
            dataset.GetRasterBand(1).WriteArray(resultArray)

        if (self.dlg.AvailableFunctionsBox.currentText() == "median"
                or self.dlg.AvailableFunctionsBox.currentText() == "laplace"
                or self.dlg.AvailableFunctionsBox.currentText() == "gaussian"
                or self.dlg.AvailableFunctionsBox.currentText() == "sobel"
                or self.dlg.AvailableFunctionsBox.currentText() == "sobel_h"
                or self.dlg.AvailableFunctionsBox.currentText() == "sobel_v" or
                self.dlg.AvailableFunctionsBox.currentText() == "unsharp_mask"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "clear_border"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "find_boundaries" or
                self.dlg.AvailableFunctionsBox.currentText() == "adjust_gamma"
                or self.dlg.AvailableFunctionsBox.currentText() == "adjust_log"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "adjust_sigmoid"
                or self.dlg.AvailableFunctionsBox.currentText()
                == "equalize_hist"):
            if (im.ndim == 3):
                dataset = driver.Create(file_name, x_pixels, y_pixels, 3,
                                        gdal.GDT_Int32)

                resultArray_r = self.method_function_call(im[:, :, 0])
                resultArray_g = self.method_function_call(im[:, :, 1])
                resultArray_b = self.method_function_call(im[:, :, 2])

                if (type(resultArray_r) == str or type(resultArray_g) == str
                        or type(resultArray_b) == str):
                    raise Exception(resultArray_r)

                dataset.GetRasterBand(1).WriteArray(resultArray_r)
                dataset.GetRasterBand(2).WriteArray(resultArray_g)
                dataset.GetRasterBand(3).WriteArray(resultArray_b)
            else:
                dataset = driver.Create(file_name, x_pixels, y_pixels, 1,
                                        gdal.GDT_Int32)
                resultArray = self.method_function_call(im)
                dataset.GetRasterBand(1).WriteArray(resultArray)

        if (self.dlg.AvailableFunctionsBox.currentText() == "quickshift"):
            dataset = driver.Create(file_name, x_pixels, y_pixels, 1,
                                    gdal.GDT_Int32)

            resultArray = self.method_function_call(im)
            if (type(resultArray) == str):
                raise Exception(resultArray)
            dataset.GetRasterBand(1).WriteArray(resultArray)

        proj = gdalIm.GetProjection()

        # If the chosen layer has a projection then add that, to the processed image
        if proj != "":
            geotrans = gdalIm.GetGeoTransform()
            dataset.SetProjection(proj)
            dataset.SetGeoTransform(geotrans)
        dataset.FlushCache()

        if (task.isCanceled):
            self.stopped(task)
            return file_name

    def run(self):
        """Run method that performs all the real work"""

        # List of options for modules
        modules = ["filters", "exposure", "segmentation"]
        # 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.dlg = getMedianFunctionsDialog()
            self.user_manual = userManualDialog()

            self.dlg.ModuleBox.currentIndexChanged.connect(
                self.update_function_list)
            self.dlg.pushButton.clicked.connect(self.select_output_file)
            self.dlg.AvailableFunctionsBox.currentIndexChanged.connect(
                self.update_parameters)
            self.dlg.AvailableFunctionsBox.currentIndexChanged.connect(
                self.update_info_box)
            self.dlg.UserManualButton.clicked.connect(self.user_manual_window)

        # Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children()

        # Clear the contents of the comboBoxes from previous runs
        self.dlg.RasterLayerBox.clear()
        self.dlg.ModuleBox.clear()
        self.dlg.AvailableFunctionsBox.clear()
        self.dlg.OutputFile.clear()

        # Populate the comboBox with names of all the loaded layers
        self.dlg.RasterLayerBox.addItems([layer.name() for layer in layers])

        # Clears and fills the Module box with options available for user
        self.dlg.ModuleBox.addItems(modules)
        self.update_function_list()
        self.update_info_box()
        self.update_parameters()

        # show the dialog
        self.dlg.show()

        # Run the dialog event loop
        result = self.dlg.exec_()

        # See if OK was pressed
        if result:
            task = QgsTask.fromFunction("Image processing",
                                        self.image_processing,
                                        on_finished=self.completed,
                                        wait_time=3)
            self.tm.addTask(task)
Пример #45
0
class PlanetExplorer(object):
    def __init__(self, iface):

        self.iface = iface

        # Initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # Initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        locale_path = os.path.join(
            self.plugin_dir, "i18n", "{0}Plugin_{1}.qm".format(PE, locale)
        )

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr("&{0}".format(P_E))
        self.toolbar = None

        # noinspection PyTypeChecker
        self.explorer_dock_widget = None
        self._terms_browser = None

        if is_segments_write_key_valid():
            analytics.write_key = segments_write_key()
        if is_sentry_dsn_valid():
            try:
                sentry_sdk.init(sentry_dsn(), release=plugin_version(True))
                sentry_sdk.set_context(
                    "qgis",
                    {
                        "type": "runtime",
                        "name": Qgis.QGIS_RELEASE_NAME,
                        "version": Qgis.QGIS_VERSION,
                    },
                )
                system = platform.system()
                if system == "Darwin":
                    sentry_sdk.set_context(
                        "mac",
                        {
                            "type": "os",
                            "name": "macOS",
                            "version": platform.mac_ver()[0],
                            "kernel_version": platform.uname().release,
                        },
                    )
                if system == "Linux":
                    sentry_sdk.set_context(
                        "linux",
                        {
                            "type": "os",
                            "name": "Linux",
                            "version": platform.release(),
                            "build": platform.version(),
                        },
                    )
                if system == "Windows":
                    sentry_sdk.set_context(
                        "windows",
                        {
                            "type": "os",
                            "name": "Windows",
                            "version": platform.version(),
                        },
                    )
            except Exception:
                QMessageBox.warning(
                    self.iface.mainWindow(),
                    "Error",
                    "Error initializing Planet Explorer.\n"
                    "Please restart QGIS to load updated libraries.",
                )

        self.qgis_hook = sys.excepthook

        def plugin_hook(t, value, tb):
            trace = "".join(traceback.format_exception(t, value, tb))
            if PLUGIN_NAMESPACE in trace.lower():
                s = ""
                if issubclass(t, exceptions.Timeout):
                    s = "Connection to Planet server timed out."
                elif issubclass(t, exceptions.ConnectionError):
                    s = (
                        "Connection error.\n Verify that your computer is correctly"
                        " connected to the Internet"
                    )
                elif issubclass(t, (exceptions.ProxyError, exceptions.InvalidProxyURL)):
                    s = (
                        "ProxyError.\n Verify that your proxy is correctly configured"
                        " in the QGIS settings"
                    )
                elif issubclass(t, planet.api.exceptions.ServerError):
                    s = "Server Error.\n Please, try again later"
                elif issubclass(t, urllib3.exceptions.ProxySchemeUnknown):
                    s = (
                        "Proxy Error\n Proxy URL must start with 'http://' or"
                        " 'https://'"
                    )

                if s:
                    QMessageBox.warning(self.iface.mainWindow(), "Error", s)
                else:
                    try:
                        sentry_sdk.capture_exception(value)
                    except Exception:
                        pass  # we swallow all exceptions here, to avoid entering an endless loop
                    self.qgis_hook(t, value, tb)
            else:
                self.qgis_hook(t, value, tb)

        sys.excepthook = plugin_hook

    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(PE, 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,
    ):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToWebMenu(self.menu, action)

        self.actions.append(action)

        return action

    # noinspection PyPep8Naming
    def initGui(self):

        self.toolbar = self.iface.addToolBar(P_E)
        self.toolbar.setObjectName(P_E)

        self.showdailyimages_act = self.add_action(
            os.path.join(plugin_path, "resources", "search.svg"),
            text=self.tr(P_E),
            callback=toggle_images_search,
            add_to_menu=True,
            add_to_toolbar=True,
            parent=self.iface.mainWindow(),
        )

        self.showbasemaps_act = self.add_action(
            os.path.join(plugin_path, "resources", "basemap.svg"),
            text=self.tr("Show Basemaps Search"),
            callback=toggle_mosaics_search,
            add_to_menu=True,
            add_to_toolbar=True,
            parent=self.iface.mainWindow(),
        )

        self.showinspector_act = self.add_action(
            os.path.join(plugin_path, "resources", "inspector.svg"),
            text=self.tr("Show Planet Inspector..."),
            callback=toggle_inspector,
            add_to_menu=False,
            add_to_toolbar=True,
            parent=self.iface.mainWindow(),
        )

        self.showtasking_act = self.add_action(
            os.path.join(plugin_path, "resources", "tasking.svg"),
            text=self.tr("Show Tasking..."),
            callback=toggle_tasking_widget,
            add_to_menu=False,
            add_to_toolbar=True,
            parent=self.iface.mainWindow(),
        )

        self.add_central_toolbar_button()

        self.showorders_act = self.add_action(
            os.path.join(plugin_path, "resources", "orders.svg"),
            text=self.tr("Show Orders Monitor..."),
            callback=toggle_orders_monitor,
            add_to_menu=False,
            add_to_toolbar=True,
            parent=self.iface.mainWindow(),
        )

        self.add_user_button()
        self.add_info_button()

        self.settings_act = self.add_action(
            os.path.join(plugin_path, "resources", "cog.svg"),
            text=self.tr("Settings..."),
            callback=self.show_settings,
            add_to_menu=True,
            add_to_toolbar=False,
            parent=self.iface.mainWindow(),
        )

        self.provider = BasemapLayerWidgetProvider()
        QgsGui.layerTreeEmbeddedWidgetRegistry().addProvider(self.provider)

        QgsProject.instance().projectSaved.connect(self.project_saved)
        QgsProject.instance().layersAdded.connect(self.layers_added)
        QgsProject.instance().layerRemoved.connect(self.layer_removed)

        PlanetClient.getInstance().loginChanged.connect(self.login_changed)

        self.enable_buttons(False)

    def add_central_toolbar_button(self):
        widget = QWidget()
        widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        layout = QHBoxLayout()
        layout.addStretch()
        self.btnLogin = QPushButton()
        palette = self.btnLogin.palette()
        palette.setColor(QPalette.Button, PLANET_COLOR)
        self.btnLogin.setPalette(palette)
        self.btnLogin.setText("Log in")
        # self.btnLogin.setAutoRaise(True)
        self.btnLogin.setAttribute(Qt.WA_TranslucentBackground)
        self.btnLogin.clicked.connect(self.btn_login_clicked)
        icon = QIcon(os.path.join(plugin_path, "resources", "planet-logo-p.svg"))
        labelIcon = QLabel()
        labelIcon.setPixmap(icon.pixmap(QSize(16, 16)))
        layout.addWidget(labelIcon)
        self.labelLoggedIn = QLabel()
        self.labelLoggedIn.setText("")
        layout.addWidget(self.labelLoggedIn)
        layout.addWidget(self.btnLogin)
        layout.addStretch()
        widget.setLayout(layout)
        self.toolbar.addWidget(widget)

    def btn_login_clicked(self):
        if PlanetClient.getInstance().has_api_key():
            self.logout()
        else:
            self.login()

    def layer_removed(self, layer):
        self.provider.layerWasRemoved(layer)

    def layers_added(self, layers):
        for layer in layers:
            add_widget_to_layer(layer)

    def login_changed(self, loggedin):
        self.provider.updateLayerWidgets()
        self.enable_buttons(loggedin)
        if not loggedin:
            hide_orders_monitor()
            hide_inspector()

    def add_info_button(self):
        info_menu = QMenu()

        add_menu_section_action("Planet", info_menu)

        p_com_act = QAction(QIcon(EXT_LINK), "planet.com", info_menu)
        p_com_act.triggered[bool].connect(lambda: open_link_with_browser(PLANET_COM))
        info_menu.addAction(p_com_act)

        p_explorer_act = QAction(QIcon(EXT_LINK), "Planet Explorer web app", info_menu)
        p_explorer_act.triggered[bool].connect(
            lambda: open_link_with_browser(PLANET_EXPLORER)
        )
        info_menu.addAction(p_explorer_act)

        p_sat_act = QAction(QIcon(EXT_LINK), "Satellite specs PDF", info_menu)
        p_sat_act.triggered[bool].connect(lambda: open_link_with_browser(SAT_SPECS_PDF))
        info_menu.addAction(p_sat_act)

        p_support_act = QAction(QIcon(EXT_LINK), "Support Community", info_menu)
        p_support_act.triggered[bool].connect(
            lambda: open_link_with_browser(PLANET_SUPPORT_COMMUNITY)
        )
        info_menu.addAction(p_support_act)

        p_whatsnew_act = QAction(QIcon(EXT_LINK), "What's new", info_menu)
        p_whatsnew_act.triggered[bool].connect(
            lambda: open_link_with_browser(PLANET_INTEGRATIONS)
        )
        info_menu.addAction(p_whatsnew_act)

        p_sales_act = QAction(QIcon(EXT_LINK), "Sales", info_menu)
        p_sales_act.triggered[bool].connect(
            lambda: open_link_with_browser(PLANET_SALES)
        )
        info_menu.addAction(p_sales_act)

        add_menu_section_action("Documentation", info_menu)

        terms_act = QAction("Terms", info_menu)
        terms_act.triggered[bool].connect(self.show_terms)
        info_menu.addAction(terms_act)

        btn = QToolButton()
        btn.setIcon(
            QIcon(
                os.path.join(plugin_path, "resources", "info.svg"),
            )
        )
        btn.setMenu(info_menu)

        btn.setPopupMode(QToolButton.MenuButtonPopup)
        # Also show menu on click, to keep disclosure triangle visible
        btn.clicked.connect(btn.showMenu)

        self.toolbar.addWidget(btn)

    def add_user_button(self):
        user_menu = QMenu()

        self.acct_act = QAction(QIcon(EXT_LINK), "Account", user_menu)
        self.acct_act.triggered[bool].connect(
            lambda: QDesktopServices.openUrl(QUrl(ACCOUNT_URL))
        )
        user_menu.addAction(self.acct_act)

        self.logout_act = QAction("Logout", user_menu)
        self.logout_act.triggered[bool].connect(self.logout)
        user_menu.addAction(self.logout_act)

        self.user_button = QToolButton()
        self.user_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.user_button.setIcon(
            QIcon(
                os.path.join(plugin_path, "resources", "account.svg"),
            )
        )
        self.user_button.setMenu(user_menu)

        self.user_button.setPopupMode(QToolButton.MenuButtonPopup)
        # Also show menu on click, to keep disclosure triangle visible
        self.user_button.clicked.connect(self.user_button.showMenu)

        self.toolbar.addWidget(self.user_button)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        PlanetClient.getInstance().log_out()
        self.provider.updateLayerWidgets()

        for action in self.actions:
            self.iface.removePluginWebMenu(self.tr("&{0}".format(P_E)), action)
            self.iface.removeToolBarIcon(action)

        # remove the toolbar
        if self.toolbar is not None:
            del self.toolbar

        remove_inspector()
        remove_explorer()
        remove_orders_monitor()
        remove_tasking_widget()

        QgsGui.layerTreeEmbeddedWidgetRegistry().removeProvider(self.provider.id())

        sys.excepthook = self.qgis_hook

        QgsProject.instance().projectSaved.disconnect(self.project_saved)
        QgsProject.instance().layersAdded.disconnect(self.layers_added)
        QgsProject.instance().layerRemoved.disconnect(self.layer_removed)

    # -----------------------------------------------------------

    def show_settings(self):
        dlg = SettingsDialog()
        dlg.exec()

    def show_terms(self, _):
        if self._terms_browser is None:
            self._terms_browser = QTextBrowser()
            self._terms_browser.setReadOnly(True)
            self._terms_browser.setOpenExternalLinks(True)
            self._terms_browser.setMinimumSize(600, 700)
            # TODO: Template terms.html first section, per subscription level
            #       Collect subscription info from self.p_client.user
            self._terms_browser.setSource(
                QUrl("qrc:/plugins/planet_explorer/terms.html")
            )
            self._terms_browser.setWindowModality(Qt.ApplicationModal)
        self._terms_browser.show()

    def login(self):
        if Qgis.QGIS_VERSION_INT >= 32000 and platform.system() == "Darwin":
            text = (
                "WARNING: Your configuration may encounter serious issues with the"
                " Planet QGIS Plugin using QGIS V3.20. We are actively troubleshooting"
                " the issue with the QGIS team, you can track <a"
                " href='https://github.com/qgis/QGIS/issues/44182'>Issue 44182"
                " here</a>. In the meantime, we recommend that you use a QGIS version"
                " between 3.10 and 3.20, such as the 3.16 long term stable release. For"
                " further information including instructions on how to downgrade QGIS,"
                " please refer to our <a"
                " href='https://support.planet.com/hc/en-us/articles/4404372169233'>support"
                " page here</a>."
            )
            QMessageBox.warning(self.iface.mainWindow(), "Planet Explorer", text)
        show_explorer()

    def logout(self):
        PlanetClient.getInstance().log_out()

    def enable_buttons(self, loggedin):
        self.btnLogin.setVisible(not loggedin)
        labelText = "<b>Welcome to Planet</b>" if not loggedin else "<b>Planet</b>"
        self.labelLoggedIn.setText(labelText)
        self.showdailyimages_act.setEnabled(loggedin)
        self.showbasemaps_act.setEnabled(loggedin)
        self.showinspector_act.setEnabled(loggedin)
        self.showorders_act.setEnabled(loggedin)
        self.showtasking_act.setEnabled(loggedin)
        self.user_button.setEnabled(loggedin)
        self.user_button.setText(
            PlanetClient.getInstance().user()["user_name"] if loggedin else ""
        )
        if loggedin:
            self.showdailyimages_act.setToolTip(
                "Show / Hide the Planet Imagery Search Panel"
            )
            self.showbasemaps_act.setToolTip(
                "Show / Hide the Planet Basemaps Search Panel"
            )
            self.showorders_act.setToolTip("Show / Hide the Order Status Panel")
            self.showinspector_act.setToolTip("Show / Hide the Planet Inspector Panel")
            self.showtasking_act.setToolTip("Show / Hide the Tasking Panel")
        else:
            self.showdailyimages_act.setToolTip("Login to access Imagery Search")
            self.showbasemaps_act.setToolTip("Login to access Basemaps Search")
            self.showorders_act.setToolTip("Login to access Order Status")
            self.showinspector_act.setToolTip("Login to access Planet Inspector")
            self.showtasking_act.setToolTip("Login to access Tasking Panel")

    def project_saved(self):
        if PlanetClient.getInstance().has_api_key():

            def resave():
                try:
                    path = QgsProject.instance().absoluteFilePath()
                    if path.lower().endswith(".qgs"):
                        with open(path, encoding="utf-8") as f:
                            s = f.read()
                        with open(path, "w", encoding="utf-8") as f:
                            f.write(s.replace(PlanetClient.getInstance().api_key(), ""))
                    else:
                        tmpfilename = path + ".temp"
                        qgsfilename = (
                            os.path.splitext(os.path.basename(path))[0] + ".qgs"
                        )
                        with zipfile.ZipFile(path, "r") as zin:
                            with zipfile.ZipFile(tmpfilename, "w") as zout:
                                zout.comment = zin.comment
                                for item in zin.infolist():
                                    if not item.filename.lower().endswith(".qgs"):
                                        zout.writestr(item, zin.read(item.filename))
                                    else:
                                        s = zin.read(item.filename).decode("utf-8")
                                        s = s.replace(
                                            PlanetClient.getInstance().api_key(), ""
                                        )
                                        qgsfilename = item.filename
                        os.remove(path)
                        os.rename(tmpfilename, path)
                        with zipfile.ZipFile(
                            path, mode="a", compression=zipfile.ZIP_DEFLATED
                        ) as zf:
                            zf.writestr(qgsfilename, s)
                except Exception:
                    QMessageBox.warning(
                        self.iface.mainWindow(),
                        "Error saving project",
                        "There was an error while removing API keys from QGIS project"
                        " file.\nThe project that you have just saved might contain"
                        " Planet API keys in plain text.",
                    )

            QTimer.singleShot(100, resave)
class Plugin:
    """QGIS Plugin Implementation."""
    def __init__(self, iface: QgisInterface) -> None:

        self.iface = iface

        setup_logger(plugin_name(), iface)
        # setup_task_logger(plugin_name())

        # initialize locale
        locale, file_path = setup_translation()
        if file_path:
            self.translator = QTranslator()
            self.translator.load(file_path)
            # noinspection PyCallByClass
            QCoreApplication.installTranslator(self.translator)
        else:
            pass

        self.actions: List[QAction] = []
        self.menu = tr(plugin_name())

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.dock_widget: Optional[QtWidgets.QDockWidget] = None

        self.processing_provider = SpatialDataPackageProcessingProvider()

    def add_action(
        self,
        icon_path: str,
        text: str,
        callback: Callable,
        enabled_flag: bool = True,
        add_to_menu: bool = True,
        add_to_toolbar: bool = True,
        status_tip: Optional[str] = None,
        whats_this: Optional[str] = None,
        parent: Optional[QWidget] = None,
    ) -> QAction:
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.

        :param text: Text that should be shown in menu items for this action.

        :param callback: Function to be called when the action is triggered.

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.

        :param parent: Parent widget for the new action. Defaults None.

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        # noinspection PyUnresolvedReferences
        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self) -> None:  # noqa: N802
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.add_action(
            resources_path("icons", "icon.png"),
            text=tr(plugin_name()),
            callback=self.run,
            parent=self.iface.mainWindow(),
            add_to_toolbar=True,
        )

        QgsApplication.processingRegistry().addProvider(
            self.processing_provider)

    def onClosePlugin(self) -> None:  # noqa: N802
        """Cleanup necessary items here when plugin dockwidget is closed"""
        if self.dock_widget is not None:
            self.dock_widget.closingPlugin.disconnect(self.onClosePlugin)
            self.plugin_is_active = False

    def unload(self) -> None:  # noqa: N802
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(tr(plugin_name()), action)
            self.iface.removeToolBarIcon(action)

        QgsApplication.processingRegistry().removeProvider(
            self.processing_provider)
        teardown_logger(plugin_name())

    # noinspection PyArgumentList
    def run(self) -> None:
        """Run method that performs all the real work"""
        if self.dock_widget is None:
            self.dock_widget = ExporterDockWidget(self.iface)

        self.dock_widget.closingPlugin.connect(self.onClosePlugin)

        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
        self.dock_widget.show()
Пример #47
0
class MtfEstimator:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'MtfEstimator_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&MTF Estimator')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('MtfEstimator', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/mtf_estimator/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'MTF Estimator'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&MTF Estimator'), action)
            self.iface.removeToolBarIcon(action)

    def console(self, *message):
        message = [str(i) for i in message]
        self.dlg.plainTextEdit.appendPlainText(" ".join(message))

    def finish(self):
        self.dlg.done(0)

    def run_mtf_algo(self):
        #self.dlg.runButton.setEnabled(False)
        self.console("__START__")
        raster_layer = self.dlg.mMapRasterLayerComboBox.currentLayer()
        band_n = self.dlg.mRasterBandComboBox.currentBand()

        gdal_layer = gdal.Open(raster_layer.source(), gdal.GA_ReadOnly)
        gt = list(gdal_layer.GetGeoTransform())
        xsize = gdal_layer.RasterXSize
        ysize = gdal_layer.RasterYSize
        band = gdal_layer.GetRasterBand(band_n)
        raster_srs = osr.SpatialReference()
        raster_srs.ImportFromWkt(gdal_layer.GetProjection())
        vlayer = self.dlg.mMapVectorLayerComboBox.currentLayer()
        vector_srs = osr.SpatialReference()
        vector_srs.ImportFromWkt(vlayer.crs().toWkt())

        # OJO!!!!
        # https://gdal.org/tutorials/osr_api_tut.html#crs-and-axis-order
        import osgeo
        if int(osgeo.__version__[0]) >= 3:
            # GDAL 3 changes axis order: https://github.com/OSGeo/gdal/issues/1546
            raster_srs.SetAxisMappingStrategy(
                osgeo.osr.OAMS_TRADITIONAL_GIS_ORDER)
            vector_srs.SetAxisMappingStrategy(
                osgeo.osr.OAMS_TRADITIONAL_GIS_ORDER)

        if str(raster_srs) is '':
            coord_transform = None
            self.console('WARNING: Raster with no CRS')
            gt[5] = -1 * gt[5]
        else:
            coord_transform = osr.CoordinateTransformation(
                vector_srs, raster_srs)

        self.console(vector_srs.GetName())
        self.console("")
        self.console(raster_srs.GetName())
        self.console("")
        self.console(coord_transform)

        memlayer_drv = ogr.GetDriverByName('Memory')
        memlayer_ds = memlayer_drv.CreateDataSource('')
        memlayer = memlayer_ds.CreateLayer('aoi',
                                           raster_srs,
                                           geom_type=ogr.wkbPolygon)
        memlayer.CreateField(ogr.FieldDefn('id', ogr.OFTInteger))
        featureDefn = memlayer.GetLayerDefn()

        for qgs_feature in vlayer.getFeatures():
            featureDefn = memlayer.GetLayerDefn()
            memfeat = ogr.Feature(featureDefn)
            geom = qgs_feature.geometry()
            self.console(geom.asWkt())
            geom = geom.asWkb()
            geom = ogr.CreateGeometryFromWkb(geom)
            if not coord_transform is None:
                geom.Transform(coord_transform)
            self.console(geom)

            memfeat.SetGeometry(geom)
            memlayer.CreateFeature(memfeat)

        # Get extent in raster coords
        e = np.array(memlayer.GetExtent()).copy()
        e = np.reshape(e, [2, 2])
        e = np.array(np.meshgrid(e[0], e[1]))
        E = e.T.reshape(-1, 2)
        m = np.reshape(np.array(gt).copy(), [2, 3])
        A = m[:, 0]
        m = m[:, 1:]
        M = np.linalg.inv(m)
        col_list, row_list = np.matmul(M, (E - A).T)
        pxoffset = 5
        col_min = np.int(np.max([np.floor(np.min(col_list)) - pxoffset, 1]))
        col_max = np.int(
            np.min([np.ceil(np.max(col_list)) + pxoffset, xsize - 1]))
        row_min = np.int(np.max([np.floor(np.min(row_list)) - pxoffset, 1]))
        row_max = np.int(
            np.min([np.ceil(np.max(row_list)) + pxoffset, ysize - 1]))
        sub_gt = gt
        sub_gt[0] = gt[0] + gt[1] * col_min + gt[2] * row_min
        sub_gt[3] = gt[3] + gt[4] * col_min + gt[5] * row_min
        sub_xsize = col_max - col_min
        sub_ysize = row_max - row_min

        memraster_drv = gdal.GetDriverByName('MEM')
        memraster = memraster_drv.Create('', sub_xsize, sub_ysize, 1,
                                         band.DataType)

        memraster.SetProjection(gdal_layer.GetProjection())
        memraster.SetGeoTransform(sub_gt)
        memband = memraster.GetRasterBand(1)
        memband.WriteArray(np.zeros([sub_ysize, sub_xsize]))
        gdal.RasterizeLayer(memraster, [1], memlayer, burn_values=[1])
        mask = memband.ReadAsArray(0, 0, sub_xsize, sub_ysize)
        memband.WriteArray(
            mask * band.ReadAsArray(col_min, row_min, sub_xsize, sub_ysize))
        mask = None

        try:
            mtf = Mtf(memraster, logfunc=self.console)
        except Exception:
            #self.console(Exception)
            self.console("*** Unable to estimate ***")
            self.console("__END__")
        else:
            self.console("__END__")

        #self.dlg.runButton.setEnabled(True)

    def set_band(self):
        self.dlg.mRasterBandComboBox.setLayer(
            self.dlg.mMapRasterLayerComboBox.currentLayer())

    def show_help(self):
        from PyQt5.QtCore import QUrl
        from PyQt5.QtGui import QDesktopServices
        QDesktopServices.openUrl(
            QUrl('https://github.com/JorgeGIlG/MTF_Estimator'))

    def run(self):
        # 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.dlg = MtfEstimatorDialog()
            self.dlg.closeButton.clicked.connect(self.finish)
            self.dlg.runButton.clicked.connect(self.run_mtf_algo)
            self.dlg.helpButton.clicked.connect(self.show_help)
            self.dlg.mMapRasterLayerComboBox.setFilters(
                QgsMapLayerProxyModel.RasterLayer)
            self.dlg.mMapRasterLayerComboBox.layerChanged.connect(
                self.set_band)
            self.set_band()
            self.dlg.mMapVectorLayerComboBox.setFilters(
                QgsMapLayerProxyModel.VectorLayer)
        # show the dialog
        self.dlg.show()
Пример #48
0
class NewRaptor:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'NewRaptor_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Add New Raptor')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('NewRaptor', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToVectorMenu(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/new_raptor/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Add New Raptor Nest'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.tr(u'&Add New Raptor'),
                                              action)
            self.iface.removeToolBarIcon(action)

    def run(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.dlg = NewRaptorDialog()
            self.dlg.cmbSpecies.currentTextChanged.connect(
                self.evt_cmbSpecies_changed)

        mc = self.iface.mapCanvas()
        self.dlg.spbLatitude.setValue(mc.center().y())
        self.dlg.spbLongitude.setValue(mc.center().x())
        self.dlg.dteLast.setDate(QDate.currentDate())

        map_layers = []
        for lyr in mc.layers():
            map_layers.append(lyr.name())
        missing_layers = []
        if not "Raptor Nests" in map_layers:
            missing_layers.append("Raptor Nests")
        if not "Raptor Buffer" in map_layers:
            missing_layers.append("Raptor Buffer")
        if not "Linear Buffer" in map_layers:
            missing_layers.append("Linear Buffer")
        if missing_layers:
            msg = "The following layers are misisng from this project\n"
            for lyr in missing_layers:
                msg += "\n{}".format(lyr)
            QMessageBox.critical(self.dlg, "Missing layers", msg)
            return

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            lyrNests = QgsProject.instance().mapLayersByName("Raptor Nests")[0]
            lyrBuffer = QgsProject.instance().mapLayersByName(
                "Raptor Buffer")[0]
            lyrLinear = QgsProject.instance().mapLayersByName(
                "Linear Buffer")[0]
            idxNestID = lyrNests.fields().indexOf("Nest_ID")
            valNestID = lyrNests.maximumValue(idxNestID) + 1
            valLat = self.dlg.spbLatitude.value()
            valLng = self.dlg.spbLongitude.value()
            valSpecies = self.dlg.cmbSpecies.currentText()
            valBuffer = self.dlg.spbBuffer.value()
            valStatus = self.dlg.cmbStatus.currentText()
            valLast = self.dlg.dteLast.date()
            QMessageBox.information(
                self.dlg, "Message",
                "New Nest ID: {}\n\nLatitude: {}\nLongitude: {}\nSpecies: {}\nBuffer: {}\nStatus: {}\nLast Survey: {}"
                .format(valNestID, valLat, valLng, valSpecies, valBuffer,
                        valStatus, valLast))
            ftrNest = QgsFeature(lyrNests.fields())
            ftrNest.setAttribute("lat_y_dd", valLat)
            ftrNest.setAttribute("long_x_dd", valLng)
            ftrNest.setAttribute("recentspec", valSpecies)
            ftrNest.setAttribute("buf_dist", valBuffer)
            ftrNest.setAttribute("recentstat", valStatus)
            ftrNest.setAttribute("lastsurvey", valLast)
            ftrNest.setAttribute("Nest_ID", valNestID)
            geom = QgsGeometry(QgsPoint(valLng, valLat))
            ftrNest.setGeometry(geom)
            pr = lyrNests.dataProvider()
            pr.addFeatures([ftrNest])
            lyrNests.reload()

            pr = lyrBuffer.dataProvider()
            buffer = geom.buffer(valBuffer, 10)
            ftrNest.setGeometry(buffer)
            pr.addFeatures([ftrNest])
            lyrBuffer.reload()

            dlgTable = DlgTable()
            dlgTable.setWindowTitle(
                "Impacts Table for Nest {}".format(valNestID))
            # Find linear projects that will be impacted and report them in the table
            bb = buffer.boundingBox()
            linears = lyrLinear.getFeatures(bb)
            for linear in linears:
                valID = linear.attribute("Project")
                valType = linear.attribute("type")
                valDistance = linear.geometry().distance(geom)
                if valDistance < valBuffer:
                    # Populate table with linear data
                    row = dlgTable.tblImpacts.rowCount()
                    dlgTable.tblImpacts.insertRow(row)
                    dlgTable.tblImpacts.setItem(row, 0,
                                                QTableWidgetItem(str(valID)))
                    dlgTable.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(valType))
                    twi = QTableWidgetItem("{:4.5f}".format(valDistance))
                    twi.setTextAlignment(QtCore.Qt.AlignRight)
                    dlgTable.tblImpacts.setItem(row, 2, twi)

            dlgTable.tblImpacts.sortItems(2)
            dlgTable.show()
            dlgTable.exec_()

        else:
            QMessageBox.information(self.dlg, "Message",
                                    "Should only run if cancelled")

    def evt_cmbSpecies_changed(self, species):
        if species == "Swainsons Hawk":
            self.dlg.spbBuffer.setValue(0.004)
        else:
            self.dlg.spbBuffer.setValue(0.008)
Пример #49
0
class pthplugin:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'pthplugin_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&paikkatietohakemisto-plugin')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None
        self.services = []
        self.urls = []
        self.selected = None
        self.layersList = []

    # 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('pthplugin', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/pth-qgis-plugin/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Hae karttatasoja'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def addWFS(self, layerName, data):
        crs = self.getCRS()
        vlayer = getWFSFeature(layerName, data, crs)
        if vlayer.isValid:
            QgsProject.instance().addMapLayer(vlayer)

    def addWMS(self, layerName, data):
        crs = self.getCRS()
        rlayer = getWMSFeature(layerName, data, crs)
        if rlayer.isValid:
            QgsProject.instance().addMapLayer(rlayer)

    def getCRS(self):
        crs = "EPSG:3067"
        activeLayer = self.iface.activeLayer()
        if activeLayer:
            if activeLayer.crs().authid():
                crs = self.iface.activeLayer().crs().authid()

        return crs

    def searchApi(self):
        """Send request to pth search API and return results."""
        self.dlg.layerTree.clear()
        self.dlg.searchResult.clear()
        self.dlg.abstractBox.clear()
        self.services = []
        self.urls = []
        self.selected = None
        text = self.dlg.searchBox.text()

        if (text and text.strip()):
            #TODO: Do something with language
            hits = SearchPTH(text, "FI")
            if hits:
                self.addResults(hits)
                self.dlg.searchResult.itemClicked.connect(
                    self.searchResultClicked)
            else:
                self.noResults()

    def addResults(self, hits):
        #REFACTOR to add if link is missing
        for hit in hits:
            for link in hit.get("downloadLinks"):
                title = self.getTitleFromHit(hit)
                if title:
                    item = QListWidgetItem()
                    item.setText(title)
                    item.setData(1, hit)
                    self.dlg.searchResult.addItem(item)

    def noResults(self):
        item = QListWidgetItem()
        item.setText("Hakutuloksia ei löytynyt!")
        self.dlg.searchResult.addItem(item)

    def getTitleFromHit(self, hit):
        title = ""
        for text in hit.get("text"):
            if text.get("lang") == "FI":
                title = text.get("title")
        return title

    def searchResultClicked(self, item):
        self.dlg.layerTree.clear()
        self.layersList = []
        self.selected = None

        data = item.data(1)
        if not data:
            return
        for text in data.get("text"):
            #TODO: Do something better with language
            lang = text.get("lang")
            if lang == "FI":
                self.dlg.abstractBox.setText(text.get("abstractText"))

        links = data.get("downloadLinks")
        if links:
            for link in links:
                LOG("Download links")
                LOG(link)
                protocol = link.get("protocol")
                url = link.get("url")
                layers = getLayersForDownloadLink(protocol, url)
                if layers.get("type") == "NA":
                    if link.get("url"):
                        layers["link"] = link.get("url")
                    else:
                        layers["link"] = data.get("catalog").get("url")
                self.layersList.append(layers)

        #Add handling for wms and wmts. Try to make code more reusable
        treeItems = []
        for index, layers in enumerate(self.layersList):
            nodeTitle = links[index].get("title")
            if not nodeTitle:
                nodeTitle = layers.get("url")
            if not nodeTitle:
                nodeTitle = layers.get("link")
            if not nodeTitle:
                continue
            treeItem = QTreeWidgetItem()
            type = layers.get("type")
            if type == "NA":
                if not nodeTitle:
                    nodeTitle = layers.get("link")
                treeItem.setText(0, "LINK: " + nodeTitle)
                treeItem.setData(0, 1, {
                    "layerName": nodeTitle,
                    "index": index
                })
            elif type != "ERROR":
                treeItem.setText(0, type + ": " + nodeTitle)
                treeItem.addChildren(listChildNodes(layers, index))

            treeItems.append(treeItem)

        self.dlg.layerTree.addTopLevelItems(treeItems)

    def treeItemClicked(self, item):
        self.selected = item.data(0, 1)

    def treeItemDoubleClicked(self, item):
        data = item.data(0, 1)
        if data is not None:
            layer = self.layersList[data.get("index")]
            if layer.get("type") == "NA":
                link = layer.get("link")
                if link:
                    webbrowser.open(layer.get("link"))
            else:
                self.selected = data
                self.addLayer()

    def addLayer(self):
        if self.selected:
            data = self.selected
            layerName = data.get("layerName")
            layer = self.layersList[data.get("index")]
            if "WFS" == layer.get("type"):
                self.addWFS(layerName, layer)
            elif "WMS" == layer.get("type"):
                self.addWMS(layerName, layer)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&paikkatietohakemisto-plugin'), action)
            self.iface.removeToolBarIcon(action)

    def run(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.dlg = pthpluginDialog()
            self.dlg.searchButton.clicked.connect(self.searchApi)
            self.dlg.AddLayerButton.clicked.connect(self.addLayer)
            self.dlg.layerTree.itemClicked.connect(self.treeItemClicked)
            self.dlg.layerTree.itemDoubleClicked.connect(
                self.treeItemDoubleClicked)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Пример #50
0
class CmrQgis:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'CmrQgis_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&CMR Search')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('CmrQgis', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/cmr_qgis/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'CMR search'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&CMR Search'), action)
            self.iface.removeToolBarIcon(action)

    def addSearchParameter(self):
        """Add a search parameter to the parameter table"""
        line = self.dlg.lineEdit.text()
        if line.find('=') > 0:
            parameter, value = line.split('=')
            rowPosition = self.dlg.tableWidget.rowCount()
            self.dlg.tableWidget.insertRow(rowPosition)
            self.dlg.tableWidget.setItem(rowPosition, 0,
                                         QTableWidgetItem(parameter))
            self.dlg.tableWidget.setItem(rowPosition, 1,
                                         QTableWidgetItem(value))
            self.dlg.lineEdit.clear()

    def run(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.dlg = CmrQgisDialog()

        # get stored settings
        settings = QgsSettings()

        # Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children()
        layerNames = [layer.name() for layer in layers]

        # Clear the contents of the comboBox from previous runs
        self.dlg.comboBox.clear()
        # Populate the comboBox with names of all the loaded layers
        self.dlg.comboBox.addItems(layerNames)

        # use the previous layer as the default if it is in the existing layers
        layerName = settings.value("cmr_qgis/layer")
        if layerName and layerName in layerNames:
            self.dlg.comboBox.setCurrentIndex(layerNames.index(layerName))

        # fill the cmr url input with the saved setting if available
        cmrUrl = settings.value("cmr_qgis/cmr_search_url")
        if cmrUrl:
            self.dlg.cmrUrlLineEdit.setText(cmrUrl)

        # populate the concept type combo box
        self.dlg.comboBoxConceptType.clear()
        self.dlg.comboBoxConceptType.addItems(['collection', 'granule'])
        conceptTypeIndex = settings.value("cmr_qgis/concept_type")
        if conceptTypeIndex:
            self.dlg.comboBoxConceptType.setCurrentIndex(int(conceptTypeIndex))

        # clear the table
        self.dlg.tableWidget.setRowCount(0)

        # set the table header
        self.dlg.tableWidget.setHorizontalHeaderLabels(
            'Parameter;Value'.split(';'))

        # add a parameter/value when the 'Add' button is clicked
        self.dlg.addButton.clicked.connect(self.addSearchParameter)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            layerName = str(self.dlg.comboBox.currentText())
            # TODO handle the case where there is more than one layer by this name
            layer = QgsProject.instance().mapLayersByName(layerName)[0]
            directory = os.path.split(layer.source())[0]

            # tempFile = NamedTemporaryFile()
            # print(tempFile.name)
            tempFile = '/tmp/cmr-qgis.zip'
            with ZipFile(tempFile, 'w') as zipObj:
                for ext in ['shp', 'cpg', 'dbf', 'prj', 'shx', 'qpj']:
                    filePath = directory + "/" + layerName + '.' + ext
                    if os.path.exists(filePath):
                        zipObj.write(filePath, layerName + '.' + ext)
            # query the CMR
            cmrSearchUrl = self.dlg.cmrUrlLineEdit.text()
            cmrQueryUrl = cmrSearchUrl + "/" + self.dlg.comboBoxConceptType.currentText(
            ) + 's.kml'
            tempFileHandle = open(tempFile, 'rb')
            multipart_form_data = {
                'shapefile': (layerName + '.zip', tempFileHandle,
                              'application/shapefile+zip')
            }

            rowCount = self.dlg.tableWidget.rowCount()
            for row in range(rowCount):
                parameter = self.dlg.tableWidget.item(row, 0).text()
                value = self.dlg.tableWidget.item(row, 1).text()
                multipart_form_data[parameter] = (None, value)

            resp = requests.post(cmrQueryUrl, files=multipart_form_data)

            tempFileHandle.close()
            os.remove(tempFile)

            tmpFile = '/tmp/' + layerName + "-cmr.kml"
            with open(tmpFile, 'w') as f:
                f.write(resp.text)
            myLayer = QgsVectorLayer(tmpFile, layerName + '-cmr', 'ogr')
            QgsProject.instance().addMapLayer(myLayer)

            resp.close()

            # save the cmr url to settings
            if cmrSearchUrl != "":
                settings.setValue("cmr_qgis/cmr_search_url", cmrSearchUrl)

            # save the chosen layer to settings
            settings.setValue("cmr_qgis/layer", layerName)

            # save concept type to settings
            settings.setValue("cmr_qgis/concept_type",
                              self.dlg.comboBoxConceptType.currentIndex())
Пример #51
0
class Nominatim:
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.path = QFileInfo(os.path.realpath(__file__)).path()
        self.toolBar = None
        self.canvas = self.iface.mapCanvas()
        self.dlgPosX = 100
        self.dlgPosY = 100
        self.lastSearch = ""
        self.localiseOnStartup = True
        self.defaultArea = Qt.LeftDockWidgetArea
        self.singleLayer = True

        self.read()

        # récup langue par défaut
        locale = QSettings().value("locale/userLocale")
        try:
            self.myLocale = locale[0:2]

            # exploiter le bon dictionnaire
            localePath = (QFileInfo(os.path.realpath(__file__)).path() +
                          "/i18n/" + self.myLocale + ".qm")

            # initialiser le traducteur
            if QFileInfo(localePath).exists():
                self.translator = QTranslator()
                self.translator.load(localePath)
                QCoreApplication.installTranslator(self.translator)
        except:
            # no translation
            pass

        try:
            self.nominatim_dlg
        except:
            self.nominatim_dlg = nominatim_dlg(self.iface.mainWindow(), self)
            self.nominatim_dlg.visibilityChanged.connect(
                self.dockVisibilityChanged)
            self.nominatim_dlg.dockLocationChanged.connect(
                self.dockLocationChanged)

        try:
            self.nominatim_dlg.editSearch.setText(self.lastSearch)
        except:
            pass

        # self.filter = OsmLocatorFilter(self.iface, self)
        # self.filter.resultProblem.connect(self.showLocatorProblem)
        # self.iface.registerLocatorFilter(self.filter)

    # def showLocatorProblem(self, err):
    #    self.iface.messageBar().pushWarning(
    #        "{} - {}".format(self.tr("Error during OSM search"), err)
    #    )

    @staticmethod
    def tr(message):
        return QCoreApplication.translate("nominatim", message)

    def store(self):
        s = QSettings()
        s.setValue("nominatim/localiseOnStartup", self.localiseOnStartup)
        s.setValue("nominatim/limitSearchToExtent", tools.limitSearchToExtent)
        s.setValue("nominatim/dlgPosX", self.dlgPosX)
        s.setValue("nominatim/dlgPosY", self.dlgPosY)
        s.setValue("nominatim/lastSearch", self.lastSearch)
        s.setValue("nominatim/gnOptions", tools.gnOptions)
        s.setValue("nominatim/defaultArea", self.defaultArea)
        s.setValue("nominatim/singleLayer", self.singleLayer)

    def read(self):
        s = QSettings()

        self.localiseOnStartup = s.value("nominatim/localiseOnStartup",
                                         (False),
                                         type=bool)
        tools.limitSearchToExtent = s.value("nominatim/limitSearchToExtent",
                                            (False),
                                            type=bool)
        self.dlgPosX = s.value("nominatim/dlgPosX", 100, type=int)
        self.dlgPosY = s.value("nominatim/dlgPosY", 100, type=int)
        self.lastSearch = s.value("nominatim/lastSearch", "")
        tools.gnOptions = s.value("nominatim/gnOptions", "")
        self.defaultArea = s.value("nominatim/defaultArea",
                                   Qt.LeftDockWidgetArea,
                                   type=int)
        self.singleLayer = s.value("nominatim/singleLayer", (True), type=bool)

    def initGui(self):
        self.toolBar = self.iface.pluginToolBar()

        self.act_config = QAction(
            self.tr("Configuration") + "...",
            self.iface.mainWindow(),
        )
        self.act_nominatim_help = QAction(
            self.tr("Help") + "...",
            self.iface.mainWindow(),
        )

        self.iface.addPluginToMenu(
            "&" + self.tr(__title__),
            self.act_config,
        )
        self.iface.addPluginToMenu(
            "&" + self.tr(__title__),
            self.act_nominatim_help,
        )

        # Add actions to the toolbar
        self.act_config.triggered.connect(self.do_config)
        self.act_nominatim_help.triggered.connect(
            lambda: showPluginHelp(filename="doc/index"))

        self.iface.addDockWidget(self.defaultArea, self.nominatim_dlg)

    def unload(self):
        self.iface.removePluginMenu(
            "&" + self.tr(__title__),
            self.act_config,
        )
        self.iface.removePluginMenu(
            "&" + self.tr(__title__),
            self.act_nominatim_help,
        )
        self.store()
        self.deactivate()
        self.iface.removeDockWidget(self.nominatim_dlg)

    def dockVisibilityChanged(self, visible):
        try:
            self.defaultActive = visible
            if visible and self.localiseOnStartup:
                self.nominatim_dlg.doLocalize()
        except:
            pass

    def dockLocationChanged(self, area):
        self.defaultArea = area

    def activate(self):
        self.nominatim_dlg.show()

    def deactivate(self):
        try:
            self.nominatim_dlg.hide()
        except:
            pass

    def zoom(self):
        pass

    def do_config(self):
        dlg = nominatim_conf_dlg(self.iface.mainWindow(), self)
        dlg.setModal(True)

        dlg.show()
        dlg.exec_()
        del dlg
Пример #52
0
class timemanager(object):
    """Plugin information"""
    name = "timemanager"
    longName = "TimeManager Plugin for QGIS >= 2.3"
    description = "Working with temporal vector data"
    author = "Anita Graser, Karolina Alexiou"
    pluginUrl = "https://github.com/anitagraser/TimeManager"

    def __init__(self, iface):
        """Initialize the plugin"""
        global control
        try:
            control
        except NameError:
            try:
                overrideLocale = bool(QSettings().value(
                    "locale/overrideFlag", False))
                if not overrideLocale:
                    lang = QLocale.system().name().split("_")[0]
                else:
                    lang = QSettings().value("locale/userLocale",
                                             "").split("_")[0]
            except Exception:
                lang = "en"  # could not get locale, OSX may have this bug
            info("Plugin language loaded: {}".format(lang))
            self.changeI18n(lang)
            control = TimeManagerControl(iface)

    def getController(self):
        return control

    def initGui(self):
        """Initialize the gui"""
        control.load()

    def changeI18n(self, new_lang):
        """
        Change internationalisation for the plugin.
        Override the system locale  and then see if we can get a valid
        translation file for whatever locale is effectively being used.
        """
        # os.environ["LANG"] = str(new_lang)
        root = os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.pardir))
        translation_path = "TimeManager:i18n/{}_{}.qm".format(
            self.name, new_lang)
        self.translator = QTranslator()
        result = self.translator.load(translation_path)
        if not result:
            error("Translation file {} for lang {} was not loaded properly," +
                  "falling back to English".format(translation_path, new_lang))
            return
        if qVersion() > "4.3.3":
            QCoreApplication.installTranslator(self.translator)
        else:
            self.translator = None
            warn("Translation not supported for Qt <= {}".format(qVersion()))

    def unload(self):
        """Unload the plugin"""
        control.unload()
        QgsExpression.unregisterFunction("$animation_datetime")
        QgsExpression.unregisterFunction("animation_datetime")
        QgsExpression.unregisterFunction("$animation_time_frame_size")
        QgsExpression.unregisterFunction("animation_time_frame_size")
        QgsExpression.unregisterFunction("$animation_time_frame_type")
        QgsExpression.unregisterFunction("animation_time_frame_type")
        QgsExpression.unregisterFunction("$animation_start_datetime")
        QgsExpression.unregisterFunction("animation_start_datetime")
        QgsExpression.unregisterFunction("$animation_end_datetime")
        QgsExpression.unregisterFunction("animation_end_datetime")

    @qgsfunction(0, "TimeManager")
    def animation_datetime(values, feature, parent):
        """Current animation time"""
        return time_util.datetime_to_str(
            control.getTimeLayerManager().getCurrentTimePosition(),
            time_util.DEFAULT_FORMAT)

    @qgsfunction(0, "TimeManager")
    def animation_time_frame_size(values, feature, parent):
        """Animation time frame size"""
        return control.getTimeLayerManager().getTimeFrameSize()

    @qgsfunction(0, "TimeManager")
    def animation_time_frame_type(values, feature, parent):
        """Unit of time frame, i.e. days, hours, minutes, seconds, ..."""
        return control.getTimeLayerManager().getTimeFrameType()

    @qgsfunction(0, "TimeManager")
    def animation_start_datetime(values, feature, parent):
        """Earliest time stamp"""
        return time_util.datetime_to_str(
            control.getTimeLayerManager().getProjectTimeExtents()[0],
            time_util.DEFAULT_FORMAT)

    @qgsfunction(0, "TimeManager")
    def animation_end_datetime(values, feature, parent):
        """Last time stamp"""
        return time_util.datetime_to_str(
            control.getTimeLayerManager().getProjectTimeExtents()[1],
            time_util.DEFAULT_FORMAT)
class menu_from_project:
    def __init__(self, iface):
        self.path = QFileInfo(os.path.realpath(__file__)).path()
        self.iface = iface
        self.toolBar = None

        # new multi projects var
        self.projects = []
        self.menubarActions = []
        self.canvas = self.iface.mapCanvas()
        self.optionTooltip = False
        self.optionCreateGroup = False
        self.optionLoadAll = False
        self.read()
        # default lang
        locale = QSettings().value("locale/userLocale")
        self.myLocale = locale[0:2]
        # dictionnary
        localePath = self.path+"/i18n/menu_from_project_" + self.myLocale + \
            ".qm"
        # translator
        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)
            QCoreApplication.installTranslator(self.translator)

    def tr(self, message):
        return QCoreApplication.translate('menu_from_project', message)

    def store(self):
        s = QSettings()
        s.remove("menu_from_project/projectFilePath")

        s.setValue("menu_from_project/optionTooltip", self.optionTooltip)
        s.setValue("menu_from_project/optionCreateGroup",
                   self.optionCreateGroup)
        s.setValue("menu_from_project/optionLoadAll", self.optionLoadAll)

        s.beginWriteArray("menu_from_project/projects")
        for i, project in enumerate(self.projects):
            s.setArrayIndex(i)
            s.setValue("file", project["file"])
            s.setValue("name", project["name"])

        s.endArray()

    def read(self):
        s = QSettings()
        try:
            # old single project conf
            filePath = s.value("menu_from_project/projectFilePath", "")

            if filePath:
                title = filePath.split('/')[-1]
                title = title.split('.')[0]
                self.projects.append({"file": filePath, "name": title})
                self.store()
            else:
                # patch : lecture ancienne conf
                size = s.beginReadArray("projects")
                for i in range(size):
                    s.setArrayIndex(i)
                    file = ((s.value("file").toString()))
                    name = ((s.value("name").toString()))
                    if file:
                        self.projects.append({"file": file, "name": name})
                s.endArray()

                size = s.beginReadArray("menu_from_project/projects")
                for i in range(size):
                    s.setArrayIndex(i)
                    file = s.value("file", "")
                    name = s.value("name", "")
                    if file != "":
                        self.projects.append({"file": file, "name": name})

                s.endArray()

            self.optionTooltip = s.value("menu_from_project/optionTooltip",
                                         True,
                                         type=bool)

            # create group option only since 1.9
            self.optionCreateGroup = s.value(
                "menu_from_project/optionCreateGroup", False, type=bool)
            self.optionLoadAll = s.value("menu_from_project/optionLoadAll",
                                         False,
                                         type=bool)

        except:
            pass

    def isAbsolute(self, doc):
        absolute = False
        try:
            props = doc.elementsByTagName("properties")
            if props.count() == 1:
                node = props.at(0)
                pathNode = node.namedItem("Paths")
                absNode = pathNode.namedItem("Absolute")
                absolute = ("true" == absNode.firstChild().toText().data())
        except:
            pass

        return absolute

    def addToolTip(self, ml, action):
        if ml is not None:
            try:
                title = ml.namedItem("title").firstChild().toText().data()
                abstract = ml.namedItem(
                    "abstract").firstChild().toText().data()

                action.setStatusTip(title)
                if (abstract != "") and (title == ""):
                    action.setToolTip("<p>%s</p>" %
                                      ("<br/>".join(abstract.split("\n"))))
                else:
                    if abstract != "" or title != "":
                        action.setToolTip(
                            "<b>%s</b><br/>%s" %
                            (title, "<br/>".join(abstract.split("\n"))))
                    else:
                        action.setToolTip("")
            except:
                pass

    def addMenuItem(self, filename, node, menu, domdoc, mapLayersDict):
        yaLayer = False
        initialFilename = filename
        if node is None or node.nodeName() == "":
            return yaLayer

        element = node.toElement()

        # if legendlayer tag
        if node.nodeName() == "layer-tree-layer":
            try:
                name = element.attribute("name")
                layerId = element.attribute("id")
                visible = element.attribute("checked", "") == "Qt::Checked"
                expanded = element.attribute("expanded", "0") == "1"
                action = QAction(name, self.iface.mainWindow())
                embedNd = getFirstChildByAttrValue(element, "property", "key",
                                                   "embedded")

                # is layer embedded ?
                if embedNd and embedNd.toElement().attribute("value") == "1":
                    # layer is embeded
                    efilename = None
                    eFileNd = getFirstChildByAttrValue(element, "property",
                                                       "key",
                                                       "embedded_project")

                    # get project file name
                    embeddedFile = eFileNd.toElement().attribute("value")
                    if not self.absolute and (embeddedFile.find(".") == 0):
                        efilename = self.projectpath + "/" + embeddedFile

                    # if ok
                    if efilename:
                        # add menu item
                        action.triggered.connect(
                            lambda checked, f=efilename, lid=layerId, m=menu, v
                            =visible, x=expanded: self.do_aeag_menu(
                                f, lid, m, v, x))

                        menu.addAction(action)
                        yaLayer = True

                        if self.optionTooltip:
                            # search embeded maplayer (for title, abstract)
                            mapLayer = getMapLayerDomFromQgs(
                                efilename, layerId)
                            if mapLayer is not None:
                                self.addToolTip(mapLayer, action)
                            else:
                                QgsMessageLog.logMessage(
                                    "Menu from layer: " + layerId +
                                    " not found in project " + efilename,
                                    'Extensions')

                # layer is not embedded
                else:
                    if self.optionTooltip:
                        self.addToolTip(mapLayersDict[layerId], action)

                    action.triggered.connect(
                        lambda checked, f=filename, lid=layerId, m=menu, v=
                        visible, x=expanded: self.do_aeag_menu(
                            f, lid, m, v, x))

                    menu.addAction(action)
                    yaLayer = True
            except Exception as e:
                for m in e.args:
                    QgsMessageLog.logMessage(m, 'Extensions')

        # / if element.tagName() == "layer-tree-layer":

        # if legendgroup tag
        if node.nodeName() == "layer-tree-group":
            name = element.attribute("name")
            if name == "-":
                menu.addSeparator()

            elif name.startswith("-"):
                action = QAction(name[1:], self.iface.mainWindow())
                font = QFont()
                font.setBold(True)
                action.setFont(font)
                menu.addAction(action)

            else:
                # sub-menu
                sousmenu = menu.addMenu('&' + element.attribute("name"))
                sousmenu.menuAction().setToolTip("")
                sousmenu.setToolTipsVisible(self.optionTooltip)

                childNode = node.firstChild()

                #  ! recursion
                r = self.addMenuItem(initialFilename, childNode, sousmenu,
                                     domdoc, mapLayersDict)

                if r and self.optionLoadAll and (len(sousmenu.actions()) > 1):
                    action = QAction(self.tr("Load all"),
                                     self.iface.mainWindow())
                    font = QFont()
                    font.setBold(True)
                    action.setFont(font)
                    sousmenu.addAction(action)
                    action.triggered.connect(
                        lambda checked, f=None, w=None, m=sousmenu: self.
                        do_aeag_menu(f, w, m))

        # / if element.tagName() == "legendgroup":

        nextNode = node.nextSibling()
        if nextNode is not None:
            # ! recursion
            r = self.addMenuItem(initialFilename, nextNode, menu, domdoc,
                                 mapLayersDict)
            yaLayer = yaLayer or r

        return yaLayer

    def addMenu(self, name, filename, domdoc):
        # main project menu
        menuBar = self.iface.editMenu().parentWidget()
        projectMenu = QMenu('&' + name, menuBar)

        projectMenu.setToolTipsVisible(self.optionTooltip)

        projectAction = menuBar.addMenu(projectMenu)
        self.menubarActions.append(projectAction)

        self.absolute = self.isAbsolute(domdoc)
        self.projectpath = QFileInfo(os.path.realpath(filename)).path()

        mapLayersDict = getMapLayersDict(domdoc)

        # build menu on legend schema
        legends = domdoc.elementsByTagName("layer-tree-group")
        if legends.length() > 0:
            node = legends.item(0)
            if node:
                node = node.firstChild()
                self.addMenuItem(filename, node, projectMenu, domdoc,
                                 mapLayersDict)

    def initMenus(self):
        menuBar = self.iface.editMenu().parentWidget()
        for action in self.menubarActions:
            menuBar.removeAction(action)
            del action

        self.menubarActions = []

        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        for project in self.projects:
            try:
                doc = QtXml.QDomDocument()
                xml = QFile(project["file"])
                if xml.open(QIODevice.ReadOnly | QIODevice.Text):
                    doc.setContent(xml)

                self.addMenu(project["name"], project["file"], doc)
            except Exception as e:
                QgsMessageLog.logMessage(
                    'Menu from layer: Invalid {}'.format(project["file"]),
                    'Extensions')
                for m in e.args:
                    QgsMessageLog.logMessage(m, 'Extensions')

        QgsApplication.restoreOverrideCursor()

    def initGui(self):
        self.act_aeag_menu_config = QAction(
            self.tr("Projects configuration") + "...", self.iface.mainWindow())

        self.iface.addPluginToMenu(self.tr("&Layers menu from project"),
                                   self.act_aeag_menu_config)
        # Add actions to the toolbar
        self.act_aeag_menu_config.triggered.connect(self.do_aeag_menu_config)

        self.act_aeag_menu_help = QAction(
            self.tr("Help") + "...", self.iface.mainWindow())
        self.iface.addPluginToMenu(self.tr("&Layers menu from project"),
                                   self.act_aeag_menu_help)
        self.act_aeag_menu_help.triggered.connect(self.do_help)

        # build menu
        self.initMenus()

    def unload(self):
        menuBar = self.iface.editMenu().parentWidget()
        for action in self.menubarActions:
            menuBar.removeAction(action)

        self.iface.removePluginMenu(self.tr("&Layers menu from project"),
                                    self.act_aeag_menu_config)
        self.iface.removePluginMenu(self.tr("&Layers menu from project"),
                                    self.act_aeag_menu_help)
        self.act_aeag_menu_config.triggered.disconnect(
            self.do_aeag_menu_config)
        self.act_aeag_menu_help.triggered.disconnect(self.do_help)

        self.store()

    def do_aeag_menu_config(self):
        dlg = menu_conf_dlg(self.iface.mainWindow(), self)
        dlg.setModal(True)

        dlg.show()
        result = dlg.exec_()
        del dlg

        if result != 0:
            self.initMenus()

    # run method that performs all the real work
    def do_aeag_menu(self,
                     fileName,
                     who,
                     menu=None,
                     visible=None,
                     expanded=None):
        self.canvas.freeze(True)
        self.canvas.setRenderFlag(False)
        group = None
        theLayer = None
        groupName = None
        QgsApplication.setOverrideCursor(Qt.WaitCursor)

        try:
            if (type(menu.parentWidget()) == QMenu or type(menu.parentWidget())
                    == QWidget) and self.optionCreateGroup:
                groupName = menu.title().replace("&", "")
                group = QgsProject.instance().layerTreeRoot().findGroup(
                    groupName)
                if group is None:
                    group = QgsProject.instance().layerTreeRoot().addGroup(
                        groupName)

            # load all layers
            if fileName is None and who is None and self.optionLoadAll:
                for action in menu.actions():
                    if ((action.text() != self.tr("&Load all"))
                            and (action.text() != "Load all")):
                        action.trigger()
            else:
                # read QGis project
                doc = QtXml.QDomDocument()
                xml = QFile(fileName)
                if xml.open(QIODevice.ReadOnly | QIODevice.Text):
                    doc.setContent(xml)

                # is project in relative path ?
                absolute = self.isAbsolute(doc)

                node = getFirstChildByTagNameValue(doc.documentElement(),
                                                   "maplayer", "id", who)
                if node:
                    idNode = node.namedItem("id")
                    layerType = node.toElement().attribute("type", "vector")
                    # give it a new id (for multiple import)
                    import re
                    newLayerId = "L%s" % re.sub("[{}-]", "",
                                                QUuid.createUuid().toString())
                    try:
                        idNode.firstChild().toText().setData(newLayerId)
                    except:
                        pass

                    # if relative path, adapt datasource
                    if not absolute:
                        try:
                            datasourceNode = node.namedItem("datasource")
                            ds = datasourceNode.firstChild().toText().data()
                            providerNode = node.namedItem("provider")
                            provider = providerNode.firstChild().toText().data(
                            )

                            if provider == "ogr" and (ds.find(".") == 0):
                                projectpath = QFileInfo(
                                    os.path.realpath(fileName)).path()
                                newlayerpath = projectpath + "/" + ds
                                datasourceNode.firstChild().toText().setData(
                                    newlayerpath)
                        except:
                            pass

                    # read modified layer node
                    if self.optionCreateGroup and group is not None:
                        """# sol 1 bug : layer incomplete
                        # because of API strange behaviour, we clone the layer... 
                        theLayer = QgsProject.instance().mapLayer(newLayerId)
                        cloneLayer = theLayer.clone()
                        # removing the first
                        QgsProject.instance().removeMapLayer(newLayerId)
                        # adding the clone...
                        treeNode = group.addLayer(cloneLayer)
                        treeNode.setExpanded(expanded)
                        treeNode.setItemVisibilityChecked(visible)"""

                        # solution 2, ok !
                        if layerType == "raster":
                            theLayer = QgsRasterLayer()
                        else:
                            theLayer = QgsVectorLayer()

                        theLayer.readLayerXml(node.toElement(),
                                              QgsReadWriteContext())
                        # needed
                        QgsProject.instance().addMapLayer(theLayer, False)
                        # add to group
                        treeNode = group.addLayer(theLayer)
                        treeNode.setExpanded(expanded)
                        treeNode.setItemVisibilityChecked(visible)
                    else:
                        # create layer
                        QgsProject.instance().readLayer(node)

        except Exception as e:
            QgsMessageLog.logMessage(
                'Menu from layer: Invalid ' +
                (fileName if fileName is not None else ""), 'Extensions')
            for m in e.args:
                QgsMessageLog.logMessage(m, 'Extensions')

        self.canvas.freeze(False)
        self.canvas.setRenderFlag(True)
        self.canvas.refresh()
        QgsApplication.restoreOverrideCursor()

    def do_help(self):
        try:
            if os.path.isfile(self.path + "/help_" + self.myLocale + ".html"):
                webbrowser.open(self.path + "/help_" + self.myLocale + ".html")
            else:
                webbrowser.open(self.path + "/help.html")

        except Exception as e:
            for m in e.args:
                QgsMessageLog.logMessage(m, 'Extensions')
Пример #54
0
class PolyStacker:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'PolyStacker_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Polygon Stacker')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('PolyStacker', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/poly_stacker/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'PolyStacker'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Polygon Stacker'), action)
            self.iface.removeToolBarIcon(action)

    def run(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.dlg = PolyStackerDialog()

        # Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children()
        # Clear the contents of the comboBox from previous runs
        self.dlg.comboBox.clear()
        # Populate the comboBox with names of all the loaded layers
        self.dlg.comboBox.addItems([layer.name() for layer in layers])

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()

        # See if OK was pressed

        #for running in Python Console:
        #def layerSelection():
        #canvas = qgis.utils.iface.mapCanvas()
        #layer = qgis.utils.iface.activeLayer()

        #for running as a Plugin:
        def layerSelection(self):
            #fetch the current layer index
            selectedLayerIndex = self.dlg.comboBox.currentIndex()
            #define the selected layer
            activeLayer = layers[selectedLayerIndex].layer()

            #get features of the selected layer
            features = activeLayer.selectedFeatures()
            selectedIds = activeLayer.selectedFeatureIds()
            #start editing the selected layer
            activeLayer.startEditing()
            return activeLayer, features, selectedIds

        def stackPolygon(self):
            activeLayer, features, selectedIds = layerSelection(self)
            #randomly selected an ID to snap selected (sheep) features to
            wolfFeature = random.choice(features)
            wolfGeom = wolfFeature.geometry()
            wolfCentre = wolfGeom.centroid()
            wolfX = wolfCentre.asPoint().x()
            wolfY = wolfCentre.asPoint().y()
            #wolfPoly = wolfGeom.asMultiPolygon

            #get geometries of Ids you want to "follow" wolfFeature
            for sheep in selectedIds:
                print(" -- FID: {0}".format(str(sheep)))
                sheepFeature = activeLayer.getFeature(sheep)
                sheepGeom = sheepFeature.geometry()
                sheepCentre = sheepGeom.centroid()
                sheepX = sheepCentre.asPoint().x()
                sheepY = sheepCentre.asPoint().y()
                #sheepPoly = sheepGeom.asMultiPolygon

                #determine distance from sheep to wolf
                dX = (wolfX - sheepX)
                dY = (wolfY - sheepY)
                print("    dX/dY: ({0}, {1})".format(str(dX), str(dY)))
                #return dX,dY, sheepFeature

                #iterate through selected sheep and move once which =/= wolf
                if (dX != 0.0 or dY != 0.0):
                    print("    tryna herd these sheep")
                    sheepGeom.translate(dX, dY)
                    activeLayer.dataProvider().changeGeometryValues(
                        {sheep: sheepGeom})

        if result:
            print(stackPolygon(self))
Пример #55
0
import os.path
from qgis.PyQt.QtCore import (QLocale, QSettings, QCoreApplication,
                              QTranslator)

DEFAULT_LANGUAGE = 'en'

try:
    # Errors here could happen if the value cannot be converted to string or
    # if it is not subscriptable (see https://github.com/gacarrillor/loadthemall/issues/11)
    locale = QSettings().value("locale/userLocale", type=str)
    QGIS_LANG = str(locale[:2])
except TypeError as e:
    QGIS_LANG = DEFAULT_LANGUAGE
PLUGIN_DIR = os.path.dirname(os.path.dirname(__file__))

# Install Qt Translator
qgis_locale = QLocale(QGIS_LANG)
locale_path = os.path.join(PLUGIN_DIR, 'i18n')
translator = QTranslator()
translator.load(qgis_locale, 'Asistente-LADM-COL', '_', locale_path)
QCoreApplication.installTranslator(translator)
Пример #56
0
class OD:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'OD_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)
            
            
        self.dlg = ODDialog()
        
        self.dlg.bt_inici.clicked.connect(self.on_click_Inici)
        self.dlg.bt_sortir.clicked.connect(self.on_click_Sortir)
        self.dlg.btnCarregar.clicked.connect(self.on_click_Carregar)
        self.dlg.btnVeure.clicked.connect(self.on_click_Veure)
        self.dlg.radio_ws.toggled.connect(self.on_toggled_radio_ws)
        self.dlg.radio_geom.toggled.connect(self.on_toggled_radio_geom)
        self.dlg.radio_latlng.toggled.connect(self.on_toggled_radio_latlng)
        self.dlg.radio_nogeom.toggled.connect(self.on_toggled_radio_nogeom)
        self.dlg.checkbox_tots.stateChanged.connect(self.on_click_checkbox_tots)
        self.dlg.btnCrs.clicked.connect(self.selectcrs)
        self.dlg.btnBorrar.clicked.connect(self.on_click_Borrar)
        self.dlg.btnBorrar.setToolTip('Esborra la url seleccionada')


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&CCU')

        
        trobat=False
        for x in iface.mainWindow().findChildren(QToolBar,'CCU'): 
            self.toolbar = x
            trobat=True
        
        if not trobat:
            self.toolbar = self.iface.addToolBar('CCU')
            self.toolbar.setObjectName('CCU')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('OD', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            #self.iface.addToolBarIcon(action)
            
            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/OD/icon.png'
        self.add_action(
            icon_path,
            text='OD',
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        '''for action in self.actions:
            print(action.text())
            self.iface.removePluginMenu(
                '&OD',
                action)
            self.iface.removeToolBarIcon(action)'''
        for action in self.actions:
            self.iface.removePluginMenu('&CCU', action)
            self.toolbar.removeAction(action)


    def run(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
        self.estatInicial()
        
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
    
    def selectcrs(self):
        # Select a new CRS
        s = QSettings()
        previousselectedcrs=s.value("quickcrs/crs", 0)
        #if previousselectedcrs=="" or previousselectedcrs==0 or previousselectedcrs is None:
            #self.nocrsselected()
        global selectedcrs
        try:
            projSelector = QgsGenericProjectionSelector()
            projSelector.exec_()
            projSelector.selectedCrsId()
            selectedcrs=projSelector.selectedCrsId()
        except:
            projSelector = QgsProjectionSelectionDialog()
            projSelector.exec_()
            selectedcrsdef = projSelector.crs()
            selectedcrs=selectedcrsdef.srsid()
        if (selectedcrs=="" or selectedcrs==0 or self.CrsId2AuthID(selectedcrs)=="" or selectedcrs is None):
            #selectedcrs=previousselectedcrs
            pass
        if (selectedcrs=="" or selectedcrs==0 or self.CrsId2AuthID(selectedcrs)=="" or selectedcrs is None) and (previousselectedcrs=="" or previousselectedcrs==0 or previousselectedcrs is None):
            #self.nocrsselected()
            pass
        else:
            #self.dlg.labelselectedcrs.setText(self.CrsId2AuthID(selectedcrs))
            src=self.CrsId2AuthID(selectedcrs).replace('\n','')
            if(not self.buscarEnArchivo(src, "src.txt")):
                this_folder = os.path.dirname(os.path.abspath(__file__))
                file = open(this_folder+"/src.txt", mode='a')
                file.write('\n'+src)
                file.close()
                self.file2Combo("src.txt", self.dlg.combo_src,'')
            self.dlg.combo_src.setCurrentText(src)
        self.dlg.show()
    
    
    def CrsId2AuthID(self, crsid=0):
        toconvert = QgsCoordinateReferenceSystem()
        if crsid=="" or crsid==0 or crsid is None:
            converted=""
        else:
            toconvert.createFromId(int(crsid), QgsCoordinateReferenceSystem.InternalCrsId)
            converted=toconvert.authid()
        return converted.lower()
    
    
    
    def estatInicial(self):
        '''
        @param self:
        Resteja tots els valors per defecte del plugin: estat inicial.
        '''
        global aux
        global Versio_modul
        global lbl_Cost
        global data
        global TEMPORARY_PATH
        data=None
        aux = False
        self.dlg.progressBar.setValue(0)
        self.dlg.radio_ws.setChecked(True)
        self.dlg.radio_geom.setChecked(True)
        self.dlg.combo_lat.setEnabled(False)
        self.dlg.combo_lng.setEnabled(False)
        self.dlg.label_lat.setEnabled(False)
        self.dlg.label_lng.setEnabled(False)
        self.dlg.label_nogeom.setEnabled(False)
        self.dlg.txt_url.clear()
        self.dlg.txt_url.setPlaceholderText("Introdueix la url del Web Service")
        self.dlg.txt_nomTaula.clear()
        self.dlg.txt_nomTaula.setPlaceholderText("Introdueix el nom que apareixerà a la llegenda")
        self.dlg.text_info.clear()
        self.dlg.combo_ws.clear()
        self.dlg.combo_nom.clear()
        self.dlg.combo_geom.clear()
        self.dlg.combo_lng.clear()
        self.dlg.combo_lat.clear()
        self.dlg.combo_cod.clear()
        self.dlg.combo_src.clear()
        self.dlg.ListaCamps.clear()
        self.dlg.checkbox_tots.setChecked(False)
        self.dlg.checkBox_save.setChecked(False)
        self.dlg.setEnabled(True)
        
        
        self.file2Combo("default_ws.txt", self.dlg.combo_ws, 'Selecciona una opció')
        self.file2Combo("codificacio.txt", self.dlg.combo_cod,'')
        self.dlg.combo_cod.setCurrentText('latin1')
        self.file2Combo("src.txt", self.dlg.combo_src,'')
        
        self.dlg.versio.setText(Versio_modul)
        if (os.name=='nt'):
            TEMPORARY_PATH=os.environ['TMP']
        else:
            TEMPORARY_PATH=os.environ['TMPDIR']
        
    def buscarEnArchivo(self,target,archivo):
        '''Función para buscar una línea en un archivo'''
        this_folder = os.path.dirname(os.path.abspath(__file__))
        file = open(this_folder+'/'+archivo)        
        for line in file:
            if (line.replace('\n','')==target):
                file.close()
                return True
        file.close()
        return False
    
        
    def file2Combo(self, archivo, combo, predef):
        '''Llenar combo leyendo datos de un archivo'''
        this_folder = os.path.dirname(os.path.abspath(__file__))
        file = open(this_folder+"/"+archivo)        
        llista=[]
        if (archivo=="default_ws.txt"):
            for line in file:
                if (line.split('=',1)[0]=="url"):
                    llista.append(line.split('=',1)[1].replace('\n',''))
        else:
            for line in file:
                llista.append(line.replace('\n',''))
        file.close()
        self.ompleCombos(combo, llista, predef, True)
    
    
    def on_click_Sortir(self):
        '''
        Tanca la finestra del plugin 
        '''
        self.estatInicial()
        self.dlg.close()
        
    def on_toggled_radio_ws(self,enabled):
        """Aquesta es una funcio auxiliar que controla la visibilitat de diferents 
        elements de la interficie segons la opcio marcada"""
        if enabled:
            self.dlg.text_ws.setEnabled(True)
            self.dlg.text_url.setEnabled(False)
            self.dlg.checkBox_save.setEnabled(False)
            self.dlg.checkBox_save.setChecked(False)
            
        else:
            self.dlg.text_ws.setEnabled(False)
            self.dlg.text_url.setEnabled(True)
            self.dlg.checkBox_save.setEnabled(True)
            
    def on_toggled_radio_geom(self,enabled):
        """Aquesta es una funcio auxiliar que controla la visibilitat de diferents 
        elements de la interficie segons la opcio marcada"""
        if enabled:
            self.dlg.combo_geom.setEnabled(True)
            self.dlg.label_geom.setEnabled(True)
        else:
            self.dlg.combo_geom.setEnabled(False)
            self.dlg.label_geom.setEnabled(False)
    
    def on_toggled_radio_latlng(self,enabled):
        """Aquesta es una funcio auxiliar que controla la visibilitat de diferents 
        elements de la interficie segons la opcio marcada"""
        if enabled:
            self.dlg.combo_lat.setEnabled(True)
            self.dlg.combo_lng.setEnabled(True)
            self.dlg.label_lat.setEnabled(True)
            self.dlg.label_lng.setEnabled(True)
        else:
            self.dlg.combo_lat.setEnabled(False)
            self.dlg.combo_lng.setEnabled(False)
            self.dlg.label_lat.setEnabled(False)
            self.dlg.label_lng.setEnabled(False)
            
            
    def on_toggled_radio_nogeom(self,enabled):
        """Aquesta es una funcio auxiliar que controla la visibilitat de diferents 
        elements de la interficie segons la opcio marcada"""
        if enabled:
            self.dlg.label_nogeom.setEnabled(True)
        else:
            self.dlg.label_nogeom.setEnabled(False)
    
        
    def MouText(self):
        newCursor=QTextCursor(self.dlg.text_info.document())
        newCursor.movePosition(QTextCursor.End)
        self.dlg.text_info.setTextCursor(newCursor)
        QApplication.processEvents()
        

 
    def ompleCombos(self, combo, llista, predef, sort):
        """Aquesta funció omple els combos que li passem per paràmetres"""
        combo.blockSignals (True)
        combo.clear()
        model=QStandardItemModel(combo)
        predefInList = None
        for elem in llista:
            try:
                item = QStandardItem(str(elem))
            except TypeError:
                item = QStandardItem(str(elem))
            model.appendRow(item)
            if elem == predef:
                predefInList = elem
        combo.setModel(model)
        if predef != "":
            if predefInList:
                combo.setCurrentIndex(combo.findText(predefInList))
            else:
                combo.insertItem(0,predef)
                combo.setCurrentIndex(0)
        combo.blockSignals (False)
            
            
    def on_click_checkbox_tots(self, state):
        if state == QtCore.Qt.Checked:
            self.dlg.ListaCamps.selectAll()
            self.dlg.ListaCamps.setFocus()
        else:
            self.dlg.ListaCamps.clearSelection()
        
        
    def on_click_Borrar(self):
        if self.dlg.combo_ws.currentText() != 'Selecciona una opció' and self.dlg.combo_ws.currentText() != '':
            reply = QMessageBox.question(None, "Advertència", "Segur que vols eliminar aquesta URL de predeterminats?", QMessageBox.Ok | QMessageBox.Cancel)
            
            if reply==QMessageBox.Ok:
                this_folder = os.path.dirname(os.path.abspath(__file__))   
                file = open(this_folder+'/default_ws.txt') 
                cont=0
                strToWrite = ''
                for line in file:
                    if (line.split('=',1)[1].replace('\n','')==self.dlg.combo_ws.currentText()):
                        cont+=1
                    elif (cont>=1 and cont<=6):
                        cont+=1
                    else:
                        strToWrite+=line
                file.close()
                file = open(this_folder+'/default_ws.txt', "w")
                file.write(strToWrite)
                file.close()
                
                self.file2Combo("default_ws.txt", self.dlg.combo_ws, 'Selecciona una opció')
        
        
    def on_click_Carregar(self):
        global data
        global listFields
        global urlToLoad
        
        self.dlg.setEnabled(False)
        self.dlg.combo_nom.clear()
        self.dlg.combo_geom.clear()
        self.dlg.combo_lat.clear()
        self.dlg.combo_lng.clear()
        self.dlg.checkbox_tots.setChecked(False)
        urlToLoad = self.dlg.txt_url.text()
        
        error = self.loadCSV(self.dlg.combo_nom.currentText(), self.dlg.combo_geom.currentText(), self.dlg.combo_cod.currentText(), False)
        if (error=="Error"):
            self.dlg.setEnabled(True)
            return

        '''else:
            error = self.loadURL(self.dlg.combo_nom.currentText(), self.dlg.combo_geom.currentText(), False)
            if (error=="Error"):
                self.dlg.setEnabled(True)
                return
            self.loadFields()'''
            
        self.ompleCombos(self.dlg.combo_nom, listFields, 'Selecciona un nom', True)
        self.ompleCombos(self.dlg.combo_geom, listFields, 'Selecciona una geometria', True)
        self.ompleCombos(self.dlg.combo_lat, listFields, 'Selecciona una latitud', True) 
        self.ompleCombos(self.dlg.combo_lng, listFields, 'Selecciona una longitud', True)  
        self.cercaCamps()
        self.dlg.setEnabled(True)

    
    
    def loadCSV(self,nom,geom, campCod, predeterminat):
        '''Función para guardar un CSV de una url en una variable'''
        global listFields
        global textBox
        global urlCargada
        global urlToLoad
        global data
        global TEMPORARY_PATH
        
        urlCargada = False
        
        self.dlg.combo_nom.clear()
        self.dlg.combo_geom.clear()
        self.dlg.combo_lat.clear()
        self.dlg.combo_lng.clear()
        self.dlg.ListaCamps.clear()
        
        
        self.dlg.progressBar.setValue(50) 
        textBox = u'Accedint a la url '+urlToLoad+'\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()

        '''Se descarga el CSV y se guarda en una carpeta temporal'''
        filename = TEMPORARY_PATH+"/WS.csv"
        try:
            self.download_file(urlToLoad, filename)
        except Exception as ex:
            missatge="La URL no és vàlida"
            if (type(ex).__name__=='ConnectTimeout'):
                missatge="Time out esgotat" 
            print (missatge)
            template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print (message)
            QMessageBox.information(None, "Error", missatge)
            self.dlg.text_info.setText('')
            self.dlg.progressBar.setValue(0)
            return "Error"
        
            
        self.dlg.progressBar.setValue(80)
        textBox += u'Detectant camps...\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()
        
        '''Se extraen los nombres de campo del CSV'''
        try:
            data=[]
            with open(filename, newline='', encoding=campCod) as f:
                reader = csv.reader(f)
                for row in reader:
                    data.append(row)
                    break;
                
            listFields = data[0]
        except Exception as ex:
            missatge="La codificació seleccionada no és correcte"
            print (missatge)
            template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print (message)
            QMessageBox.information(None, "Error", missatge)
            self.dlg.text_info.setText('')
            self.dlg.progressBar.setValue(0)
            return "Error"
        self.dlg.progressBar.setValue(0)
        textBox += u'Informació obtinguda del CSV\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()
        urlCargada=not predeterminat
        return
        
        
    def download_file(self, url, filename):
        '''Función para descargar el archivo de la url y guardarlo con el filename'''
        response = requests.get(url,timeout=20)
        # Se comprueba si la respuesta es ok (200)
        if response.status_code == 200:
            with open(filename, 'wb') as file:
                for chunk in response:
                    file.write(chunk)
        
        
     
    
    def on_click_Veure(self):
        '''Función para visualizar la url en el navegador predeterminado del SO'''
        webbrowser.open_new(self.dlg.txt_url.text())
            
            
    def searchNomGeomCodSrcInFile(self):
        '''Función que devuelve los valores de nombre, geometría, codificación y src de la url predeterminada que se está consultando.
        Dichos valores están guardados en un fichero llamado default_ws.txt, localizado en la raíz del proyecto'''
        this_folder = os.path.dirname(os.path.abspath(__file__))
        file = open(this_folder+"/default_ws.txt") 
        nom=None
        geometria=None  
        cod=None
        src=None     
        cont=0
        for line in file:
            if (line.split('=',1)[1].replace('\n','')==self.dlg.combo_ws.currentText()):
                cont+=1
            elif (cont==1):
                nom = line.split('=')[1].replace('\n','')
                cont+=1
            elif (cont==2):
                geometria = line.split('=',1)[1].replace('\n','')
                cont+=1
            elif (cont==3):
                lat = line.split('=',1)[1].replace('\n','')
                cont+=1
            elif (cont==4):
                lng = line.split('=',1)[1].replace('\n','')
                cont+=1
            elif (cont==5):
                cod = line.split('=',1)[1].replace('\n','')
                cont=cont+1
            elif (cont==6):
                src = line.split('=',1)[1].replace('\n','')
                break
        file.close()     
        return(nom,geometria, lat, lng,cod,src)
    
    
    def controlErrorsInput(self):
        '''
        Aquesta funció s'encarrega de controlar que quan comenci el càlcul
        totes les entrades de dades estiguin omplertes i siguin correctes
        '''
        global urlCargada
        errors = []
        
        if self.dlg.txt_nomTaula.text() == '':
            errors.append('No hi ha cap nom')
        if self.dlg.radio_ws.isChecked():
            if self.dlg.combo_ws.currentText() == 'Selecciona una opció':
                errors.append('No hi ha cap Web Service seleccionat')
        else:
            if not urlCargada:
                errors.append('No hi ha cap URL carregada')
            if self.dlg.combo_nom.currentText() == 'Selecciona un nom' or self.dlg.combo_nom.currentText() == '':
                errors.append('No hi ha cap "Camp nom" seleccionat')
            if self.dlg.radio_geom.isChecked():
                if self.dlg.combo_geom.currentText() == 'Selecciona una geometria' or self.dlg.combo_geom.currentText() == '':
                    errors.append('No hi ha cap camp de geometria seleccionat')
            elif not self.dlg.radio_nogeom.isChecked():
                if self.dlg.combo_lat.currentText() == 'Selecciona una latitud' or self.dlg.combo_lat.currentText() == '':
                    errors.append('No hi ha cap camp de latitud seleccionat')
                if self.dlg.combo_lng.currentText() == 'Selecciona una longitud' or self.dlg.combo_lng.currentText() == '':
                    errors.append('No hi ha cap camp de longitud seleccionat')
        return errors
    
    def cercaCamps(self):
        """Esta función llena la LlistaCamps de los nombres de los campos obtenidos"""
        global listFields
        self.dlg.ListaCamps.clear()
        
        for field in listFields:
            self.dlg.ListaCamps.addItem(field)
            
        
    
    def comprobarValidez(self,vlayer):        
        #processing.algorithmHelp("native:shortestpathpointtolayer")
        parameters= {'ERROR_OUTPUT' : 'memory:',
                     'INPUT_LAYER' : vlayer,
                     'INVALID_OUTPUT' : 'memory:',
                     'METHOD' : 1,
                     'VALID_OUTPUT' : 'memory:'}
        
        result = processing.run('qgis:checkvalidity',parameters)
        
        return result['VALID_OUTPUT']

    
    def getIndexOfField(self,vlayer,field):
        '''Función para obtener el índice de un campo de un vlayer'''
        fields = vlayer.fields()
        for x in range(len(fields)):
            if(fields[x].displayName()==field):
                return x
        return -1
    
    def on_click_Inici(self):
        global lbl_Cost
        global data
        global listFields
        global urlToLoad
        global TEMPORARY_PATH
    
        self.dlg.setEnabled(False)
        '''Tratamiento de errores'''
        llistaErrors = self.controlErrorsInput()
        if len(llistaErrors) > 0:
            llista = "Llista d'errors:\n\n"
            for i in range (0,len(llistaErrors)):
                llista += ("- "+llistaErrors[i] + '\n')
            QMessageBox.information(None, "Error", llista)
            self.dlg.setEnabled(True)
            return
        
        
        textBox = u'INICI DEL PROCÉS\n\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()
        campNom = ''
        campGeometria = ''
        campCod = ''
        campSrc = ''
        campLat = ''
        campLng = ''
        
        
        '''Obtención de Nom y Geometria'''
        if self.dlg.radio_ws.isChecked():
            campNom,campGeometria,campLat, campLng, campCod,campSrc=self.searchNomGeomCodSrcInFile()
            urlToLoad=self.dlg.combo_ws.currentText()
            #if(urlToLoad[-4:]=='.csv'):
            error = self.loadCSV(campNom, campGeometria, campCod,True)
            if (error=="Error"):
                self.dlg.setEnabled(True)
                return
    
        else:
            campNom = self.dlg.combo_nom.currentText()
            campCod=self.dlg.combo_cod.currentText()
            campSrc=self.dlg.combo_src.currentText()   
            if self.dlg.radio_geom.isChecked():
                campGeometria = self.dlg.combo_geom.currentText()
            elif self.dlg.radio_latlng.isChecked():
                campLat=self.dlg.combo_lat.currentText()
                campLng=self.dlg.combo_lng.currentText()
        
        '''Creación vector layer'''
        self.dlg.progressBar.setValue(60)
        textBox += u'Generant capa vectorial...\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()
        if campGeometria != '':
            file = 'file:///'+TEMPORARY_PATH+'/WS.csv?encoding=%s&delimiter=%s&wktField=%s&crs=%s' % (campCod,",", campGeometria,campSrc)
        elif campLat != '' and campLng != '':
            file = 'file:///'+TEMPORARY_PATH+'/WS.csv?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s' % (campCod,",", campLng, campLat,campSrc)
        else:
            file = 'file:///'+TEMPORARY_PATH+'/WS.csv?encoding=%s&delimiter=%s' % (campCod,",")  
        vlayergeom = QgsVectorLayer(file, self.dlg.txt_nomTaula.text(),'delimitedtext')
        try:
            vlayergeom = self.comprobarValidez(vlayergeom) #Sirve tanto para comprobar la corrección del CSV como para pasar el layer a memoria
        except Exception as ex:
            missatge="La geometria seleccionada no és correcte"
            print (missatge)
            template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print (message)
            QMessageBox.information(None, "Error", missatge)
            self.dlg.text_info.setText('')
            self.dlg.progressBar.setValue(0)
            self.dlg.setEnabled(True)
            return "Error"
        vlayergeom.setName(self.dlg.txt_nomTaula.text())
               
        self.dlg.progressBar.setValue(80)
        textBox += u'Adaptant camps...\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()
        
        '''Se renombra el campo de nombre y se añade un id'''
        vlayergeom.startEditing()
        fields = vlayergeom.fields()
        for x in range(len(fields)):
            if(campNom in fields[x].displayName()):
                vlayergeom.renameAttribute(x,'Nom')
                break;
        vlayergeom.addAttribute(QgsField('id', QVariant.Int))
        vlayergeom.commitChanges()
        
        '''Se autonumera el id'''
        features = vlayergeom.getFeatures()
        vlayergeom.startEditing()
        x=1
        for feature in features:
            vlayergeom.changeAttributeValue(feature.id(),self.getIndexOfField(vlayergeom,"id"),x)
            x=x+1
        vlayergeom.commitChanges()
           
        
        '''Se borran los campos no seleccionados''' 
        if not self.dlg.radio_ws.isChecked():
            llista_sel=[]    
            if (len(self.dlg.ListaCamps.selectedItems())>0):
                for item in self.dlg.ListaCamps.selectedItems():
                    llista_sel.append(item.text())
            
            vlayergeom.startEditing()
            for elem in listFields:
                if elem not in llista_sel:
                    vlayergeom.deleteAttribute(self.getIndexOfField(vlayergeom,elem))
            
            vlayergeom.commitChanges()
       
       
        '''Se representa en pantalla'''
        QgsProject.instance().addMapLayer(vlayergeom,False)
        root = QgsProject.instance().layerTreeRoot()
        myLayerNode=QgsLayerTreeLayer(vlayergeom)
        root.insertChildNode(0,myLayerNode)
        myLayerNode.setCustomProperty("showFeatureCount", True)
        
        
        if self.dlg.checkBox_save.isChecked():
            this_folder = os.path.dirname(os.path.abspath(__file__))   
            '''UPDATE'''
            file = open(this_folder+'/default_ws.txt') 
            cont=0
            strToWrite = ''
            for line in file:
                if (line.split('=',1)[1].replace('\n','')==self.dlg.txt_url.text()):
                    cont+=1
                    strToWrite+= line
                elif (cont==1):
                    cont+=1
                    strToWrite+= 'nom='+campNom+'\n'
                elif (cont==2):
                    cont+=1
                    if self.dlg.radio_geom.isChecked():
                        strToWrite+= 'geom='+campGeometria+'\n'
                    else:
                        strToWrite+='geom=\n'
                elif (cont==3):
                    cont+=1
                    if self.dlg.radio_latlng.isChecked():
                        strToWrite+= 'lat='+campLat+'\n'
                    else:
                        strToWrite+='lat=\n'
                elif (cont==4):
                    cont+=1
                    if self.dlg.radio_latlng.isChecked():
                        strToWrite+= 'lng='+campLng+'\n'
                    else:
                        strToWrite+='lng=\n'
                elif (cont==5):
                    cont+=1
                    strToWrite+= 'cod='+campCod+'\n'
                elif (cont==6):
                    cont+=1
                    strToWrite+= 'src='+campSrc+'\n'
                else:
                    strToWrite+=line
            file.close()
            file = open(this_folder+'/default_ws.txt', "w")
            file.write(strToWrite)
            file.close()    
            
            '''APEND'''
            if cont == 0:
                strToAppend = '\nurl='+self.dlg.txt_url.text()
                strToAppend += '\nnom='+campNom
                if self.dlg.radio_geom.isChecked():
                    strToAppend += '\ngeo='+campGeometria
                else:
                    strToAppend += '\ngeo='
                if self.dlg.radio_latlng.isChecked():
                    strToAppend += '\nlat='+campLat
                    strToAppend += '\nlng='+campLng
                else:
                    strToAppend += '\nlat='
                    strToAppend += '\nlng='
                strToAppend += '\ncod='+campCod
                strToAppend += '\nsrc='+campSrc
                file = open(this_folder+'/default_ws.txt', "a")
                file.write(strToAppend)
                file.close()
            
            
            self.file2Combo("default_ws.txt", self.dlg.combo_ws, 'Selecciona una opció')
            
        
        self.dlg.progressBar.setValue(100)
        textBox += u'\nProcés finalitzat.\n'
        self.dlg.text_info.setText(textBox)
        self.MouText()
        self.dlg.setEnabled(True)

    def createVlayer(self, listFields,campSrc):
        '''Función para crear el vlayer con un campo de id, un campo de nom, los campos pasados por el parámetro lisFields y el parámetro campSrc para crear la geometría'''
        vlayer = QgsVectorLayer("Point?crs="+campSrc, self.dlg.txt_nomTaula.text(), "memory")
        
        vlayer.startEditing()
        vlayer.addAttribute(QgsField('id', QVariant.Int))
        vlayer.addAttribute(QgsField('Nom', QVariant.String))
        for x in range(len(listFields)):
            vlayer.addAttribute(QgsField(listFields[x], QVariant.String))
        vlayer.commitChanges()
        return vlayer
    
    
    def fillVlayer(self, llistaFeatures, llistaCamps, vlayer, campNom, campGeometria,campLng,campLat):
        '''Función para llenar un vlayer vació con la lista de features y fields que se pasen por parámetro, siendo necesario indicar el nombre de campNom
        y, por otra parte, indicar el campo de geometría o los de longitud y latitud.'''
        for x in range(len(llistaFeatures)):
            try:
                if self.dlg.radio_geom.isChecked():
                    coordinates = llistaFeatures[x][campGeometria].replace("POINT ","")
                    xCoord = coordinates.split(" ")[0][1:]
                    yCoord = coordinates.split(" ")[1][:-1]
                else:
                    xCoord = llistaFeatures[x][campLng]
                    yCoord = llistaFeatures[x][campLat]
                feature = QgsFeature()
                feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(float(xCoord),float(yCoord))))
            except Exception as ex:
                missatge="El camp de geometria no és correcte"
                print (missatge)
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(ex).__name__, ex.args)
                print (message)
                QMessageBox.information(None, "Error", missatge)
                self.dlg.text_info.setText('')
                self.dlg.progressBar.setValue(0)
                return "Error"
            
            values=[]
            values.append(QVariant(x))
            values.append(QVariant(str(llistaFeatures[x][campNom])))
            for y in range(len(llistaCamps)):
                if(llistaCamps[y]!='id' and llistaCamps[y]!=campNom and llistaCamps[y]!=campGeometria):
                    if llistaCamps[y] in llistaFeatures[x]:
                        values.append(QVariant(str(llistaFeatures[x][llistaCamps[y]])))
                    else:
                        values.append(QVariant(str('')))           
            
            feature.setAttributes(values)
            vlayer.startEditing()
            vlayer.addFeature(feature)
            vlayer.commitChanges()
        return vlayer
Пример #57
0
class ShipPlotter:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ShipPlotter_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Ship Plotter')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # 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('ShipPlotter', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(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/ship_plotter/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u''),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Ship Plotter'), action)
            self.iface.removeToolBarIcon(action)

    def run(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.dlg = ShipPlotterDialog()

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            lineedit_minlat = self.dlg.lineedit_minlat.value()
            lineedit_maxlat = self.dlg.lineedit_maxlat.value()
            lineedit_minlog = self.dlg.lineedit_minlog.value()
            lineedit_maxlog = self.dlg.lineedit_maxlog.value()
            base_url = 'https://services.marinetraffic.com/api/exportvessels/v:7/'

            params = {
                "MINLAT": lineedit_minlat,
                "MAXLAT": lineedit_maxlat,
                "MINLON": lineedit_minlog,
                "MAXLON": lineedit_maxlog,
                "timespan": 10,
                "protocol": 'json'
            }

            response = requests.get(url=base_url, params=params)
            response_json = response.json()

            if response.status_code == 200:
                if response_json.get('error'):
                    QMessageBox.critical(
                        self.iface.mainWindow(), "The API Error",
                        "The buy request was not processsed succesfully\n\n"
                        "Message:\n"
                        "{}".format(response.json()))
                    return

                print(response)

                # Capture relevant response fields
                x = float(response_json['lon'])
                y = float(response_json['lat'])
                address = response_json['display_name']
                license = response_json['licence']
Пример #58
0
    def __init__(self, iface):

        self.iface = iface

        # Initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # Initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        locale_path = os.path.join(
            self.plugin_dir, "i18n", "{0}Plugin_{1}.qm".format(PE, locale)
        )

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr("&{0}".format(P_E))
        self.toolbar = None

        # noinspection PyTypeChecker
        self.explorer_dock_widget = None
        self._terms_browser = None

        if is_segments_write_key_valid():
            analytics.write_key = segments_write_key()
        if is_sentry_dsn_valid():
            try:
                sentry_sdk.init(sentry_dsn(), release=plugin_version(True))
                sentry_sdk.set_context(
                    "qgis",
                    {
                        "type": "runtime",
                        "name": Qgis.QGIS_RELEASE_NAME,
                        "version": Qgis.QGIS_VERSION,
                    },
                )
                system = platform.system()
                if system == "Darwin":
                    sentry_sdk.set_context(
                        "mac",
                        {
                            "type": "os",
                            "name": "macOS",
                            "version": platform.mac_ver()[0],
                            "kernel_version": platform.uname().release,
                        },
                    )
                if system == "Linux":
                    sentry_sdk.set_context(
                        "linux",
                        {
                            "type": "os",
                            "name": "Linux",
                            "version": platform.release(),
                            "build": platform.version(),
                        },
                    )
                if system == "Windows":
                    sentry_sdk.set_context(
                        "windows",
                        {
                            "type": "os",
                            "name": "Windows",
                            "version": platform.version(),
                        },
                    )
            except Exception:
                QMessageBox.warning(
                    self.iface.mainWindow(),
                    "Error",
                    "Error initializing Planet Explorer.\n"
                    "Please restart QGIS to load updated libraries.",
                )

        self.qgis_hook = sys.excepthook

        def plugin_hook(t, value, tb):
            trace = "".join(traceback.format_exception(t, value, tb))
            if PLUGIN_NAMESPACE in trace.lower():
                s = ""
                if issubclass(t, exceptions.Timeout):
                    s = "Connection to Planet server timed out."
                elif issubclass(t, exceptions.ConnectionError):
                    s = (
                        "Connection error.\n Verify that your computer is correctly"
                        " connected to the Internet"
                    )
                elif issubclass(t, (exceptions.ProxyError, exceptions.InvalidProxyURL)):
                    s = (
                        "ProxyError.\n Verify that your proxy is correctly configured"
                        " in the QGIS settings"
                    )
                elif issubclass(t, planet.api.exceptions.ServerError):
                    s = "Server Error.\n Please, try again later"
                elif issubclass(t, urllib3.exceptions.ProxySchemeUnknown):
                    s = (
                        "Proxy Error\n Proxy URL must start with 'http://' or"
                        " 'https://'"
                    )

                if s:
                    QMessageBox.warning(self.iface.mainWindow(), "Error", s)
                else:
                    try:
                        sentry_sdk.capture_exception(value)
                    except Exception:
                        pass  # we swallow all exceptions here, to avoid entering an endless loop
                    self.qgis_hook(t, value, tb)
            else:
                self.qgis_hook(t, value, tb)

        sys.excepthook = plugin_hook
Пример #59
0
class Qchainage(object):
    """Main class for Chainage
    """
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale_path = ""
        locale = QSettings().value("locale/userLocale")[0:2]

        if QFileInfo(self.plugin_dir).exists():
            locale_path = self.plugin_dir + "/i18n/qchainage_" + locale + ".qm"

        if QFileInfo(locale_path).exists():
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        """Initiate GUI
        """
        # Create action that will start plugin configuration
        self.action = QAction(
            QIcon(":/plugins/qchainage/img/qchainage.png"),
            u"QChainage", self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToVectorMenu(u"&QChainage", self.action)

    def unload(self):
        """ Unloading the plugin
        """
        # Remove the plugin menu item and icon
        self.iface.removePluginVectorMenu(u"&QChainage", self.action)
        self.iface.removeToolBarIcon(self.action)

    def run(self):
        """ Running the plugin
        """
        #otf = self.iface.mapCanvas().mapRenderer().hasCrsTransformEnabled()
        #if otf:
        #    message = "There might be wrong results with OTF switched on." \
        #              "Please switch it off and chainage the layer you want to"
        #    show_warning(self, message)
        leave = -1

        for layer in self.iface.mapCanvas().layers():
            if layer.type() == QgsMapLayer.VectorLayer and \
               layer.geometryType() == QgsWkbTypes.LineGeometry:
                leave += 1

        if leave < 0:
            message = "No layers with line features - chainage not useful!"
            show_warning(self, message)
            return
        # show the dialog
        dialog = QChainageDialog(self.iface)
        # Run the dialog event loop
        result = dialog.exec_()
        # See if OK was pressed
        if result == 1:
            # do something useful (delete the line containing pass and
            # substitute with your code)
            pass
Пример #60
0
class finddata:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'finddata_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&finddata')
        self.toolbar = self.iface.addToolBar(u'finddata')
        self.toolbar.setObjectName(u'finddata')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

        self.search_folder = ""

        self.file_log = ""              #Log file
        self.file_csv = ""              # output csv file



    # 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('finddata', 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):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        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:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action


    def search_vector_data(self):
        data_vector = ['shp', 'mif', 'mid']

        search_folder = self.search_folder

        # add to log
        self.dlg.lvLog.addItem("Starting at: ")
        self.dlg.lvLog.addItem(search_folder)



        numRows = self.dlg.tableWidget.rowCount()
        # Create a empty row at bottom of table
        #numRows = self.dlg.tableWidget.rowCount()
        #self.dlg.tableWidget.insertRow(numRows)
        #self.dlg.tableWidget.show()
        # Add text to the row

        try:
            for root, subdirs, files in os.walk(search_folder):
                for file in os.listdir(root):
                    file_path = str(os.path.join(root, file))
                    if os.path.isfile(file_path):
                        numRows = self.dlg.tableWidget.rowCount()
                        self.dlg.tableWidget.insertRow(numRows)

                        # .lower() - под линуксом есть разница!!!
                        # ext = '.'.join(file.split('.')[1:]).lower()
                        file_name = file # .lower()
                        print(file_name)
                        # file_ext = self.get_extension(file)
                        ext = '.'.join(file.split('.')[1:]).lower()
                        # 'shx','shp'
                        self.dlg.lvLog.addItem(ext)
                        self.dlg.tableWidget.setItem(numRows, 0, QtWidgets.QTableWidgetItem(file_name))
                        self.dlg.tableWidget.setItem(numRows, 1, QtWidgets.QTableWidgetItem(ext))
                        self.dlg.tableWidget.setItem(numRows, 2, QtWidgets.QTableWidgetItem("size"))
                        self.dlg.tableWidget.setItem(numRows, 3, QtWidgets.QTableWidgetItem("file_name"))
                        self.dlg.tableWidget.setItem(numRows, 4, QtWidgets.QTableWidgetItem("cdata"))
                        self.dlg.tableWidget.setItem(numRows, 5, QtWidgets.QTableWidgetItem("mdata"))
                        self.dlg.tableWidget.setItem(numRows, 6, QtWidgets.QTableWidgetItem("ladata"))
                        self.dlg.tableWidget.setItem(numRows, 7, QtWidgets.QTableWidgetItem(file_path))
                        self.dlg.tableWidget.setItem(numRows, 8, QtWidgets.QTableWidgetItem("npath"))
                        self.dlg.tableWidget.setHorizontalHeaderItem(2, QtWidgets.QTableWidgetItem())
                        # if os.path.isfile(file_path) :  # and file_name.startswith('info.doc')      #ext == "csv":
                        #     self.dlg.lvLog.addItem(file_path)

                            #listdir.append(file_path)
        except Exception as e:
            ss = "Exception occurred search_vector_data" + str(e)
            print(ss)
            self.dlg.lvLog.addItem(ss)

        QMessageBox.information(None, "Info!", "Done!")
        pass

    def get_extension(filename=''):
        basename = os.path.basename(filename)  # os independent
        ext = '.'.join(basename.split('.')[1:])
        return str('' + ext if ext else '').lower()

    def select_root_folder(self):
        foldername = QFileDialog.getExistingDirectory(self.dlg, "Select folder ","",)
        #print("select_root_folder(self)")
        if os.path.exists(foldername):
            self.dlg.edtFolder.setText(foldername)
            self.search_folder = foldername
            self.search_vector_data()




    def search_spatial_data(self):
        root_folder = self.dlg.edtFolder.displayText()
        if root_folder == '':
            QMessageBox.information(None, "Warning!", "No root folder selected. Please select a folder.")
            return
        else:
            QMessageBox.information(None, "Warning!", root_folder)



    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/finddata/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'finddata'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&finddata'),
                action)
            self.iface.removeToolBarIcon(action)


    def run(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.dlg = finddataDialog()

        # self.dlg.tableWidget.columnCount()
        # Set column headers
        self.dlg.tableWidget.setHorizontalHeaderItem(0, QtWidgets.QTableWidgetItem("filename"))
        self.dlg.tableWidget.setHorizontalHeaderItem(1, QtWidgets.QTableWidgetItem("ext"))
        self.dlg.tableWidget.setHorizontalHeaderItem(2, QtWidgets.QTableWidgetItem("size"))
        self.dlg.tableWidget.setHorizontalHeaderItem(3, QtWidgets.QTableWidgetItem("hsize"))
        self.dlg.tableWidget.setHorizontalHeaderItem(4, QtWidgets.QTableWidgetItem("cdata"))
        self.dlg.tableWidget.setHorizontalHeaderItem(5, QtWidgets.QTableWidgetItem("mdata"))
        self.dlg.tableWidget.setHorizontalHeaderItem(6, QtWidgets.QTableWidgetItem("ladata"))
        self.dlg.tableWidget.setHorizontalHeaderItem(7, QtWidgets.QTableWidgetItem("fpath"))
        self.dlg.tableWidget.setHorizontalHeaderItem(8, QtWidgets.QTableWidgetItem("npath"))


        self.dlg.edtFolder.clear()
        #self.dlg

        # signals
        self.dlg.btnSelectFolder.pressed.connect(self.select_root_folder)
        self.dlg.btnApply.pressed.connect(self.search_spatial_data)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            pass