def open_settings_dialog(self):
        # open a dialog with settings
        dialog = SettingsDialog(self, self.profilecon)
        dialog.exec()

        # update settings
        self.configure_plot()
Exemplo n.º 2
0
 def setting(self):
   from settingsdialog import SettingsDialog
   dialog = SettingsDialog(self.iface.mainWindow())
   dialog.show()
   if dialog.exec_():
     from pluginmanager import PluginManager
     self.pluginManager = PluginManager()
Exemplo n.º 3
0
 def openSettings(self):
     # button signals in SettingsDialog were not working on Win7/64
     # if SettingsDialog was created with iface.mainWindow() as parent
     #self.settingsDialog = SettingsDialog(self.iface.mainWindow())
     self.settingsDialog = SettingsDialog()
     self.settingsDialog.changed.connect(self.spline.settingsChanged)
     self.settingsDialog.show()
Exemplo n.º 4
0
    def pluginSettings(self):
        from settingsdialog import SettingsDialog

        dialog = SettingsDialog(self)
        if dialog.exec_():
            self.pluginManager.reloadPlugins()
            self.pages[ppages.PAGE_DEM].initLayerComboBox()
Exemplo n.º 5
0
 def setting(self):
     from settingsdialog import SettingsDialog
     dialog = SettingsDialog(self.iface.mainWindow())
     dialog.show()
     if dialog.exec_():
         from pluginmanager import PluginManager
         self.pluginManager = PluginManager()
Exemplo n.º 6
0
    def settings(self):
      oldMoveToLayer = QSettings().value("/TileLayerPlugin/moveToLayer", 0, type=int)

      from settingsdialog import SettingsDialog
      dialog = SettingsDialog(self.iface)
      accepted = dialog.exec_()
      if not accepted:
        return False
      self.downloadTimeout = dialog.ui.spinBox_downloadTimeout.value()
      self.navigationMessagesEnabled = dialog.ui.checkBox_NavigationMessages.checkState()

      moveToLayer = dialog.ui.checkBox_MoveToLayer.checkState()
      if moveToLayer != oldMoveToLayer:
        if oldMoveToLayer:
          self.iface.layerToolBar().removeAction(self.action)
          self.iface.removeAddLayerAction(self.action)
        else:
          self.iface.removePluginWebMenu(self.pluginName, self.action)

        if moveToLayer:
          self.iface.insertAddLayerAction(self.action)
          self.iface.layerToolBar().addAction(self.action)
        else:
          self.iface.addPluginToWebMenu(self.pluginName, self.action)
      return True
Exemplo n.º 7
0
    def settings(self):
        oldMoveToLayer = QSettings().value("/TileLayerPlugin/moveToLayer",
                                           0,
                                           type=int)

        from settingsdialog import SettingsDialog
        dialog = SettingsDialog(self.iface)
        accepted = dialog.exec_()
        if not accepted:
            return False
        self.downloadTimeout = dialog.ui.spinBox_downloadTimeout.value()
        self.navigationMessagesEnabled = dialog.ui.checkBox_NavigationMessages.checkState(
        )

        moveToLayer = dialog.ui.checkBox_MoveToLayer.checkState()
        if moveToLayer != oldMoveToLayer:
            if oldMoveToLayer:
                self.iface.layerToolBar().removeAction(self.action)
                self.iface.removeAddLayerAction(self.action)
            else:
                self.iface.removePluginWebMenu(self.pluginName, self.action)

            if moveToLayer:
                self.iface.insertAddLayerAction(self.action)
                self.iface.layerToolBar().addAction(self.action)
            else:
                self.iface.addPluginToWebMenu(self.pluginName, self.action)
        return True
Exemplo n.º 8
0
 def settings(self):
     from settingsdialog import SettingsDialog
     dialog = SettingsDialog(self.iface)
     dialog.show()
     accepted = dialog.exec_()
     if accepted:
         self.downloadTimeout = dialog.ui.spinBox_downloadTimeout.value()
         self.navigationMessagesEnabled = dialog.ui.checkBox_NavigationMessages.checkState(
         )
Exemplo n.º 9
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
        super(EarthMineQGIS, self).__init__()
        self.movingfeature = None
        self.iface = iface
        self.viewer = None
        self.canvas = self.iface.mapCanvas()
        self.settings = QSettings()
        # 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',
                                   'EarthMineQGIS_{}.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.pointtool = QgsMapToolEmitPoint(self.canvas)
        self.pointtool.canvasClicked.connect(self.set_viewer_location)

        self.settingsdialog = SettingsDialog(self.iface.mainWindow())

        self.actions = []
        self.menu = self.tr(u'&Earthmine')

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

        self.legend = self.iface.legendInterface()

        emcolor = QColor(1, 150, 51)
        self.tempband = QgsRubberBand(self.canvas, QGis.Line)
        self.tempband.setWidth(5)
        self.tempband.setColor(emcolor)

        self.tempbandpoints = QgsRubberBand(self.canvas, QGis.Point)
        self.tempbandpoints.setWidth(7)
        self.tempbandpoints.setColor(emcolor)

        self.movingband = QgsRubberBand(self.canvas, QGis.Point)
        self.movingband.setWidth(5)
        self.movingband.setColor(emcolor)

        self.layersignals = []
        self.marker = None
Exemplo n.º 10
0
    def settings_button_clicked(self):
        s = SettingsDialog(self)
        
        ret = s.exec_()
    
        if ret == 1:
            Settings.save(s.settings)

            self.settings = Settings.read()
            
            self.refresh_shortcuts()
Exemplo n.º 11
0
    def settings_button_clicked(self):
        s = SettingsDialog(self)

        ret = s.exec_()

        if ret == 1:
            Settings.save(s.settings)

            self.settings = Settings.read()

            self.refresh_shortcuts()
Exemplo n.º 12
0
    def settingsDialog(self):
        dlg = SettingsDialog(self.theme, self.palette().highlight().color().name(), parent=self)
        dlg.exec()
        if dlg.theme != self.theme or dlg.hilite_color != self.palette().highlight().color().name():
            settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName())
            settings.setValue("theme", dlg.theme)
            settings.setValue("hiliteColor", dlg.hilite_color)

            msgBox = QMessageBox()
            msgBox.setText("Please restart the app to change the theme!")
            msgBox.exec()
Exemplo n.º 13
0
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        self.dlgSettings = SettingsDialog()

        self.digitizingSetup = DigitizingSetup(self.iface)
        self.currentMode = None
        self.currentLayer = None
        self.isBackgroundSnapping = False

        self.initSettings()
Exemplo n.º 14
0
class SplinePlugin:
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # There is bug in SIP (Transfer of QgsMapRenderer)
        # http://lists.osgeo.org/pipermail/qgis-developer/2013-December/029816.html
        # so we have to keep reference to QgsMapRenderer
        self.mapRenderer = iface.mapCanvas().mapRenderer()

        # 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',
                                  'splineplugin_{}.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):
        self.settingsAction = QAction(
            QCoreApplication.translate("Spline", "Settings"),
            self.iface.mainWindow())
        self.settingsAction.setObjectName("splineAction")
        self.settingsAction.triggered.connect(self.openSettings)

        self.iface.addPluginToVectorMenu(u"Digitize Spline",
                                         self.settingsAction)

        self.spline = SplineTool(self.iface)

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginVectorMenu(u"Digitize Spline",
                                          self.settingsAction)
        del self.spline  # removes its action from toolbar

    def run(self):
        pass

    def openSettings(self):
        # button signals in SettingsDialog were not working on Win7/64
        # if SettingsDialog was created with iface.mainWindow() as parent
        #self.settingsDialog = SettingsDialog(self.iface.mainWindow())
        self.settingsDialog = SettingsDialog()
        self.settingsDialog.changed.connect(self.spline.settingsChanged)
        self.settingsDialog.show()
Exemplo n.º 15
0
 def openSettings(self):
     """Open settings dialog and reload settings"""
     settingsDialog = SettingsDialog(self.settings)
     settingsDialog.exec_()
     if self.settings["theme"] == "dark":
         self.dark_theme = True
         self.darkstyle = self.genDarkStyle()
         self.style = self.darkstyle
     else:
         self.dark_theme = False
         self.style = self.def_style
     #self.app.setStyleSheet("")
     self.app.setStyleSheet(self.style)
     self.resizeElements()
Exemplo n.º 16
0
class SplinePlugin:

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

        # There is bug in SIP (Transfer of QgsMapRenderer) 
        # http://lists.osgeo.org/pipermail/qgis-developer/2013-December/029816.html
        # so we have to keep reference to QgsMapRenderer
        self.mapRenderer = iface.mapCanvas().mapRenderer()

        # 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', 'splineplugin_{}.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):
        self.settingsAction = QAction( QCoreApplication.translate("Spline", "Settings" ), self.iface.mainWindow() )
        self.settingsAction.setObjectName("splineAction")
        self.settingsAction.triggered.connect(self.openSettings)

        self.iface.addPluginToVectorMenu(u"Digitize Spline", self.settingsAction)

        self.spline = SplineTool(self.iface)


    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginVectorMenu(u"Digitize Spline", self.settingsAction )
        del self.spline # removes its action from toolbar

    def run(self):
        pass

    def openSettings(self):
        # button signals in SettingsDialog were not working on Win7/64
        # if SettingsDialog was created with iface.mainWindow() as parent
        #self.settingsDialog = SettingsDialog(self.iface.mainWindow())
        self.settingsDialog = SettingsDialog()
        self.settingsDialog.changed.connect( self.spline.settingsChanged )
        self.settingsDialog.show()
Exemplo n.º 17
0
    def __init__(self, app=None):
        #QMainWindow.__init__(self, None)
        super(MainWindow, self).__init__(None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(
            QIcon("/usr/share/package-manager/data/tray-zero.svg"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)
Exemplo n.º 18
0
 def openSettings(self):
     # button signals in SettingsDialog were not working on Win7/64
     # if SettingsDialog was created with iface.mainWindow() as parent
     #self.settingsDialog = SettingsDialog(self.iface.mainWindow())
     self.settingsDialog = SettingsDialog()
     self.settingsDialog.changed.connect( self.spline.settingsChanged )
     self.settingsDialog.show()
Exemplo n.º 19
0
  def ShowSettings(self):
    if not self.settings_dialog:
      # Create the dialog the first time it's shown
      self.settings_dialog = SettingsDialog()
      self.settings_dialog.connect("accepted()", self.di_service.ReloadSettings)
      self.settings_dialog.connect("accepted()", self.sky_service.ReloadSettings)

    self.settings_dialog.show()
Exemplo n.º 20
0
 def setGetSaveSettings(self):
     self.pluginSettingsDic = {}
     try:
         self.getSaveSettings = GetSaveSettings(self.pluginSettingsDic, self.iface, self.projName, self.Path)
         self.pluginSettingsDic = self.getSaveSettings.getSettings(self.pluginSettingsDic)
     except:
         pass
     self.settingsDialog = SettingsDialog(self.iface, self.pluginSettingsDic, self.projName, self.Path)
Exemplo n.º 21
0
 def titleContextMenu(self, pos):
     menu = QMenu()
     menu.setStyleSheet('background: '+self.sets.get('window.menubgcolor','#222')+'; color: '+self.sets.get('window.menucolor','#fff')+'; padding: 6px;')
     settingsAction = menu.addAction("Настройка")
     settingsAction.setIcon(QIcon(':/set.png'))
     menu.addSeparator()
     addgroupAction = menu.addAction('Добавить группу')
     addgroupAction.setIcon(QIcon(':/addgroup.png'))
     menu.addSeparator()
     quitAction = menu.addAction("Quit")
     quitAction.setIcon(QIcon(':/quit.png'))
     action = menu.exec_(self.sender().mapToGlobal(pos))
     if action == quitAction:
         self.onCloseSignal.emit(self)
         self.close()
     elif action == settingsAction:
         dialog = SettingsDialog(self.sets, self)
         dialog.loadfromsets()
         if dialog.exec() == 1:
             dialog.savetosets()
             self.sets.save()
             self.applysets()
     elif action == addgroupAction:
         shladd, title, withtext = groupedit.groupAdd(self.sets.get('panel.withtext',False))
         if shladd:
             self.glist.addList(title, (0,0),withtext)
Exemplo n.º 22
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
        super(EarthMineQGIS, self).__init__()
        self.movingfeature = None
        self.iface = iface
        self.viewer = None
        self.canvas = self.iface.mapCanvas()
        self.settings = QSettings()
        # 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", "EarthMineQGIS_{}.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.pointtool = QgsMapToolEmitPoint(self.canvas)
        self.pointtool.canvasClicked.connect(self.set_viewer_location)

        self.settingsdialog = SettingsDialog(self.iface.mainWindow())

        self.actions = []
        self.menu = self.tr(u"&Earthmine")

        self.toolbar = self.iface.addToolBar(u"EarthMineQGIS")
        self.toolbar.setObjectName(u"EarthMineQGIS")

        self.legend = self.iface.legendInterface()

        emcolor = QColor(1, 150, 51)
        self.tempband = QgsRubberBand(self.canvas, QGis.Line)
        self.tempband.setWidth(5)
        self.tempband.setColor(emcolor)

        self.tempbandpoints = QgsRubberBand(self.canvas, QGis.Point)
        self.tempbandpoints.setWidth(7)
        self.tempbandpoints.setColor(emcolor)

        self.movingband = QgsRubberBand(self.canvas, QGis.Point)
        self.movingband.setWidth(5)
        self.movingband.setColor(emcolor)

        self.layersignals = []
        self.marker = None
Exemplo n.º 23
0
    def settings_dialog(self):
        """
        Opens the settings window allowing the user to manually change the settings in the config
        file
        """

        logger.info('Opening settings window')
        if (not SettingsDialog.singleton):
            SettingsDialog(self.__root, self). \
                wm_iconbitmap(ICO)
        else:
            logger.warning('Found existing settings window, canceling')
Exemplo n.º 24
0
 def __init__(self, parent=None):
     KXmlGuiWindow.__init__(self, parent)
     self.setupUi(self)
     self.setWindowIcon(KIcon(":/data/package-manager.png"))
     self.setCentralWidget(MainWidget(self))
     self.settingsDialog = SettingsDialog(self)
     self.initializeActions()
     self.initializeStatusBar()
     self.initializeTray()
     self.connectMainSignals()
     
     self.offlinemanager = OfflineManager()
     self.connectOfflineSignals()
Exemplo n.º 25
0
    def __init__(self, app = None, silence = False):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.iface = backend.pm.Iface()
        self.setWindowIcon(QtGui.QIcon(":/data/package-manager.png"))
        self.connect(app, SIGNAL("aboutToQuit()"), self.slotQuit)
        self.setCentralWidget(MainWidget(self, silence))
        self.initializeActions()

        if not silence:
            self.settingsDialog = SettingsDialog(self)
            self.initializeStatusBar()
            self.initializeTray()
            self.connectMainSignals()
Exemplo n.º 26
0
    def __init__(self, loadFile=None, fileType=None):
	QtGui.QMainWindow.__init__(self)
	self.setupUi(self)
        self.setWindowIcon(QtGui.QIcon(':moose_thumbnail.png'))
        self.settingsDialog = SettingsDialog()
        self.settingsDialog.hide()
        layout = QtGui.QVBoxLayout(self.modelTreeTab)
        self.modelTreeTab.setLayout(layout)
        layout.addWidget(self.modelTreeContainerWidget)
        self.modelTreeWidget.headerItem().setHidden(True)
        self.plotUpdateIntervalLabel.setText(self.tr('<br>Plot update interval (<b>steps</b>)'))
        self.runTimeLabel.setText(self.tr('<br>Run for (<b>seconds</b>)'))
#         self.modelTreeWidget.show()
#         self.mooseClassToolBox.show()
###################
#         self.plotsLayout = QtGui.QHBoxLayout(self.plotsGroupBox)
#         self.plotsGroupBox.setLayout(self.plotsLayout)
#         self.plotsScrollArea = QtGui.QScrollArea(self.plotsGroupBox)
#         self.plotsLayout.addWidget(self.plotsScrollArea)
#         self.plots = MoosePlots(self.plotsScrollArea)
#         self.plotsScrollArea.setWidget(self.plots)
#         self.plots.show()
##################
        self.plots = MoosePlots(self.plotsGroupBox)
        self.plotsLayout = QtGui.QHBoxLayout(self.plotsGroupBox)
        self.plotsGroupBox.setLayout(self.plotsLayout)
        self.plotsLayout.addWidget(self.plots)
        
######################
        self.plots.show()
        self.isModelLoaded = False
        self.stopFlag = False
	self.mooseHandler = MHandler()
        self.runTimeLineEdit.setText(self.tr(str(self.mooseHandler.runTime)))
        self.plotUpdateIntervalLineEdit.setText(self.tr(str(self.mooseHandler.updateInterval)))
	self.currentDirectory = '.'
	self.fileType = fileType
	self.fileTypes = MHandler.file_types
	self.filter = ''
	self.setupActions()
        if loadFile is not None and fileType is not None:
            self.load(loadFile, fileType)
Exemplo n.º 27
0
    def __init__(self, app=None):
        KXmlGuiWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(KIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)
Exemplo n.º 28
0
class Plugin:
  def __init__(self):
    self.settings_dialog = None

    cb = self.ShowSettings

    # Register for when the user clicks the Settings button
    __script__.connect("SettingsDialogRequested()", cb)

    # Create the services and add them to the Internet tab
    self.di_service = DigitallyImportedService(clementine.internet_model, cb)
    self.sky_service = SkyFmService(clementine.internet_model, cb)
    clementine.internet_model.AddService(self.di_service)
    clementine.internet_model.AddService(self.sky_service)

  def ShowSettings(self):
    if not self.settings_dialog:
      # Create the dialog the first time it's shown
      self.settings_dialog = SettingsDialog()
      self.settings_dialog.connect("accepted()", self.di_service.ReloadSettings)
      self.settings_dialog.connect("accepted()", self.sky_service.ReloadSettings)

    self.settings_dialog.show()
Exemplo n.º 29
0
 def configureSettings(self):
     settingsDialog = SettingsDialog(self, self.settingsManager)
     settingsDialog.show()
Exemplo n.º 30
0
class DateControl:
 
    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', 'datecontrol_{}.qm'.format(locale))
        
        self.proj = QgsProject.instance()
        UriFile = str(self.proj.fileName())
        self.Path = str(os.path.dirname(UriFile))
#        QMessageBox.warning(None, "Path",self.Path)
        self.projName = UriFile[len(self.Path)+1:]

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

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

        # Create the dialog (after translation) and keep reference
        self.setGetSaveSettings()            
        self.dock = DateControlDock(self.iface, self.pluginSettingsDic)
 
    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/datecontrol/DateControlControl.png"), u"Date control", self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)
        self.settingsAction = QAction(QIcon(":/plugins/datecontrol/DateControlSettings.png"), u"Settings", self.iface.mainWindow())
        self.settingsAction.triggered.connect(self.showSettings)
        self.convertDatesAction = QAction(QIcon(":/plugins/datecontrol/DateControlCheckDates.png"), u"Convert dates", self.iface.mainWindow())
        self.convertDatesAction.triggered.connect(self.showConvertDates)
#        self.iface.mapCanvas().layersChanged.connect(self.layersChanged)
        self.iface.projectRead.connect(self.changeProject)

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

    def changeProject(self):
        if not QgsProject is None:
            self.proj = QgsProject.instance()
            UriFile = str(self.proj.fileName())
            self.Path = str(os.path.dirname(UriFile))
            self.projName = UriFile[len(self.Path)+1:]
        else:
            self.projName = ""

        self.setGetSaveSettings()
        settingsKeys = self.pluginSettingsDic.keys()
        self.dock = DateControlDock(self.iface, self.pluginSettingsDic)
        self.convertDatesDialog = convertDatesDialog(self.iface)

    def setGetSaveSettings(self):
        self.pluginSettingsDic = {}
        try:
            self.getSaveSettings = GetSaveSettings(self.pluginSettingsDic, self.iface, self.projName, self.Path)
            self.pluginSettingsDic = self.getSaveSettings.getSettings(self.pluginSettingsDic)
        except:
            pass
        self.settingsDialog = SettingsDialog(self.iface, self.pluginSettingsDic, self.projName, self.Path)

# run method that performs all the real work
    def run(self):
        # show the dialog
        self.openDateControlDock()
#        try:
#            self.openDateControlDock()
#        except:
#            pass
 
    def showConvertDates(self):
        self.convertDatesDialog = convertDatesDialog(self.iface)
        self.convertDatesDialog.show()
        # Run the dialog event loop
        self.convertDatesDialog.exec_()
 
    def showSettings(self):
        self.settingsDialog.show()
        # Run the dialog event loop
        if self.settingsDialog.exec_():
            self.pluginSettingsDic = self.settingsDialog.pluginSettingsDic
            self.dock = DateControlDock(self.iface, self.pluginSettingsDic)
 
    def openDateControlDock(self):
        self.dock.getLayersData()
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

    def unload(self):
       # Remove the plugin menu item and icon
        self.dock.resetLayerQueries()
        self.iface.removePluginMenu(u"&DateControl", self.action)
        self.iface.removeToolBarIcon(self.action)
        self.iface.removePluginMenu(u"&DateControl", self.settingsAction)
        self.iface.removeToolBarIcon(self.settingsAction)
        self.iface.removePluginMenu(u"&DateControl", self.convertDatesAction)
        self.iface.removeToolBarIcon(self.convertDatesAction)
Exemplo n.º 31
0
class EarthMineQGIS(QObject):
    """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
        super(EarthMineQGIS, self).__init__()
        self.movingfeature = None
        self.iface = iface
        self.viewer = None
        self.canvas = self.iface.mapCanvas()
        self.settings = QSettings()
        # 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',
                                   'EarthMineQGIS_{}.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.pointtool = QgsMapToolEmitPoint(self.canvas)
        self.pointtool.canvasClicked.connect(self.set_viewer_location)

        self.settingsdialog = SettingsDialog(self.iface.mainWindow())

        self.actions = []
        self.menu = self.tr(u'&Earthmine')

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

        self.legend = self.iface.legendInterface()

        emcolor = QColor(1, 150, 51)
        self.tempband = QgsRubberBand(self.canvas, QGis.Line)
        self.tempband.setWidth(5)
        self.tempband.setColor(emcolor)

        self.tempbandpoints = QgsRubberBand(self.canvas, QGis.Point)
        self.tempbandpoints.setWidth(7)
        self.tempbandpoints.setColor(emcolor)

        self.movingband = QgsRubberBand(self.canvas, QGis.Point)
        self.movingband.setWidth(5)
        self.movingband.setColor(emcolor)

        self.layersignals = []
        self.marker = None

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/icons/settings'
        self.add_action(icon_path,
                        text=self.tr(u'Show Settings'),
                        callback=self.show_settings,
                        parent=self.iface.mainWindow())
        icon_path = ':/icons/viewer'
        self.add_action(icon_path,
                        text=self.tr(u'Earthmine Viewer'),
                        callback=self.open_viewer,
                        parent=self.iface.mainWindow())

        self.marker = PostionMarker(self.canvas)
        self.marker.hide()

        self.viewer = Viewer(callbackobject=self)
        self.viewer.trackingChanged.connect(self.marker.setTracking)
        self.viewer.setLocationTriggered.connect(
            partial(self.canvas.setMapTool, self.pointtool))
        self.viewer.updateFeatures.connect(self.update_earthmine_features)
        self.viewer.layerChanged.connect(self.iface.setActiveLayer)
        self.viewer.clearLine.connect(self.clear_bands)
        self.viewer.closed.connect(self.remove_items)
        self.iface.currentLayerChanged.connect(
            self.viewer.update_current_layer)

        cursor = QCursor(QPixmap(":/icons/location"))
        self.pointtool.setCursor(cursor)
        self.pointtool.setAction(self.viewer.setlocationaction)

    def remove_items(self):
        self.marker.setTracking(False)
        self.disconnect_projectsignals()
        self.iface.actionPan().trigger()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        self.canvas.scene().removeItem(self.marker)
        del self.marker

        self.disconnect_projectsignals()

        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Earthmine'), action)
            self.iface.removeToolBarIcon(action)

        del self.toolbar

        self.iface.removeDockWidget(self.viewer)
        self.viewer.deleteLater()

    def disconnect_projectsignals(self):
        safe_disconnect(QgsMapLayerRegistry.instance().layerWasAdded,
                        self.connect_layer_signals)
        safe_disconnect(QgsMapLayerRegistry.instance().layersRemoved,
                        self.layers_removed)
        safe_disconnect(self.canvas.layersChanged, self.layers_changed)
        safe_disconnect(self.iface.projectRead, self.connect_signals)
        safe_disconnect(self.canvas.selectionChanged, self.selection_changed)
        safe_disconnect(self.canvas.selectionChanged,
                        self.viewer.selection_changed)

    def clear_bands(self):
        self.tempband.reset(QGis.Line)
        self.tempbandpoints.reset(QGis.Point)

    def visible_layers(self):
        """
        Return the visible layers shown in the map canvas
        :return:
        """
        return (layer for layer, visible in self.layers_with_states()
                if visible)

    def layers_with_states(self):
        for layer in maplayers():
            if not layer.type() == QgsMapLayer.VectorLayer:
                continue

            if not layer.geometryType() in [QGis.Point, QGis.Line]:
                continue

            yield layer, self.legend.isLayerVisible(layer)

    def _layer_feature_added(self, featureid):
        layer = self.sender()
        if not layer:
            return

        self.layer_feature_added(layer, featureid)

    def layer_feature_added(self, layer, featureid):
        if not self.viewer:
            return

        feature = layer.getFeatures(QgsFeatureRequest(featureid)).next()
        renderer = layer.rendererV2()
        transform = self.coordinatetransform(layer)
        featuredata = to_feature_data(layer.id(), feature, renderer, transform)
        geomtype = layer.geometryType()
        layerdata = dict(id=layer.id(),
                         geomtype=QGis.vectorGeometryType(geomtype))
        self.viewer.load_features(layerdata, featuredata)

    def _layer_feature_delete(self, featureid):
        layer = self.sender()
        if not layer:
            return
        self.layer_feature_delete(layer, featureid)

    def layer_feature_delete(self, layer, featureid):
        if not self.viewer:
            return

        self.viewer.remove_feature(layer.id(), featureid)

    def _layer_geometry_changed(self, featureid, geometry):
        layer = self.sender()
        if not layer:
            return
        self.layer_geometry_changed(layer, featureid, geometry)

    def layer_geometry_changed(self, layer, featureid, geometry):
        if not self.viewer:
            return

        geomtype = layer.geometryType()
        if geomtype == QGis.Point:
            geom = geometry.asPoint()
            transform = self.coordinatetransform(layer)
            point = transform.transform(
                geom, QgsCoordinateTransform.ReverseTransform)
            location = dict(lat=point.y(), lng=point.x())
            self.viewer.edit_feature(layer.id(), featureid, [location])
        elif geomtype == QGis.Line:
            self.layer_feature_delete(layer, featureid)
            self.layer_feature_added(layer, featureid)

    def connect_layer_signals(self, layer):
        if not layer.type() == QgsMapLayer.VectorLayer:
            return

        layer.featureAdded.connect(self._layer_feature_added)
        layer.featureDeleted.connect(self._layer_feature_delete)
        layer.editingStarted.connect(self.layer_editstate_changed)
        layer.editingStopped.connect(self.layer_editstate_changed)
        # HACK The new style doesn't work here
        # http://hub.qgis.org/issues/6573
        signal = SIGNAL("geometryChanged(QgsFeatureId, QgsGeometry&)")
        self.connect(layer, signal, self._layer_geometry_changed)
        self.load_layer_features(layers=[layer])

    def layer_editstate_changed(self):
        layer = self.sender()
        if layer == self.iface.activeLayer():
            self.viewer.layer_changed(layer)

    def disconnect_signals(self):
        self.disconnect_projectsignals()

        for layer in maplayers():
            if not layer.type() == QgsMapLayer.VectorLayer:
                return

            safe_disconnect(layer.featureAdded, self._layer_feature_added)
            safe_disconnect(layer.featureDeleted, self._layer_feature_delete)
            safe_disconnect(layer.editingStarted, self.layer_editstate_changed)
            safe_disconnect(layer.editingStopped, self.layer_editstate_changed)
            # HACK The new style doesn't work here
            # http://hub.qgis.org/issues/6573
            signal = SIGNAL("geometryChanged(QgsFeatureId, QgsGeometry&)")
            self.disconnect(layer, signal, self._layer_geometry_changed)

    def connect_signals(self):
        for layer in maplayers():
            self.connect_layer_signals(layer)

        self.center_on_canvas()

    def set_viewer_location(self, point, mousebutton):
        transform = self.coordinatetransform()
        point = transform.transform(point,
                                    QgsCoordinateTransform.ReverseTransform)
        self.viewer.set_location(point)

    def distancearea(self):
        area = QgsDistanceArea()
        dest = self.canvas.mapRenderer().destinationCrs()
        area.setSourceCrs(dest)
        return area, dest.mapUnits()

    def coordinatetransform(self, layer=None):
        """
        Return the transform for WGS84 -> QGIS projection.
        """
        source = QgsCoordinateReferenceSystem()
        source.createFromWkt(
            'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]'
        )
        if not layer:
            dest = self.canvas.mapRenderer().destinationCrs()
        else:
            dest = layer.crs()
        transform = QgsCoordinateTransform(source, dest)
        return transform

    def earthmine_settings(self):
        settings = {}
        with settinggroup(self.settings, "plugins/Earthmine"):
            for key in [
                    'serviceUrl', 'baseDataUrl', "apiKey", 'secretKey',
                    'viewerUrl'
            ]:
                if not self.settings.contains(key):
                    raise EarthmineSettingsError("{} not set".format(key))

                value = self.settings.value(key, type=str)
                if value is None:
                    raise EarthmineSettingsError("{} not set".format(key))

                settings[key] = value

        return settings

    @pyqtSlot()
    def ready(self):
        """
        Called when the viewer is ready to be started.  At this point the viewer hasn't been loaded
        so no other methods apart from startViewer will be handled.
        """
        settings = self.earthmine_settings()
        self.viewer.startViewer(settings)

    @pyqtSlot()
    def viewerReady(self):
        """
        Called once the viewer is loaded and ready to get location events.
        """
        self.disconnect_signals()
        self.connect_signals()
        self.iface.projectRead.connect(self.connect_signals)
        self.canvas.layersChanged.connect(self.layers_changed)
        self.canvas.selectionChanged.connect(self.selection_changed)
        self.canvas.selectionChanged.connect(self.viewer.selection_changed)
        QgsMapLayerRegistry.instance().layersRemoved.connect(
            self.layers_removed)
        QgsMapLayerRegistry.instance().layerWasAdded.connect(
            self.connect_layer_signals)
        self.center_on_canvas()
        self.viewer.activelayercombo.setLayer(self.iface.activeLayer())

    def center_on_canvas(self):
        point = self.canvas.extent().center()
        transform = self.coordinatetransform()
        point = transform.transform(point,
                                    QgsCoordinateTransform.ReverseTransform)
        self.viewer.set_location(point)
        self.viewer.infoaction.toggle()

    def selection_changed(self, layer):
        ids = [feature.id() for feature in layer.selectedFeatures()]
        if not ids:
            self.viewer.clear_selection(layer.id())
        else:
            self.viewer.set_selection(layer.id(), ids)

    def layers_changed(self):
        layerstates = self.layers_with_states()
        for layer, visible in layerstates:
            layerid = layer.id()
            viewerloaded = self.viewer.layer_loaded(layerid)
            QgsMessageLog.instance().logMessage(layerid, "Earthmine")
            QgsMessageLog.instance().logMessage(
                "Viewer State:" + str(viewerloaded), "Earthmine")
            QgsMessageLog.instance().logMessage("QGIS State:" + str(visible),
                                                "Earthmine")
            if (viewerloaded and visible) or (not viewerloaded
                                              and not visible):
                QgsMessageLog.instance().logMessage("Ignoring as states match",
                                                    "Earthmine")
                continue

            if viewerloaded and not visible:
                QgsMessageLog.instance().logMessage(
                    "Clearing layer because viewer loaded and disabled in QGIS",
                    "Earthmine")
                self.viewer.clear_layer_features(layerid)
                continue

            if not viewerloaded and visible:
                QgsMessageLog.instance().logMessage("Loading layer",
                                                    "Earthmine")
                self.load_layer_features(layers=[layer])
                continue

    def layers_removed(self, layers):
        for layerid in layers:
            self.viewer.clear_layer_features(layerid)

    @pyqtSlot(str, float, float)
    def viewChanged(self, event, yaw, angle):
        self.marker.setAngle(angle)
        self.marker.setYaw(yaw)

    @pyqtSlot(str, str)
    def getInfo(self, layerid, featureid):
        featureid = int(featureid)
        activelayer = self.iface.activeLayer()
        if not activelayer:
            return

        activetool = self.viewer.active_tool()
        if not activetool in ["Info", "Select"]:
            return

        # Only show information for the active layer
        if not layerid == activelayer.id():
            return

        layer = layer_by_id(layerid)
        if activetool == "Select":
            layer.setSelectedFeatures([featureid])
        elif activetool == "Info":
            rq = QgsFeatureRequest(featureid)
            feature = layer.getFeatures(rq).next()
            dlg = get_feature_form(layer, feature)
            if dlg.dialog().exec_():
                self.canvas.refresh()

    @pyqtSlot(str, str, float, float, bool)
    def featureMoved(self, layerid, featureid, lat, lng, end):
        layer = layer_by_id(layerid)
        transform = self.coordinatetransform(layer)
        point = transform.transform(lng, lat)
        if not end:
            self.movingband.show()
            self.movingband.setToGeometry(QgsGeometry.fromPoint(point), layer)
            self.movingband.updatePosition()
            self.movingband.update()
        else:
            self.movingband.hide()
            feature = feature_by_id(layer, featureid)
            startpoint = feature.geometry().asPoint()
            dx = point.x() - startpoint.x()
            dy = point.y() - startpoint.y()
            layer.beginEditCommand("Feature Moved")
            # Block signals for this move as the geometry changed signal will re add the geometry on use.
            layer.blockSignals(True)
            layer.translateFeature(feature.id(), dx, dy)
            layer.blockSignals(False)
            self.canvas.refresh()
            layer.endEditCommand()

    @pyqtSlot(str, str)
    def onError(self, message, stacktrace=None):
        self.iface.messageBar().pushMessage("Earthmine", message,
                                            QgsMessageBar.WARNING)
        QgsMessageLog.logMessage(stacktrace, "Earthmine")

    @pyqtSlot(float, float, float)
    def addPoint(self, lat, lng, z):
        layer = self.viewer.active_layer
        if not layer.isEditable():
            self.iface.messageBar().pushMessage(
                "Earthmine",
                "Selected layer isn't editable. Please enable edit mode to add features",
                duration=3,
                level=QgsMessageBar.WARNING)
            return

        transform = self.coordinatetransform(layer)
        point = transform.transform(lng, lat)
        geom = QgsGeometry.fromPoint(point)
        self.add_feature(layer, geom, z)

    def add_feature(self, layer, geom, z=None):
        feature = QgsFeature(layer.pendingFields())
        if z and self.viewer.copyZvalue:
            try:
                feature['Z'] = z
            except KeyError:
                QgsMessageLog.log("No Z found on layer {}".format(
                    layer.name()))
                pass

        feature.setGeometry(geom)
        dlg = get_feature_form(layer, feature, isadd=True)
        if dlg.dialog().exec_():
            self.canvas.refresh()

    @pyqtSlot(str, bool, str)
    def drawLine(self, points, end, stats):
        points = json.loads(points)
        stats = json.loads(stats)
        QgsMessageLog.logMessage(str(stats), "Earthmine")
        self.tempband.reset(QGis.Line)
        self.tempbandpoints.reset(QGis.Point)
        color = QColor(self.viewer.current_action_color)
        self.tempband.setColor(color)
        self.tempbandpoints.setColor(color)

        layer = self.viewer.active_layer
        transform = self.coordinatetransform(layer)
        earthminepoints = []
        for point in points:
            newpoint = transform.transform(point['lng'], point['lat'])
            self.tempband.addPoint(newpoint)
            self.tempbandpoints.addPoint(newpoint)
            empoint = EarthminePoint(newpoint, point)
            earthminepoints.append(empoint)

        if end and not self.viewer.mode == "Vertical":
            geom = self.tempband.asGeometry()
            self.add_feature(layer, geom)
            self.clear_bands()

        self.viewer.geom = EarthmineLine(earthminepoints, stats)

        self.tempband.show()
        self.tempbandpoints.show()

    @pyqtSlot(str, str, str, float)
    def locationChanged(self, lat, lng, yaw, angle):
        transform = self.coordinatetransform()
        point = transform.transform(float(lng), float(lat))
        self.marker.setCenter(point)
        yaw = float(yaw)
        self.marker.setAngle(angle)
        self.marker.setYaw(yaw)
        self.marker.setTracking(self.viewer.tracking)

        if self.marker.tracking:
            rect = QgsRectangle(point, point)
            extentlimt = QgsRectangle(self.canvas.extent())
            extentlimt.scale(0.95)

            if not extentlimt.contains(point):
                self.canvas.setExtent(rect)
                self.canvas.refresh()

        # Clear old features
        self.viewer.clear_features()
        self.load_layer_features(point)

    def update_earthmine_features(self, viewfeatures):
        self.viewer.clear_features()

        if viewfeatures:
            self.load_layer_features()

    def load_layer_features(self, point=None, layers=None):

        # TODO Move this logic into the viewer and let it track it's position
        if point is None and self.marker.map_pos is None:
            return

        if point is None:
            point = self.marker.map_pos

        area, units = self.distancearea()
        rect = search_area(units, area, point)

        if layers is None:
            layers = self.visible_layers()

        for layer in layers:
            transform = self.coordinatetransform(layer)
            # Transform the rect
            source = self.canvas.mapRenderer().destinationCrs()
            dest = layer.crs()
            recttransform = QgsCoordinateTransform(source, dest)
            rect = recttransform.transformBoundingBox(rect)
            features = list(
                get_features_in_area(layer, rect, transform,
                                     self.canvas.mapSettings()))
            geomtype = layer.geometryType()
            layerdata = dict(id=layer.id(),
                             geomtype=QGis.vectorGeometryType(geomtype))
            self.viewer.load_features(layerdata, features)

    # 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('EarthMineQGIS', 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 InaSAFE 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 s, "Earhtmine"how 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 open_viewer(self):
        """Run method that performs all the real work"""
        try:
            settings = self.earthmine_settings()
        except EarthmineSettingsError as ex:
            self.onError(ex.message)
            self.show_settings()
            return

        url = settings["viewerUrl"]
        if not url.startswith("http"):
            url = url.replace("\\\\", "\\")
            url = QUrl.fromLocalFile(url)
        else:
            url = QUrl(url)

        if not self.viewer.isVisible():
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.viewer)

        self.viewer.loadviewer(url)

    def show_settings(self):
        self.settingsdialog.show()
Exemplo n.º 32
0
 def showSettings(self):
     dlg = SettingsDialog(self)
     dlg.exec_()
Exemplo n.º 33
0
 def display_settings(self):
     """Display a dialog box with plugin settings."""
     dialog = SettingsDialog(self)
     dialog.run()
     self.refresh()
Exemplo n.º 34
0
 def settings_click_cb(self, widget):
     dialog = SettingsDialog(widget.get_toplevel())
     dialog.show()
Exemplo n.º 35
0
 def configureSettings(self):
     settingsDialog = SettingsDialog(self, self.settingsManager)
     settingsDialog.show()
Exemplo n.º 36
0
 def setting(self):
   from settingsdialog import SettingsDialog
   dialog = SettingsDialog(self.iface)
   dialog.show()
   dialog.exec_()
Exemplo n.º 37
0
 def on_actionConfigure_triggered(self):
     dialog = SettingsDialog(self.programSettings, self)
     dialog.rowHeightChanged.connect(self.setRowHeight)
     dialog.exec_()
Exemplo n.º 38
0
 def openSettings(self):
     """Open settings dialog and reload settings"""
     settingsDialog = SettingsDialog(self.settings)
     settingsDialog.exec_()
Exemplo n.º 39
0
    def openSettings(self):

        self.settingsDialog = SettingsDialog()
        self.settingsDialog.changed.connect(self.spline.settingsChanged)
        self.settingsDialog.show()
Exemplo n.º 40
0
class QuickDigitize:
    """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: QgisInterface
        """
        # 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',
        #     'QuickDigitize_{}.qm'.format(locale))

        userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path(
        ) + "/python/plugins/QuickDigitize"
        systemPluginPath = QgsApplication.prefixPath(
        ) + "/share/qgis/python/plugins/QuickDigitize"
        locale = QSettings().value("locale/userLocale")
        myLocale = locale[0:2]

        if QFileInfo(userPluginPath).exists():
            pluginPath = userPluginPath + "/i18n/QuickDigitize_" + myLocale + ".qm"
        elif QFileInfo(systemPluginPath).exists():
            pluginPath = systemPluginPath + "/i18n/QuickDigitize_" + myLocale + ".qm"

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

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
        # Declare instance attributes
        self.actions = []
        self.dlg = QuickDigitizeDialog()

        self.menu = self.tr(u'&QuickDigitize')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QuickDigitize')
        self.toolbar.setObjectName(u'QuickDigitize')
        self.createpointlayer = CreatePointLayerTool(self.iface, self.toolbar)
        self.createlinelayer = CreateLineLayerTool(self.iface, self.toolbar)
        self.createpolygonlayer = CreatePolygonLayerTool(
            self.iface, self.toolbar)
        self.spline = SplineTool(self.iface, self.toolbar)
        self.ortho = OrthogonalDigitizerTool(self.iface, self.toolbar)
        self.rectangle = RectTool(self.iface, self.toolbar)
        self.addattribute = AddAttributeTool(self.iface, self.toolbar)
        self.addfields = AddFieldsTool(self.iface, self.toolbar)
        self.showazimuth = ShowAzimuthTool(self.iface, self.toolbar)
        self.rotateobject = RotateObjectTool(self.iface, self.toolbar)
        self.addstyle = AddStyleTool(self.iface, self.toolbar)

        toolbars = iface.mainWindow().findChildren(QToolBar)
        for self.toolbar in toolbars:
            self.toolbar.setIconSize(QSize(48, 48))

        self.dlg.lineEdit.clear()
        self.dlg.pushButton.clicked.connect(self.select_output_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('QuickDigitize', 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):

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

        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.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/QuickDigitize/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Quick Digitize'),
                        callback=self.run,
                        parent=self.iface.mainWindow())
        self.settingsAction = QAction(
            QCoreApplication.translate("Spline", "Settings"),
            self.iface.mainWindow())
        self.settingsAction.setObjectName("splineAction")
        self.settingsAction.triggered.connect(self.openSettings)

        self.iface.addPluginToVectorMenu(u"Digitize Spline",
                                         self.settingsAction)

        self.settingsAction.triggered.connect(self.openSettings)

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

        # remove the toolbar
        del self.toolbar

    def openSettings(self):

        self.settingsDialog = SettingsDialog()
        self.settingsDialog.changed.connect(self.spline.settingsChanged)
        self.settingsDialog.show()

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

    def run(self):

        layers = self.iface.legendInterface().layers()
        layer_list = []
        for layer in layers:
            layer_list.append(layer.name())
        self.dlg.comboBox.clear()
        self.dlg.comboBox.addItems(layer_list)
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            filename = self.dlg.lineEdit.text()
            output_file = open(filename, 'w')

            selectedLayerIndex = self.dlg.comboBox.currentIndex()
            selectedLayer = layers[selectedLayerIndex]
            fields = selectedLayer.pendingFields()
            fieldnames = [field.name() for field in fields]

            for f in selectedLayer.getFeatures():
                line = ','.join(unicode(f[x]) for x in fieldnames) + '\n'
                unicode_line = line.encode('utf-8')
                output_file.write(unicode_line)
            output_file.close()
Exemplo n.º 41
0
class GVDigitizingTools:
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        self.dlgSettings = SettingsDialog()

        self.digitizingSetup = DigitizingSetup(self.iface)
        self.currentMode = None
        self.currentLayer = None
        self.isBackgroundSnapping = False

        self.initSettings()

    def initSettings(self):
        # set default if first time this ie executed
        settings = QSettings()
        method = settings.value(constants.ARC_METHOD,
                                constants.ARC_METHOD_ANGLE)
        settings.setValue(constants.ARC_METHOD, method)
        angle = settings.value(constants.ARC_ANGLE, 3.0, type=float)
        settings.setValue(constants.ARC_ANGLE, angle)
        numberOfPoints = settings.value(constants.ARC_NUMBEROFPOINTS,
                                        10,
                                        type=int)
        settings.setValue(constants.ARC_NUMBEROFPOINTS, numberOfPoints)

        enablePreview = settings.value(constants.PREVIEW_ENABLED, True)
        settings.setValue(constants.PREVIEW_ENABLED, enablePreview)
        enablePreviewLimit = settings.value(constants.PREVIEW_LIMIT_ENABLED,
                                            False)
        settings.setValue(constants.PREVIEW_LIMIT_ENABLED, enablePreviewLimit)
        maxLimitPreview = settings.value(constants.PREVIEW_LIMIT_MAX, 1000)
        settings.setValue(constants.PREVIEW_LIMIT_MAX, maxLimitPreview)

    def initGui(self):
        self.actions = []
        self.createAction("actionSettings",
                          "icons/iconSettings.png",
                          u"Settings",
                          self.doShowSettings,
                          checkable=False)
        self.createAction("action", "icon.png", u"Digitizing tools",
                          self.doSetupDigitizing)
        self.createAction("actionBackgroundSnapping", "icons/iconSnap.png",
                          u"Snap to background layers",
                          self.doSetupBackgroundSnapping)

        self.createAction("actionDrawArc", "icons/iconDrawArc.png", u"Add arc",
                          self.doDrawArc, "Alt+Ctrl+S")
        self.createAction("actionExtend", "icons/iconExtend.png", u"Extend",
                          self.doExtend, "Alt+Ctrl+E")
        self.createAction("actionFillet", "icons/iconFillet.png", u"Fillet",
                          self.doFillet, "Alt+Ctrl+F")
        self.createAction("actionTrim", "icons/iconTrim.png", u"Trim",
                          self.doTrim, "Alt+Ctrl+C")
        self.createAction("actionMirror", "icons/iconMirror.png", u"Mirror",
                          self.doMirror, "Alt+Ctrl+W")
        self.createAction("actionScale", "icons/iconScale.png", u"Scale",
                          self.doScale, "Alt+Ctrl+Z")
        self.createAction("actionMove", "icons/iconMove.png", u"Move",
                          self.doMove, "Alt+Ctrl+D")
        self.createAction("actionCopy", "icons/iconCopy.png", u"Copy",
                          self.doCopy, "Alt+Ctrl+X")
        self.createAction("actionMoveMultipleLayers",
                          "icons/iconMoveMultipleLayers.png",
                          u"Move from multiple layers",
                          self.doMoveMultipleLayers, "Alt+Ctrl+Q")
        self.createAction("actionCopyMultipleLayers",
                          "icons/iconCopyMultipleLayers.png",
                          u"Copy from multiple layers",
                          self.doCopyMultipleLayers, "Alt+Ctrl+R")
        self.createAction("actionParallel", "icons/iconParallel.png",
                          u"Parallel", self.doParallel, "Alt+Ctrl+P")
        self.createAction("actionSplit", "icons/iconSplit.png", u"Split",
                          self.doSplit, "Alt+Ctrl+H")
        self.createAction("actionCenterline", "icons/iconCenterline.png",
                          u"Centerline", self.doCenterline, "Alt+Ctrl+J")
        self.createAction("actionCenterlineAdvanced",
                          "icons/iconCenterlineAdvanced.png",
                          u"Centerline Advanced", self.doCenterlineAdvanced,
                          "Alt+Ctrl+K")

        self.createAction("actionPolygonize",
                          "icons/iconPolygonize.png",
                          u"Polygonize",
                          self.doPolygonize,
                          checkable=False)
        self.createAction("actionIntersect",
                          "icons/iconIntersect.png",
                          u"Create node at intersections",
                          self.doIntersect,
                          checkable=False)
        self.createAction("actionExplode",
                          "icons/iconExplode.png",
                          u"Explode multipart to single parts",
                          self.doExplode,
                          checkable=False)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu(u"&GV Digitizing Tools",
                                   self.actionSettings)

        self.toolbar = self.iface.addToolBar("GV Digitizing Tools")
        self.toolbar.addAction(self.action)
        self.toolbar.addAction(self.actionBackgroundSnapping)
        self.toolbar.addSeparator()
        self.addActionGroup([
            self.actionDrawArc, self.actionExtend, self.actionFillet,
            self.actionTrim, self.actionMirror, self.actionScale,
            self.actionParallel, self.actionSplit, self.actionCenterline,
            self.actionCenterlineAdvanced
        ])
        self.toolbar.addSeparator()
        self.addActionGroup([
            self.actionMove, self.actionCopy, self.actionMoveMultipleLayers,
            self.actionCopyMultipleLayers
        ])
        self.toolbar.addSeparator()
        self.addActionGroup(
            [self.actionPolygonize, self.actionIntersect, self.actionExplode])

        self.ignoreActions = set([
            self.action, self.actionSettings, self.actionBackgroundSnapping,
            self.actionMoveMultipleLayers, self.actionCopyMultipleLayers,
            self.actionMove, self.actionCopy, self.actionParallel
        ])
        self.action.setEnabled(True)
        self.actionMoveMultipleLayers.setEnabled(True)
        self.actionCopyMultipleLayers.setEnabled(True)
        self.actionParallel.setEnabled(False)
        self.actionBackgroundSnapping.setEnabled(True)

        self.extendMode = ExtendDigitizingMode(self.iface)
        self.extendMode.setAction(self.actionExtend)
        self.trimMode = TrimDigitizingMode(self.iface)
        self.trimMode.setAction(self.actionTrim)
        self.drawArcMode = DrawArcDigitizingMode(self.iface)
        self.drawArcMode.setAction(self.actionDrawArc)
        self.filletMode = FilletDigitizingMode(self.iface)
        self.filletMode.setAction(self.actionFillet)
        self.mirrorMode = MirrorDigitizingMode(self.iface, self)
        self.mirrorMode.setAction(self.actionMirror)
        self.scaleMode = ScaleDigitizingMode(self.iface, self)
        self.scaleMode.setAction(self.actionScale)
        self.moveMode = MoveDigitizingMode(self.iface, self)
        self.moveMode.setAction(self.actionMove)
        self.copyMode = CopyDigitizingMode(self.iface, self)
        self.copyMode.setAction(self.actionCopy)
        self.moveMultipleLayersMode = MoveMultipleLayersDigitizingMode(
            self.iface, self)
        self.moveMultipleLayersMode.setAction(self.actionMoveMultipleLayers)
        self.copyMultipleLayersMode = CopyMultipleLayersDigitizingMode(
            self.iface, self)
        self.copyMultipleLayersMode.setAction(self.actionCopyMultipleLayers)
        self.parallelConstraintMode = ParallelConstraintMode(self.iface)
        self.parallelConstraintMode.setAction(self.actionParallel)
        self.splitMode = SplitDigitizingMode(self.iface)
        self.splitMode.setAction(self.actionSplit)
        self.centerlineMode = CenterlineDigitizingMode(self.iface)
        self.centerlineMode.setAction(self.actionCenterline)
        self.centerlineAdvancedMode = CenterlineAdvancedDigitizingMode(
            self.iface)
        self.centerlineAdvancedMode.setAction(self.actionCenterlineAdvanced)

        self.explodeCommand = ExplodeCommand(self.iface)
        self.polygonizeCommand = PolygonizeCommand(self.iface)
        self.intersectCommand = IntersectCommand(self.iface)

        self.cadPointList = CadPointList(self.checkIsParallelEnabled)
        self.eventFilter = ConstraintEventFilter(self.iface, self,
                                                 self.cadPointList)
        # to track the mouse for mouseMoveEvents to happen
        self.iface.mapCanvas().viewport().setMouseTracking(True)
        # to get the mouse events
        self.iface.mapCanvas().viewport().installEventFilter(self.eventFilter)

        self.iface.legendInterface().currentLayerChanged.connect(
            self.currentLayerChanged)
        self.currentLayer = self.iface.legendInterface().currentLayer()
        if self.currentLayer and self.currentLayer.type(
        ) == QgsMapLayer.VectorLayer:
            self.currentLayer.editingStopped.connect(self.editingStopped)
            self.currentLayer.editingStarted.connect(self.editingStarted)
            self.currentLayer.selectionChanged.connect(self.selectionChanged)
        self.iface.mapCanvas().mapToolSet.connect(self.maptoolChanged)

        self.maptoolChanged()
        self.checkCurrentLayerIsEditableLineLayer()
        self.checkIsMoveOrCopyEnabled()
        self.checkIsParallelEnabled()

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(u"&GV Digitizing Tools",
                                    self.actionSettings)

        self.iface.legendInterface().currentLayerChanged.disconnect(
            self.currentLayerChanged)
        self.currentLayer = self.iface.legendInterface().currentLayer()
        if self.currentLayer:
            try:
                self.currentLayer.editingStarted.disconnect(
                    self.editingStarted)
            except Exception:
                pass
            try:
                self.currentLayer.editingStopped.disconnect(
                    self.editingStopped)
            except Exception:
                pass
            try:
                self.currentLayer.selectionChanged.disconnect(
                    self.selectionChanged)
            except:
                pass
        self.iface.mapCanvas().mapToolSet.disconnect(self.maptoolChanged)

        self.iface.mapCanvas().viewport().setMouseTracking(False)
        self.eventFilter.close()
        self.iface.mapCanvas().viewport().removeEventFilter(self.eventFilter)

        del self.toolbar

    def createAction(self,
                     name,
                     icon,
                     tip,
                     callback,
                     shortcut=None,
                     checkable=True):

        action = QAction(QIcon(":/plugins/gvdigitizingtools/" + icon), tip,
                         self.iface.mainWindow())
        # connect the action to the run method
        action.triggered.connect(callback)
        action.setCheckable(checkable)

        if shortcut:
            action.setShortcut(shortcut)

        self.__dict__[name] = action
        self.actions.append(action)

    def addActionGroup(self, actions):
        for action in actions:
            self.toolbar.addAction(action)

    def currentLayerChanged(self):
        # first cleanup events for previous layer
        if self.currentLayer:
            try:
                self.currentLayer.editingStarted.disconnect(
                    self.editingStarted)
            except Exception:
                pass
            try:
                self.currentLayer.editingStopped.disconnect(
                    self.editingStopped)
            except Exception:
                pass
            try:
                self.currentLayer.selectionChanged.disconnect(
                    self.selectionChanged)
            except:
                pass
        self.currentLayer = self.iface.legendInterface().currentLayer()
        if self.currentLayer and self.currentLayer.type(
        ) == QgsMapLayer.VectorLayer:
            self.currentLayer.editingStopped.connect(self.editingStopped)
            self.currentLayer.editingStarted.connect(self.editingStarted)
            self.currentLayer.selectionChanged.connect(self.selectionChanged)

        self.checkCurrentLayerIsEditableLineLayer()
        self.checkIsParallelEnabled()

        # selectedLayers not yet updated and no event for this (have to use
        # currentLAyer change event)
        # get stuck when going from multiple to one selection
        QTimer.singleShot(1, self.checkIsMoveOrCopyEnabled)

    def editingStarted(self):
        self.checkCurrentLayerIsEditableLineLayer()
        self.checkIsParallelEnabled()
        self.checkIsMoveOrCopyEnabled()

    def editingStopped(self):
        self.checkCurrentLayerIsEditableLineLayer()
        self.checkIsParallelEnabled()
        self.checkIsMoveOrCopyEnabled()

    def selectionChanged(self):
        self.checkIsMoveOrCopyEnabled()

    def maptoolChanged(self):
        self.parallelConstraintMode.isRelevant = (
            self.iface.mapCanvas().mapTool() is not None
            and self.iface.mapCanvas().mapTool().isEditTool())

    def checkCurrentLayerIsEditableLineLayer(self):
        if self.currentLayer and self.currentLayer.type(
        ) == QgsMapLayer.VectorLayer and self.currentLayer.geometryType(
        ) == QGis.Line and self.currentLayer.isEditable():
            for action in self.actions:
                # special processing for some actions (irrelevant or some custom processing)
                if action not in self.ignoreActions:
                    action.setEnabled(True)

            if self.currentMode and self.currentMode != self.moveMultipleLayersMode:
                self.currentMode.reset()
                self.currentMode.setLayer(self.currentLayer)

        else:
            for action in self.actions:
                if action not in self.ignoreActions:
                    action.setEnabled(False)

            if self.currentMode and self.currentMode != self.moveMultipleLayersMode:
                self.currentMode.reset()
                self.iface.mapCanvas().unsetMapTool(self.currentMode)
                self.currentMode = None

    def checkIsParallelEnabled(self):
        if (self.currentLayer
                and self.currentLayer.type() == QgsMapLayer.VectorLayer
                and self.currentLayer.geometryType() == QGis.Line
                and self.currentLayer.isEditable()
                and len(self.cadPointList) > 1
                and self.digitizingSetup.enableEventFilter):
            self.actionParallel.setEnabled(True)
        else:
            self.actionParallel.setEnabled(False)

    def checkIsMoveOrCopyEnabled(self):
        """
        Any type of geometry
        For Multiple... modes, no need to be editable but needs to have selection
        """
        layers = self.iface.legendInterface().selectedLayers()
        isSingleEnabled = False
        isMultipleEnabled = False
        for layer in layers:
            if layer.type() == QgsMapLayer.VectorLayer:
                if layer.isEditable():
                    self.actionMove.setEnabled(True)
                    self.actionCopy.setEnabled(True)
                    isSingleEnabled = True
                if layer.selectedFeatureCount() > 0:
                    self.actionMoveMultipleLayers.setEnabled(True)
                    self.actionCopyMultipleLayers.setEnabled(True)
                    isMultipleEnabled = True
                    break

        if not isSingleEnabled:
            self.moveMode.reset()
            self.copyMode.reset()
            self.actionMove.setChecked(False)
            self.actionMove.setEnabled(False)
            self.actionCopy.setChecked(False)
            self.actionCopy.setEnabled(False)

        if not isMultipleEnabled:
            self.moveMultipleLayersMode.reset()
            self.copyMultipleLayersMode.reset()
            self.actionMoveMultipleLayers.setChecked(False)
            self.actionMoveMultipleLayers.setEnabled(False)
            self.actionCopyMultipleLayers.setChecked(False)
            self.actionCopyMultipleLayers.setEnabled(False)

    def setupMode(self):
        layer = self.iface.legendInterface().currentLayer()
        self.currentMode.setLayer(layer)
        self.iface.mapCanvas().setMapTool(self.currentMode)

        self.currentMode.reset()
        self.currentMode.next()

    def doSetupDigitizing(self):
        if self.action.isChecked():
            self.digitizingSetup.activate()
            self.checkIsParallelEnabled()
        else:
            self.digitizingSetup.deactivate()
            self.checkIsParallelEnabled()

    def doSetupBackgroundSnapping(self):
        self.isBackgroundSnapping = self.actionBackgroundSnapping.isChecked()

    def doShowSettings(self):
        self.dlgSettings.clear()
        self.dlgSettings.show()
        result = self.dlgSettings.exec_()

    def doDrawArc(self):
        self.currentMode = self.drawArcMode
        self.setupMode()

    def doExtend(self):
        self.currentMode = self.extendMode
        self.setupMode()

    def doFillet(self):
        self.currentMode = self.filletMode
        self.setupMode()

    def doTrim(self):
        self.currentMode = self.trimMode
        self.setupMode()

    def doMirror(self):
        self.currentMode = self.mirrorMode
        self.setupMode()

    def doScale(self):
        self.currentMode = self.scaleMode
        self.setupMode()

    def doMove(self):
        self.currentMode = self.moveMode
        self.setupMode()

    def doCopy(self):
        self.currentMode = self.copyMode
        self.setupMode()

    def doMoveMultipleLayers(self):
        self.currentMode = self.moveMultipleLayersMode
        self.setupMode()

    def doCopyMultipleLayers(self):
        self.currentMode = self.copyMultipleLayersMode
        self.setupMode()

    def doParallel(self):
        if self.actionParallel.isChecked():
            self.parallelConstraintMode.activate()
        else:
            self.parallelConstraintMode.deactivate()

    def doSplit(self):
        self.currentMode = self.splitMode
        self.setupMode()

    def doCenterline(self):
        self.currentMode = self.centerlineMode
        self.setupMode()

    def doCenterlineAdvanced(self):
        self.currentMode = self.centerlineAdvancedMode
        self.setupMode()

    def doPolygonize(self):
        self.polygonizeCommand.run()

    def doIntersect(self):
        self.intersectCommand.run()

    def doExplode(self):
        self.explodeCommand.run()
Exemplo n.º 42
0
parser = argparse.ArgumentParser(description="SimpleShortcuts")
parser.add_argument("-s", "--settings",
                    help="Show the settings dialog",
                    action="store_true")
parser.add_argument("-i", "--imitate",
                    help="Show and immediately close the main window.",
                    action="store_true")

args = parser.parse_args()

app = QApplication(sys.argv)

if args.settings:
    from settingsdialog import SettingsDialog
    g = SettingsDialog()
else:
    try:
        g = MainUi()
    except Exception as err:
        print("An exception has occured!")
        print("Try opening the settings dialog with -s parameter and resaving the settings.",
              "You may have to delete your settings file as last resort."
            )
        raise err

g.show()

if args.imitate: sys.exit()

rect = app.desktop().screenGeometry()
Exemplo n.º 43
0
 def openSettings(self):
     """Open settings dialog and reload settings"""
     settingsDialog = SettingsDialog(self.settings)
     settingsDialog.exec_()
Exemplo n.º 44
0
 def on_actionConfigure_triggered(self):
     dialog = SettingsDialog(self.programSettings, self)
     dialog.exec_()
Exemplo n.º 45
0
class EarthMineQGIS(QObject):
    """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
        super(EarthMineQGIS, self).__init__()
        self.movingfeature = None
        self.iface = iface
        self.viewer = None
        self.canvas = self.iface.mapCanvas()
        self.settings = QSettings()
        # 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", "EarthMineQGIS_{}.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.pointtool = QgsMapToolEmitPoint(self.canvas)
        self.pointtool.canvasClicked.connect(self.set_viewer_location)

        self.settingsdialog = SettingsDialog(self.iface.mainWindow())

        self.actions = []
        self.menu = self.tr(u"&Earthmine")

        self.toolbar = self.iface.addToolBar(u"EarthMineQGIS")
        self.toolbar.setObjectName(u"EarthMineQGIS")

        self.legend = self.iface.legendInterface()

        emcolor = QColor(1, 150, 51)
        self.tempband = QgsRubberBand(self.canvas, QGis.Line)
        self.tempband.setWidth(5)
        self.tempband.setColor(emcolor)

        self.tempbandpoints = QgsRubberBand(self.canvas, QGis.Point)
        self.tempbandpoints.setWidth(7)
        self.tempbandpoints.setColor(emcolor)

        self.movingband = QgsRubberBand(self.canvas, QGis.Point)
        self.movingband.setWidth(5)
        self.movingband.setColor(emcolor)

        self.layersignals = []
        self.marker = None

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ":/icons/settings"
        self.add_action(
            icon_path, text=self.tr(u"Show Settings"), callback=self.show_settings, parent=self.iface.mainWindow()
        )
        icon_path = ":/icons/viewer"
        self.add_action(
            icon_path, text=self.tr(u"Earthmine Viewer"), callback=self.open_viewer, parent=self.iface.mainWindow()
        )

        self.marker = PostionMarker(self.canvas)
        self.marker.hide()

        self.viewer = Viewer(callbackobject=self)
        self.viewer.trackingChanged.connect(self.marker.setTracking)
        self.viewer.setLocationTriggered.connect(partial(self.canvas.setMapTool, self.pointtool))
        self.viewer.updateFeatures.connect(self.update_earthmine_features)
        self.viewer.layerChanged.connect(self.iface.setActiveLayer)
        self.viewer.clearLine.connect(self.clear_bands)
        self.viewer.closed.connect(self.remove_items)
        self.iface.currentLayerChanged.connect(self.viewer.update_current_layer)

        cursor = QCursor(QPixmap(":/icons/location"))
        self.pointtool.setCursor(cursor)
        self.pointtool.setAction(self.viewer.setlocationaction)

    def remove_items(self):
        self.marker.setTracking(False)
        self.disconnect_projectsignals()
        self.iface.actionPan().trigger()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        self.canvas.scene().removeItem(self.marker)
        del self.marker

        self.disconnect_projectsignals()

        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u"&Earthmine"), action)
            self.iface.removeToolBarIcon(action)

        del self.toolbar

        self.iface.removeDockWidget(self.viewer)
        self.viewer.deleteLater()

    def disconnect_projectsignals(self):
        safe_disconnect(QgsMapLayerRegistry.instance().layerWasAdded, self.connect_layer_signals)
        safe_disconnect(QgsMapLayerRegistry.instance().layersRemoved, self.layers_removed)
        safe_disconnect(self.canvas.layersChanged, self.layers_changed)
        safe_disconnect(self.iface.projectRead, self.connect_signals)
        safe_disconnect(self.canvas.selectionChanged, self.selection_changed)
        safe_disconnect(self.canvas.selectionChanged, self.viewer.selection_changed)

    def clear_bands(self):
        self.tempband.reset(QGis.Line)
        self.tempbandpoints.reset(QGis.Point)

    def visible_layers(self):
        """
        Return the visible layers shown in the map canvas
        :return:
        """
        return (layer for layer, visible in self.layers_with_states() if visible)

    def layers_with_states(self):
        for layer in maplayers():
            if not layer.type() == QgsMapLayer.VectorLayer:
                continue

            if not layer.geometryType() in [QGis.Point, QGis.Line]:
                continue

            yield layer, self.legend.isLayerVisible(layer)

    def _layer_feature_added(self, featureid):
        layer = self.sender()
        if not layer:
            return

        self.layer_feature_added(layer, featureid)

    def layer_feature_added(self, layer, featureid):
        if not self.viewer:
            return

        feature = layer.getFeatures(QgsFeatureRequest(featureid)).next()
        renderer = layer.rendererV2()
        transform = self.coordinatetransform(layer)
        featuredata = to_feature_data(layer.id(), feature, renderer, transform)
        geomtype = layer.geometryType()
        layerdata = dict(id=layer.id(), geomtype=QGis.vectorGeometryType(geomtype))
        self.viewer.load_features(layerdata, featuredata)

    def _layer_feature_delete(self, featureid):
        layer = self.sender()
        if not layer:
            return
        self.layer_feature_delete(layer, featureid)

    def layer_feature_delete(self, layer, featureid):
        if not self.viewer:
            return

        self.viewer.remove_feature(layer.id(), featureid)

    def _layer_geometry_changed(self, featureid, geometry):
        layer = self.sender()
        if not layer:
            return
        self.layer_geometry_changed(layer, featureid, geometry)

    def layer_geometry_changed(self, layer, featureid, geometry):
        if not self.viewer:
            return

        geomtype = layer.geometryType()
        if geomtype == QGis.Point:
            geom = geometry.asPoint()
            transform = self.coordinatetransform(layer)
            point = transform.transform(geom, QgsCoordinateTransform.ReverseTransform)
            location = dict(lat=point.y(), lng=point.x())
            self.viewer.edit_feature(layer.id(), featureid, [location])
        elif geomtype == QGis.Line:
            self.layer_feature_delete(layer, featureid)
            self.layer_feature_added(layer, featureid)

    def connect_layer_signals(self, layer):
        if not layer.type() == QgsMapLayer.VectorLayer:
            return

        layer.featureAdded.connect(self._layer_feature_added)
        layer.featureDeleted.connect(self._layer_feature_delete)
        layer.editingStarted.connect(self.layer_editstate_changed)
        layer.editingStopped.connect(self.layer_editstate_changed)
        # HACK The new style doesn't work here
        # http://hub.qgis.org/issues/6573
        signal = SIGNAL("geometryChanged(QgsFeatureId, QgsGeometry&)")
        self.connect(layer, signal, self._layer_geometry_changed)
        self.load_layer_features(layers=[layer])

    def layer_editstate_changed(self):
        layer = self.sender()
        if layer == self.iface.activeLayer():
            self.viewer.layer_changed(layer)

    def disconnect_signals(self):
        self.disconnect_projectsignals()

        for layer in maplayers():
            if not layer.type() == QgsMapLayer.VectorLayer:
                return

            safe_disconnect(layer.featureAdded, self._layer_feature_added)
            safe_disconnect(layer.featureDeleted, self._layer_feature_delete)
            safe_disconnect(layer.editingStarted, self.layer_editstate_changed)
            safe_disconnect(layer.editingStopped, self.layer_editstate_changed)
            # HACK The new style doesn't work here
            # http://hub.qgis.org/issues/6573
            signal = SIGNAL("geometryChanged(QgsFeatureId, QgsGeometry&)")
            self.disconnect(layer, signal, self._layer_geometry_changed)

    def connect_signals(self):
        for layer in maplayers():
            self.connect_layer_signals(layer)

        self.center_on_canvas()

    def set_viewer_location(self, point, mousebutton):
        transform = self.coordinatetransform()
        point = transform.transform(point, QgsCoordinateTransform.ReverseTransform)
        self.viewer.set_location(point)

    def distancearea(self):
        area = QgsDistanceArea()
        dest = self.canvas.mapRenderer().destinationCrs()
        area.setSourceCrs(dest)
        return area, dest.mapUnits()

    def coordinatetransform(self, layer=None):
        """
        Return the transform for WGS84 -> QGIS projection.
        """
        source = QgsCoordinateReferenceSystem()
        source.createFromWkt(
            'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]'
        )
        if not layer:
            dest = self.canvas.mapRenderer().destinationCrs()
        else:
            dest = layer.crs()
        transform = QgsCoordinateTransform(source, dest)
        return transform

    def earthmine_settings(self):
        settings = {}
        with settinggroup(self.settings, "plugins/Earthmine"):
            for key in ["serviceUrl", "baseDataUrl", "apiKey", "secretKey", "viewerUrl"]:
                if not self.settings.contains(key):
                    raise EarthmineSettingsError("{} not set".format(key))

                value = self.settings.value(key, type=str)
                if value is None:
                    raise EarthmineSettingsError("{} not set".format(key))

                settings[key] = value

        return settings

    @pyqtSlot()
    def ready(self):
        """
        Called when the viewer is ready to be started.  At this point the viewer hasn't been loaded
        so no other methods apart from startViewer will be handled.
        """
        settings = self.earthmine_settings()
        self.viewer.startViewer(settings)

    @pyqtSlot()
    def viewerReady(self):
        """
        Called once the viewer is loaded and ready to get location events.
        """
        self.disconnect_signals()
        self.connect_signals()
        self.iface.projectRead.connect(self.connect_signals)
        self.canvas.layersChanged.connect(self.layers_changed)
        self.canvas.selectionChanged.connect(self.selection_changed)
        self.canvas.selectionChanged.connect(self.viewer.selection_changed)
        QgsMapLayerRegistry.instance().layersRemoved.connect(self.layers_removed)
        QgsMapLayerRegistry.instance().layerWasAdded.connect(self.connect_layer_signals)
        self.center_on_canvas()
        self.viewer.activelayercombo.setLayer(self.iface.activeLayer())

    def center_on_canvas(self):
        point = self.canvas.extent().center()
        transform = self.coordinatetransform()
        point = transform.transform(point, QgsCoordinateTransform.ReverseTransform)
        self.viewer.set_location(point)
        self.viewer.infoaction.toggle()

    def selection_changed(self, layer):
        ids = [feature.id() for feature in layer.selectedFeatures()]
        if not ids:
            self.viewer.clear_selection(layer.id())
        else:
            self.viewer.set_selection(layer.id(), ids)

    def layers_changed(self):
        layerstates = self.layers_with_states()
        for layer, visible in layerstates:
            layerid = layer.id()
            viewerloaded = self.viewer.layer_loaded(layerid)
            QgsMessageLog.instance().logMessage(layerid, "Earthmine")
            QgsMessageLog.instance().logMessage("Viewer State:" + str(viewerloaded), "Earthmine")
            QgsMessageLog.instance().logMessage("QGIS State:" + str(visible), "Earthmine")
            if (viewerloaded and visible) or (not viewerloaded and not visible):
                QgsMessageLog.instance().logMessage("Ignoring as states match", "Earthmine")
                continue

            if viewerloaded and not visible:
                QgsMessageLog.instance().logMessage(
                    "Clearing layer because viewer loaded and disabled in QGIS", "Earthmine"
                )
                self.viewer.clear_layer_features(layerid)
                continue

            if not viewerloaded and visible:
                QgsMessageLog.instance().logMessage("Loading layer", "Earthmine")
                self.load_layer_features(layers=[layer])
                continue

    def layers_removed(self, layers):
        for layerid in layers:
            self.viewer.clear_layer_features(layerid)

    @pyqtSlot(str, float, float)
    def viewChanged(self, event, yaw, angle):
        self.marker.setAngle(angle)
        self.marker.setYaw(yaw)

    @pyqtSlot(str, str)
    def getInfo(self, layerid, featureid):
        featureid = int(featureid)
        activelayer = self.iface.activeLayer()
        if not activelayer:
            return

        activetool = self.viewer.active_tool()
        if not activetool in ["Info", "Select"]:
            return

        # Only show information for the active layer
        if not layerid == activelayer.id():
            return

        layer = layer_by_id(layerid)
        if activetool == "Select":
            layer.setSelectedFeatures([featureid])
        elif activetool == "Info":
            rq = QgsFeatureRequest(featureid)
            feature = layer.getFeatures(rq).next()
            dlg = get_feature_form(layer, feature)
            if dlg.dialog().exec_():
                self.canvas.refresh()

    @pyqtSlot(str, str, float, float, bool)
    def featureMoved(self, layerid, featureid, lat, lng, end):
        layer = layer_by_id(layerid)
        transform = self.coordinatetransform(layer)
        point = transform.transform(lng, lat)
        if not end:
            self.movingband.show()
            self.movingband.setToGeometry(QgsGeometry.fromPoint(point), layer)
            self.movingband.updatePosition()
            self.movingband.update()
        else:
            self.movingband.hide()
            feature = feature_by_id(layer, featureid)
            startpoint = feature.geometry().asPoint()
            dx = point.x() - startpoint.x()
            dy = point.y() - startpoint.y()
            layer.beginEditCommand("Feature Moved")
            # Block signals for this move as the geometry changed signal will re add the geometry on use.
            layer.blockSignals(True)
            layer.translateFeature(feature.id(), dx, dy)
            layer.blockSignals(False)
            self.canvas.refresh()
            layer.endEditCommand()

    @pyqtSlot(str, str)
    def onError(self, message, stacktrace=None):
        self.iface.messageBar().pushMessage("Earthmine", message, QgsMessageBar.WARNING)
        QgsMessageLog.logMessage(stacktrace, "Earthmine")

    @pyqtSlot(float, float, float)
    def addPoint(self, lat, lng, z):
        layer = self.viewer.active_layer
        if not layer.isEditable():
            self.iface.messageBar().pushMessage(
                "Earthmine",
                "Selected layer isn't editable. Please enable edit mode to add features",
                duration=3,
                level=QgsMessageBar.WARNING,
            )
            return

        transform = self.coordinatetransform(layer)
        point = transform.transform(lng, lat)
        geom = QgsGeometry.fromPoint(point)
        self.add_feature(layer, geom, z)

    def add_feature(self, layer, geom, z=None):
        feature = QgsFeature(layer.pendingFields())
        if z and self.viewer.copyZvalue:
            try:
                feature["Z"] = z
            except KeyError:
                QgsMessageLog.log("No Z found on layer {}".format(layer.name()))
                pass

        feature.setGeometry(geom)
        dlg = get_feature_form(layer, feature, isadd=True)
        if dlg.dialog().exec_():
            self.canvas.refresh()

    @pyqtSlot(str, bool, str)
    def drawLine(self, points, end, stats):
        points = json.loads(points)
        stats = json.loads(stats)
        QgsMessageLog.logMessage(str(stats), "Earthmine")
        self.tempband.reset(QGis.Line)
        self.tempbandpoints.reset(QGis.Point)
        color = QColor(self.viewer.current_action_color)
        self.tempband.setColor(color)
        self.tempbandpoints.setColor(color)

        layer = self.viewer.active_layer
        transform = self.coordinatetransform(layer)
        earthminepoints = []
        for point in points:
            newpoint = transform.transform(point["lng"], point["lat"])
            self.tempband.addPoint(newpoint)
            self.tempbandpoints.addPoint(newpoint)
            empoint = EarthminePoint(newpoint, point)
            earthminepoints.append(empoint)

        if end and not self.viewer.mode == "Vertical":
            geom = self.tempband.asGeometry()
            self.add_feature(layer, geom)
            self.clear_bands()

        self.viewer.geom = EarthmineLine(earthminepoints, stats)

        self.tempband.show()
        self.tempbandpoints.show()

    @pyqtSlot(str, str, str, float)
    def locationChanged(self, lat, lng, yaw, angle):
        transform = self.coordinatetransform()
        point = transform.transform(float(lng), float(lat))
        self.marker.setCenter(point)
        yaw = float(yaw)
        self.marker.setAngle(angle)
        self.marker.setYaw(yaw)
        self.marker.setTracking(self.viewer.tracking)

        if self.marker.tracking:
            rect = QgsRectangle(point, point)
            extentlimt = QgsRectangle(self.canvas.extent())
            extentlimt.scale(0.95)

            if not extentlimt.contains(point):
                self.canvas.setExtent(rect)
                self.canvas.refresh()

        # Clear old features
        self.viewer.clear_features()
        self.load_layer_features(point)

    def update_earthmine_features(self, viewfeatures):
        self.viewer.clear_features()

        if viewfeatures:
            self.load_layer_features()

    def load_layer_features(self, point=None, layers=None):

        # TODO Move this logic into the viewer and let it track it's position
        if point is None and self.marker.map_pos is None:
            return

        if point is None:
            point = self.marker.map_pos

        area, units = self.distancearea()
        rect = search_area(units, area, point)

        if layers is None:
            layers = self.visible_layers()

        for layer in layers:
            transform = self.coordinatetransform(layer)
            # Transform the rect
            source = self.canvas.mapRenderer().destinationCrs()
            dest = layer.crs()
            recttransform = QgsCoordinateTransform(source, dest)
            rect = recttransform.transformBoundingBox(rect)
            features = list(get_features_in_area(layer, rect, transform, self.canvas.mapSettings()))
            geomtype = layer.geometryType()
            layerdata = dict(id=layer.id(), geomtype=QGis.vectorGeometryType(geomtype))
            self.viewer.load_features(layerdata, features)

    # 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("EarthMineQGIS", 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 InaSAFE 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 s, "Earhtmine"how 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 open_viewer(self):
        """Run method that performs all the real work"""
        try:
            settings = self.earthmine_settings()
        except EarthmineSettingsError as ex:
            self.onError(ex.message)
            self.show_settings()
            return

        url = settings["viewerUrl"]
        if not url.startswith("http"):
            url = url.replace("\\\\", "\\")
            url = QUrl.fromLocalFile(url)
        else:
            url = QUrl(url)

        if not self.viewer.isVisible():
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.viewer)

        self.viewer.loadviewer(url)

    def show_settings(self):
        self.settingsdialog.show()
Exemplo n.º 46
0
 def setting(self):
     from settingsdialog import SettingsDialog
     dialog = SettingsDialog(self.iface)
     dialog.show()
     dialog.exec_()
Exemplo n.º 47
0
class PreencheSelecionada:
    """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',
                                   'PreencheSelecionada_{}.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'&Preenche feicoes selecionadas')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'PreencheSelecionada')
        self.toolbar.setObjectName(u'PreencheSelecionada')

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

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

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

        # Cria ação para menu de ajustes
        self.settingsAction = QAction("Configura", self.iface.mainWindow())
        self.settingsAction.setObjectName("preencheSelecionadaAction")
        self.settingsAction.triggered.connect(self.openSettings)

        # Adiciona menu de ajustes na barra Vetor
        self.iface.addPluginToMenu("&PreencheSelecionada: Usuario e Senha",
                                   self.settingsAction)

    def openSettings(self):
        # button signals in SettingsDialog were not working on Win7/64
        # if SettingsDialog was created with iface.mainWindow() as parent
        #self.settingsDialog = SettingsDialog(self.iface.mainWindow())
        self.settingsDialog = SettingsDialog()
        self.settingsDialog.show()

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

    def run(self):
        """Roda método que faz todo o trabalho real"""
        """Executa tarefas antes de apertar o OK da janela do Complemento"""

        # Pega camada ativa na legenda
        camadaAtiva = self.iface.activeLayer()

        # Se não tiver nenhuma camada ativa selecionada (se não tiver nenhum dataProvider) acusa erro
        try:
            provedor = camadaAtiva.dataProvider()
        except:
            QMessageBox.information(self.iface.mainWindow(), 'Aviso',
                                    'Selecione alguma camada')
            return

        # Se o dataProvider da camada não for Postgres também acusa erro
        if provedor.name() != 'postgres':
            QMessageBox.information(
                self.iface.mainWindow(), 'Aviso',
                'Selecione uma camada com conexao PostGIS')
            return

        # Cria mesma URI da camada ativa
        uri_camadaAtiva = QgsDataSourceURI(
            camadaAtiva.dataProvider().dataSourceUri())
        # print uri_camadaAtiva

        # Pega tabela selecionada para ser usada como dado da consulta
        tabela = uri_camadaAtiva.table()
        esquema = uri_camadaAtiva.schema()
        #print 'Tabela = ', uri.table()
        #print 'Esquema = ', uri.schema()

        # Estabelece nomes a serem usados na cláusula WHERE da consulta
        ultima_letra_geom = tabela[-1]
        dic_geom = {'a': 'poligono', 'p': 'ponto', 'l': 'linha'}
        sigla_classe = tabela[0:-2]
        #print 'sigla_classe = ', sigla_classe
        #print ultima_letra_geom, 'vamos ver: ', dic_geom[ultima_letra_geom]

        # Lista de camadas presente na legenda
        camadasAbertas = self.iface.legendInterface().layers()
        #for camada in camadasAbertas:
        #    print camada.name()

        # Percorre camadas na legenda para determinar se existe a mesma classe da camada selecionada em outra escala. Caso ela exista a URI dela será adicionada
        # para InfoUriCamadasOutraEscala e o objeto da camada será adicionado para CamadasOutraEscala
        InfoUriCamadasOutraEscala = []
        CamadasOutraEscala = []

        for camadaLegenda in camadasAbertas:
            try:
                uri_camadaLegenda = QgsDataSourceURI(
                    camadaLegenda.dataProvider().dataSourceUri())

                # Testa para ver se é mesma camada só que em outra escala - Não está funcionando ainda
                if uri_camadaAtiva.table() == uri_camadaLegenda.table(
                ) and uri_camadaAtiva.schema() != uri_camadaLegenda.schema():
                    # print 'Tabela_selecao: ', uri.table(), ' Esquema_selecao: ', uri.schema(), ' diferente de Tabela_legenda: ', uri_camadaLegenda.table(), ' Esquema_legenda: ', uri_camadaLegenda.schema()
                    #QMessageBox.information(self.iface.mainWindow(), 'Aviso', 'Tem mesma(s) camada(s) em escala diferente')
                    if uri_camadaLegenda.uri(
                    ) not in InfoUriCamadasOutraEscala:
                        # print 'Vou adicionar camada'
                        InfoUriCamadasOutraEscala.append(uri_camadaLegenda)
                        CamadasOutraEscala.append(camadaLegenda)
                    else:
                        # print 'Não vou adicionar camada'
                        pass
            except:
                pass

        #print InfoUriCamadasOutraEscala
        #print CamadasOutraEscala

        mensagem_uri = ''
        for uri in InfoUriCamadasOutraEscala:
            #print uri
            mensagem_uri = mensagem_uri + 'tabela: ' + uri.table(
            ) + '; esquema: ' + uri.schema() + '\n'

        #print 'Camadas iguais em escalas diferentes: ' + mensagem_uri
        QMessageBox.information(
            self.iface.mainWindow(), 'Aviso',
            'Tem mesma(s) camada(s) em escala diferente: \n' + mensagem_uri)

        # Cria uma conexão ao Postgres através de QSqlDatabase - QPSQL se refere ao Postgres
        db = QSqlDatabase.addDatabase("QPSQL")

        # Dados da conexão são os mesmos da camada ativa (mesmo servidor, mesmo banco e mesma porta)
        db.setHostName(uri_camadaAtiva.host())
        db.setDatabaseName(uri_camadaAtiva.database())
        db.setPort(int(uri_camadaAtiva.port()))

        # Pega nome e senha de usuários nas configurações do plugin
        usuario = QSettings().value(SETTINGS_NAME + "/usuario",
                                    DEFAULT_USUARIO)
        senha = QSettings().value(SETTINGS_NAME + "/senha", DEFAULT_SENHA)
        #print usuario, senha

        # Estabelece usuário e senha para conexão com o banco
        db.setUserName(usuario)
        db.setPassword(senha)

        # Feições selecionadas
        selecao = camadaAtiva.selectedFeatures()
        #print selecao
        selecao_outras_camadas = [
            camada.selectedFeatures() for camada in CamadasOutraEscala
        ]
        #print "Selecao outras camadas = ", selecao_outras_camadas

        # cria lista do id_objeto das feições selecionadas de todas as classes iguais de escalas diferentes presentes na legenda
        lista_id_objeto = [feicao['id_objeto'] for feicao in selecao]
        lista_id_objeto_outras_camadas = [[
            feicao['id_objeto'] for feicao in camada
        ] for camada in selecao_outras_camadas]
        #print 'lista_id_objeto_outras_camadas = ', lista_id_objeto_outras_camadas
        #lista_unica_id_objeto_outras_camadas = [id_objeto for elemento in lista_id_objeto_outras_camadas for id_objeto in elemento]
        #lista_unica_id_objeto = lista_id_objeto + lista_unica_id_objeto_outras_camadas

        #print lista_id_objeto, type(lista_id_objeto[0])

        # converte elementos da lista de id_objeto em string para usá-los na consulta
        lista_id_objeto = [str(el) for el in lista_id_objeto]
        lista_id_objeto_string = ','.join(lista_id_objeto)

        lista_id_objeto_outras_camadas = [[
            str(subel) for subel in el
        ] for el in lista_id_objeto_outras_camadas]
        #print 'Lista de objetos de outras camadas =', lista_id_objeto_outras_camadas

        #lista_unica_id_objeto = [str(el) for el in lista_unica_id_objeto]
        #lista_unica_id_objeto_string = ','.join(lista_unica_id_objeto)

        #print 'vou conectar no banco'

        # Abre conexão ao banco de dados para adicionar os esquemas que têm tabelas espaciais contidos lá
        if db.open():
            # Tenho que rever essa consulta
            string_consulta = "SELECT id_objeto_producao, id_nomebngb, nm_geografico_producao, cd_validacao_operador, tx_apontamento_crng FROM bngb_interface.t_interface WHERE id_objeto_producao IN (" + lista_id_objeto_string + ") " + \
            "AND nm_esquema_base = '" + esquema + "' AND concat_ws('_', nm_sigla_categoria, nm_classe) ILIKE '" + sigla_classe + "' AND tp_geom ILIKE '" + dic_geom[ultima_letra_geom] +"' "
            #print "string consulta exibir comboBox = ", string_consulta
            msg_add = ""
            for indice, uri in enumerate(InfoUriCamadasOutraEscala):
                # Verifica se a lista de id_objeto contém algum valor (alguma seleção)
                if lista_id_objeto_outras_camadas[indice]:
                    msg_add = msg_add + "UNION SELECT id_objeto_producao, id_nomebngb, nm_geografico_producao, cd_validacao_operador, tx_apontamento_crng FROM bngb_interface.t_interface WHERE id_objeto_producao IN (" + ','.join(lista_id_objeto_outras_camadas[indice]) + ") " + \
                    "AND nm_esquema_base = '" + uri.schema() + "' AND concat_ws('_', nm_sigla_categoria, nm_classe) ILIKE '" + sigla_classe + "' AND tp_geom ILIKE '" + dic_geom[ultima_letra_geom] +"' "

            string_consulta = string_consulta + msg_add
            #print string_consulta

            #print string_consulta
            consulta = db.exec_(
                string_consulta)  #IN (" + lista_id_objeto_string + ")")

            resultado_consulta = []

            # Adiciona resultados da consulta (id_objeto_producao, id_nomebngb, nm_geografico_producao)
            # na lista Python para posterior adição à comboBox
            while consulta.next():
                record = consulta.record()

                #print 'Comecando'
                # Pega o id_objeto_producao (na tabela t_interface) correspondente ao id_objeto das feições selecionadas
                id_objeto_producao = str(
                    record.field('id_objeto_producao').value()).decode("utf-8")
                #print id_objeto_producao, ' - tipo ', type(id_objeto_producao)

                # Pega id_nomebngb
                id_nomebngb = str(
                    record.field('id_nomebngb').value()).decode("utf-8")
                #print id_nomebngb, ' - tipo ', type(id_nomebngb)

                # Pega nm_geografico_producao
                if isinstance(
                        record.field('nm_geografico_producao').value(),
                        QPyNullVariant):
                    nome_bngb = str(
                        record.field('nm_geografico_producao').value()).decode(
                            "utf-8")
                    #print nome_bngb, ' - tipo1 ', type(nome_bngb)

                else:
                    nome_bngb = record.field('nm_geografico_producao').value()
                    #print nome_bngb, ' - tipo1 ', type(nome_bngb)

                cd_validacao_operador = str(
                    record.field('cd_validacao_operador').value()).decode(
                        "utf-8")

                if isinstance(
                        record.field('tx_apontamento_crng').value(),
                        QPyNullVariant):
                    tx_apontamento_crng = str(
                        record.field('tx_apontamento_crng').value()).decode(
                            "utf-8")
                    #print nome_bngb, ' - tipo1 ', type(nome_bngb)

                else:
                    tx_apontamento_crng = record.field(
                        'tx_apontamento_crng').value()
                    #print nome_bngb, ' - tipo1 ', type(nome_bngb)

                # Tupla a ser adicionada para a lista que será posteriormente adicionada à ComboBox
                tupla_add = (id_objeto_producao, id_nomebngb, nome_bngb,
                             cd_validacao_operador, tx_apontamento_crng)
                resultado_consulta.append(tupla_add)

            #print 'Resultado da consulta = ', resultado_consulta

            # Parei aqui. Até aqui tudo bem, resultado_consulta guarda a tupla (id_objeto_producao, id_nomebngb, nome_bngb) da t_interface referente a todos os registros selecionados nas diversas camadas da legenda que se referem a uma classe em escalas distintas
            # Cria lista de strings a partir de resultado_consulta para adição à ComboBox
            resultado_consulta_string = []
            for el in resultado_consulta:
                item_comboBox = el[0] + '\ ' + el[1] + '\ ' + el[
                    2] + '\ ' + el[3] + '\ ' + el[4]
                resultado_consulta_string.append(item_comboBox)

            #print resultado_consulta_string

            # Limpa e adiciona elementos na Combo Box (caixa de opção)
            self.dlg.comboBox.clear()
            self.dlg.comboBox.addItems(resultado_consulta_string)

            # Indica na caixa de diálogo uma linha para mostrar a camada que está sendo editada na t_interface
            self.dlg.lineEdit.clear()
            self.dlg.lineEdit.setText(uri_camadaAtiva.schema() + '.' +
                                      uri_camadaAtiva.table())
        else:
            QMessageBox.information(self.iface.mainWindow(), 'Aviso',
                                    'Conexao rejeitada')
            return

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        """ Executa tarefas caso o OK seja pressionado """
        if result:

            # Pega índice e tupla (id_objeto_producao, id_nomebngb, nm_geografico_producao) escolhidos no ComboBox
            indice = self.dlg.comboBox.currentIndex()
            stringSelecionada = resultado_consulta_string[indice]

            #print 'String Selecionada = ', stringSelecionada

            # Transforma opção selecionada na ComboBox em lista
            listastringSelecionada = stringSelecionada.split("\ ")
            #print 'Lista selecionada =', listastringSelecionada
            #print 'Lista selecionada[2] =', listastringSelecionada[2], 'tipo = ', type(listastringSelecionada[2])
            listastringSelecionada[2] = listastringSelecionada[2].replace(
                "'", "''")
            listastringSelecionada[4] = listastringSelecionada[4].replace(
                "'", "''")
            print listastringSelecionada[4]

            #print 'Lista selecionada[2] depois =', listastringSelecionada[2], 'tipo = ', type(listastringSelecionada[2])
            print
            print
            print

            # Estabelece string para consulta na Camada Ativa (nm_geografico_producao e tx_apontamento_crng podem ser nulos)
            if listastringSelecionada[2] == 'NULL':
                string_consulta = "UPDATE bngb_interface.t_interface SET cd_validacao_operador = '" + listastringSelecionada[
                    3] + "', id_nomebngb = " + listastringSelecionada[
                        1] + ", nm_geografico_producao = " + listastringSelecionada[
                            2]
                #print "UPDATE referente à camada ativa =", string_consulta
            else:
                string_consulta = "UPDATE bngb_interface.t_interface SET cd_validacao_operador = '" + listastringSelecionada[
                    3] + "', id_nomebngb = " + listastringSelecionada[
                        1] + ", nm_geografico_producao = '" + listastringSelecionada[
                            2] + "'"
                #print "UPDATE referente à camada ativa =", string_consulta

            if listastringSelecionada[4] == 'NULL':
                string_consulta = string_consulta + ", tx_apontamento_crng = " + listastringSelecionada[4] + \
                " WHERE id_objeto_producao IN (" + lista_id_objeto_string + ") " + \
                "AND nm_esquema_base = '" + esquema  + "' AND concat_ws('_', nm_sigla_categoria, nm_classe) ILIKE '" + sigla_classe + "' AND tp_geom ILIKE '" + dic_geom[ultima_letra_geom] +"'"
                print u"UPDATE referente à camada ativa =", string_consulta
            else:
                string_consulta = string_consulta + ", tx_apontamento_crng = '" + listastringSelecionada[4] + \
                "' WHERE id_objeto_producao IN (" + lista_id_objeto_string + ") " + \
                "AND nm_esquema_base = '" + esquema  + "' AND concat_ws('_', nm_sigla_categoria, nm_classe) ILIKE '" + sigla_classe + "' AND tp_geom ILIKE '" + dic_geom[ultima_letra_geom] +"'"
                print u"UPDATE referente à camada ativa =", string_consulta

            # Executa atualização (update)
            db.exec_(string_consulta)

            # Percorre a mesma classe nas outras escalas
            for indice, uri in enumerate(InfoUriCamadasOutraEscala):
                # Verifica se a lista de id_objeto contém algum valor (alguma seleção)
                if lista_id_objeto_outras_camadas[indice]:
                    if listastringSelecionada[2] == 'NULL':
                        string_consulta = "UPDATE bngb_interface.t_interface SET cd_validacao_operador = '" + listastringSelecionada[
                            3] + "', id_nomebngb = " + listastringSelecionada[
                                1] + ", nm_geografico_producao = " + listastringSelecionada[
                                    2]
                        #print "UPDATE referente à camada auxiliar = ", string_consulta
                    else:
                        string_consulta = "UPDATE bngb_interface.t_interface SET cd_validacao_operador = '" + listastringSelecionada[
                            3] + "', id_nomebngb = " + listastringSelecionada[
                                1] + ", nm_geografico_producao = '" + listastringSelecionada[
                                    2] + "'"
                        #print "UPDATE referente à camada auxiliar = ", string_consulta

                    if listastringSelecionada[4] == 'NULL':
                        string_consulta = string_consulta + ", tx_apontamento_crng = " + listastringSelecionada[4] + \
                        " WHERE id_objeto_producao IN (" + ','.join(lista_id_objeto_outras_camadas[indice]) + ") " + \
                        "AND nm_esquema_base = '" + uri.schema()  + "' AND concat_ws('_', nm_sigla_categoria, nm_classe) ILIKE '" + sigla_classe + "' AND tp_geom ILIKE '" + dic_geom[ultima_letra_geom] +"'"
                        print u"UPDATE referente à camada auxiliar =", string_consulta
                    else:
                        string_consulta = string_consulta + ", tx_apontamento_crng = '" + listastringSelecionada[4] + \
                        "' WHERE id_objeto_producao IN (" + ','.join(lista_id_objeto_outras_camadas[indice]) + ") " + \
                        "AND nm_esquema_base = '" + uri.schema()  + "' AND concat_ws('_', nm_sigla_categoria, nm_classe) ILIKE '" + sigla_classe + "' AND tp_geom ILIKE '" + dic_geom[ultima_letra_geom] +"'"
                        print u"UPDATE referente à camada auxiliar =", string_consulta

                    # Executa atualização (update)
                    db.exec_(string_consulta)
 def initParameters(self):
     from settingsdialog import SettingsDialog
     dialog = SettingsDialog(self.iface)
     accepted = dialog.exec_()
     if not accepted:
         return False
Exemplo n.º 49
0
parser.add_argument("-s",
                    "--settings",
                    help="Show the settings dialog",
                    action="store_true")
parser.add_argument("-i",
                    "--imitate",
                    help="Show and immediately close the main window.",
                    action="store_true")

args = parser.parse_args()

app = QApplication(sys.argv)

if args.settings:
    from settingsdialog import SettingsDialog
    g = SettingsDialog()
else:
    try:
        g = MainUi()
    except Exception as err:
        print("An exception has occured!")
        print(
            "Try opening the settings dialog with -s parameter and resaving the settings.",
            "You may have to delete your settings file as last resort.")
        raise err

g.show()

if args.imitate: sys.exit()

rect = app.desktop().screenGeometry()
Exemplo n.º 50
0
 def pluginSettings(self):
     from settingsdialog import SettingsDialog
     dialog = SettingsDialog(self)
     if dialog.exec_():
         self.pluginManager.reloadPlugins()
         self.pages[ppages.PAGE_DEM].initLayerComboBox()
Exemplo n.º 51
0
 def on_actionConfigure_triggered(self):
     dialog = SettingsDialog(self.programSettings, self)
     dialog.rowHeightChanged.connect(self.setRowHeight)
     dialog.exec_()
Exemplo n.º 52
0
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, app = None, silence = False):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.iface = backend.pm.Iface()
        self.setWindowIcon(QtGui.QIcon(":/data/package-manager.png"))
        self.connect(app, SIGNAL("aboutToQuit()"), self.slotQuit)
        self.setCentralWidget(MainWidget(self, silence))
        self.initializeActions()

        if not silence:
            self.settingsDialog = SettingsDialog(self)
            self.initializeStatusBar()
            self.initializeTray()
            self.connectMainSignals()

    def connectMainSignals(self):
        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.centralWidget().updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.centralWidget().state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayAction)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)
        self.centralWidget().switchState(StateManager.UPGRADE, action=False)
        self.centralWidget().initialize()
        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in ["System.Manager.updatePackage",
                                                   "System.Manager.installPackage",
                                                   "System.Manager.removePackage"]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.statusLabel = QtGui.QLabel(i18n("Currently your basket is empty."), self.statusBar())
        self.statusLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.statusBar().addWidget(self.statusLabel)
        self.statusBar().setSizeGripEnabled(True)
        self.wheelMovie = QtGui.QMovie(self)
        self.statusLabel.setText(i18n("Currently your basket is empty."))
        self.wheelMovie.setFileName(":/data/wheel.mng")
        self.connect(self.centralWidget(), SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.centralWidget(), SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar = QtGui.QToolBar(self)
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)

        self.initializeOperationActions()

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.menubar = QtGui.QMenuBar(self)

        self.menuFile = QtGui.QMenu(i18n('File'), self.menubar)
        self.menuOptions = QtGui.QMenu(i18n('Settings'), self.menubar)
        self.menuHelp = QtGui.QMenu(i18n('Help'), self.menubar)

        self.quitAppAction = QtGui.QAction(KIcon(('exit', 'application-exit')), i18n("Quit"), self)
        self.quitAppAction.setShortcut(QtGui.QKeySequence('Ctrl+q'))
        self.quitAppAction.triggered.connect(self.slotQuit)

        self.helpAppAction = QtGui.QAction(KIcon(('help', 'help-contents')), i18n("Help"), self)
        self.helpAppAction.setShortcut(QtGui.QKeySequence('F1'))
        self.helpAppAction.triggered.connect(self.showHelp)
        self.menuHelp.addAction(self.helpAppAction)

        self.setMenuBar(self.menubar)

        # Action Show Installable Packages
        self.showInstallAction = QtGui.QAction(KIcon("list-add"),
                          i18n("Show Installable Packages"), self)
        self.showInstallAction.setCheckable(True)
        self.showInstallAction.setChecked(True)
        self.showInstallAction.triggered.connect(lambda:self.centralWidget().switchState(StateManager.INSTALL))
        actionGroup.addAction(self.showInstallAction)
        self.toolBar.addAction(self.showInstallAction)
        self.menuFile.addAction(self.showInstallAction)

        # Action Show Installed Packages
        self.showRemoveAction = QtGui.QAction(KIcon("list-remove"),
                          i18n("Show Installed Packages"), self)
        self.showRemoveAction.setCheckable(True)
        self.showRemoveAction.triggered.connect(lambda:self.centralWidget().switchState(StateManager.REMOVE))
        actionGroup.addAction(self.showRemoveAction)
        self.toolBar.addAction(self.showRemoveAction)
        self.menuFile.addAction(self.showRemoveAction)

        # Action Show Upgradable Packages
        self.showUpgradeAction = QtGui.QAction(KIcon("view-refresh"),
                          i18n("Show Upgradable Packages"), self)
        self.showUpgradeAction.setCheckable(True)
        self.showUpgradeAction.triggered.connect(lambda:self.centralWidget().switchState(StateManager.UPGRADE))
        actionGroup.addAction(self.showUpgradeAction)
        self.toolBar.addAction(self.showUpgradeAction)
        self.menuFile.addAction(self.showUpgradeAction)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.quitAppAction)

        self.showSettingsAction = QtGui.QAction(KIcon("preferences-system"),
                          i18n("Package Manager Settings"), self)
        self.showSettingsAction.triggered.connect(self.showSettingsDialog)
        self.menuOptions.addAction(self.showSettingsAction)

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuOptions.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

    def showSettingsDialog(self):
        self.settingsDialog.show()

    def statusWaiting(self):
        self.statusLabel.setMovie(self.wheelMovie)
        self.wheelMovie.start()

    def updateStatusBar(self, text):
        self.wheelMovie.stop()
        self.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def showHelp(self):
        helpDialog = helpdialog.HelpDialog(self, helpdialog.MAINAPP)
        helpDialog.show()

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray.notification:
                self.tray.notification.close()
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
        QtCore.QCoreApplication.quit()
Exemplo n.º 53
0
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    """Main Window for MOOSE GUI"""
    def __init__(self, loadFile=None, fileType=None):
	QtGui.QMainWindow.__init__(self)
	self.setupUi(self)
        self.setWindowIcon(QtGui.QIcon(':moose_thumbnail.png'))
        self.settingsDialog = SettingsDialog()
        self.settingsDialog.hide()
        layout = QtGui.QVBoxLayout(self.modelTreeTab)
        self.modelTreeTab.setLayout(layout)
        layout.addWidget(self.modelTreeContainerWidget)
        self.modelTreeWidget.headerItem().setHidden(True)
        self.plotUpdateIntervalLabel.setText(self.tr('<br>Plot update interval (<b>steps</b>)'))
        self.runTimeLabel.setText(self.tr('<br>Run for (<b>seconds</b>)'))
#         self.modelTreeWidget.show()
#         self.mooseClassToolBox.show()
###################
#         self.plotsLayout = QtGui.QHBoxLayout(self.plotsGroupBox)
#         self.plotsGroupBox.setLayout(self.plotsLayout)
#         self.plotsScrollArea = QtGui.QScrollArea(self.plotsGroupBox)
#         self.plotsLayout.addWidget(self.plotsScrollArea)
#         self.plots = MoosePlots(self.plotsScrollArea)
#         self.plotsScrollArea.setWidget(self.plots)
#         self.plots.show()
##################
        self.plots = MoosePlots(self.plotsGroupBox)
        self.plotsLayout = QtGui.QHBoxLayout(self.plotsGroupBox)
        self.plotsGroupBox.setLayout(self.plotsLayout)
        self.plotsLayout.addWidget(self.plots)
        
######################
        self.plots.show()
        self.isModelLoaded = False
        self.stopFlag = False
	self.mooseHandler = MHandler()
        self.runTimeLineEdit.setText(self.tr(str(self.mooseHandler.runTime)))
        self.plotUpdateIntervalLineEdit.setText(self.tr(str(self.mooseHandler.updateInterval)))
	self.currentDirectory = '.'
	self.fileType = fileType
	self.fileTypes = MHandler.file_types
	self.filter = ''
	self.setupActions()
        if loadFile is not None and fileType is not None:
            self.load(loadFile, fileType)


    def setupActions(self):
	self.connect(self.actionQuit,
		     QtCore.SIGNAL('triggered()'), 
		     QtGui.qApp, 
		     QtCore.SLOT('closeAllWindows()'))		     
	self.connect(self.actionLoad, 
		     QtCore.SIGNAL('triggered()'),		   
		     self.loadFileDialog)
	self.connect(self.actionSquid_Axon,
		     QtCore.SIGNAL('triggered()'),
		     self.loadSquid_Axon_Tutorial)
	self.connect(self.actionIzhikevich_Neurons,
		     QtCore.SIGNAL('triggered()'),
		     self.loadIzhikevich_Neurons_Tutorial)
        self.connect(self.actionGLCell,
                     QtCore.SIGNAL('triggered()'),
                     self.loadGLCellDemo)
        self.connect(self.actionGLView,
                     QtCore.SIGNAL('triggered()'),
                     self.loadGLViewDemo)
	self.connect(self.actionAbout_MOOSE,
		     QtCore.SIGNAL('triggered()'),
		     self.showAbout_MOOSE)
	self.connect(self.actionReset,
		     QtCore.SIGNAL('triggered()'),
		     self.reset)
	self.connect(self.actionStart,
		     QtCore.SIGNAL('triggered()'),
		     self.run)
        self.connect(self.actionStop,
                     QtCore.SIGNAL('triggered()'),
                     self.stop)
        self.connect(self.runPushButton,
                     QtCore.SIGNAL('clicked()'),
                     self.run)
        self.connect(self.resetPushButton,
                     QtCore.SIGNAL('clicked()'),
                     self.reset)
#         self.connect(self.stopPushButton,
#                      QtCore.SIGNAL('clicked()'),
#                      self.mooseHandler.stop)
        self.connect(self.plotUpdateIntervalLineEdit,
                     QtCore.SIGNAL('editingFinished()'),
                     self.plotUpdateIntervalSlot)
        self.connect(self.modelTreeWidget, 
                     QtCore.SIGNAL('itemDoubleClicked(QTreeWidgetItem *, int)'),
                     self.popupPropertyEditor)
        self.connect(self.mooseHandler, 
                     QtCore.SIGNAL('updated()'), 
                     self.updatePlots)
        self.connect(self.runTimeLineEdit, 
                     QtCore.SIGNAL('editingFinished()'),
                     self.runTimeSlot)
        self.connect(self.rescalePlotsPushButton,
                     QtCore.SIGNAL('clicked()'),
                     self.plots.rescalePlots)

        self.connect(self.actionSettings,
                     QtCore.SIGNAL('triggered()'),
                     self.popupSettings)
        for listWidget in self.mooseClassToolBox.listWidgets:
            self.connect(listWidget, 
                         QtCore.SIGNAL('itemDoubleClicked(QListWidgetItem*)'), 
                         self.insertMooseObjectSlot)
        

    def popupPropertyEditor(self, item, column):
        """Pop-up a property editor to edit the Moose object in the item"""
        obj = item.getMooseObject()
        self.propertyModel = PropertyModel(obj)
        self.connect(self.propertyModel, 
                     QtCore.SIGNAL('objectNameChanged(const QString&)'),
                     item.updateSlot)
        self.propertyEditor = QtGui.QTableView()
        self.propertyEditor.setModel(self.propertyModel)
        self.propertyEditor.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.propertyEditor, QtCore.SIGNAL('customContextMenuRequested ( const QPoint&)'), self.popupFieldMenu)
        self.propertyEditor.show()

    def loadFileDialog(self):
	fileDialog = QtGui.QFileDialog(self)
	fileDialog.setFileMode(QtGui.QFileDialog.ExistingFile)
	ffilter = ''
	for key in self.fileTypes.keys():
	    ffilter = ffilter + key + ';;'
	ffilter = ffilter[:-2]
	fileDialog.setFilter(self.tr(ffilter))
        # The following version gymnastic is because QFileDialog.selectNameFilter() was introduced in Qt 4.4
        qtVersion = str(QtCore.QT_VERSION_STR).split('.')
        major = int(qtVersion[0])
        minor = int(qtVersion[1])
        if (major > 4)or ((major == 4) and (minor >= 4)):
            for key, value in self.fileTypes.items():
                if value == FileTypeChecker.type_genesis:
                    fileDialog.selectNameFilter(key)
                    break
	if fileDialog.exec_():
	    fileNames = fileDialog.selectedFiles()
	    fileFilter = fileDialog.selectedFilter()
	    fileType = self.fileTypes[str(fileFilter)]
# 	    print 'file type:', fileType
	    directory = fileDialog.directory() # Potential bug: if user types the whole file path, does it work? - no but gives error message
	    for fileName in fileNames: 
# 		print fileName
		self.load(fileName, fileType)


    def loadIzhikevich_Neurons_Tutorial(self):
#     self.mooseHandler.load('../../DEMOS/pymoose/izhikevich/Izhikevich.py', 'MOOSE')
        spath = sys.path[0] + '/../../DEMOS/pymoose/izhikevich/demogui_qt.py'
        self.mooseHandler.load(spath, 'MOOSE')
        
    def loadGLCellDemo(self):
        spath = sys.path[0] + '/demo/glcelldemo.py'
        self.mooseHandler.load(spath, 'MOOSE')

    def loadGLViewDemo(self):
        spath = sys.path[0] + '/demo/glviewdemo.py'
        self.mooseHandler.load(spath, 'MOOSE')
        


    def loadSquid_Axon_Tutorial(self):
#     self.mooseHandler.load('../../DEMOS/pymoose/squid/qtSquid.py', 'MOOSE')
       spath = sys.path[0] + '/../../DEMOS/pymoose/squid/qtSquid.py'
       self.mooseHandler.load(spath, 'MOOSE')
       
	


    def showAbout_MOOSE(self):
	about = QtCore.QT_TR_NOOP('<p>MOOSE is the Multi-scale Object Oriented Simulation Environment.</p>'
				  '<p>It is a general purpose simulation environment for computational neuroscience and chemical kinetics.</p>'
				  '<p>Copyright (C) 2003-2009 Upinder S. Bhalla. and NCBS</p>'
				  '<p>It is made available under the terms of the GNU Lesser General Public License version 2.1. See the file COPYING.LIB for the full notice.</p>'
                  '<p>homepage: <a href="http://moose.ncbs.res.in">http://moose.ncbs.res.in</a></p>')
	aboutDialog = QtGui.QMessageBox.information(self, self.tr('About MOOSE'), about)

    def plotUpdateIntervalSlot(self):
        try:
            new_interval = int(str(self.plotUpdateIntervalLineEdit.text()))
            self.plotUpdateInterval = new_interval
        except ValueError:
            print 'Update steps must be whole number.'
            self.plotUpdateIntervalLineEdit.setText(self.tr(str(self.plotUpdateInterval)))
    
    def runTimeSlot(self):
        try:
            runtime = float(str(self.runTimeLineEdit.text()))
            self.mooseHandler.runTime = runtime
        except ValueError:
            print 'Error in converting runtime to float'
            self.runTimeLineEdit.setText(self.tr(str(self.mooseHandler.updateInterval)))
        
            
    def run(self):
        #print 'Going to run'
        if not self.isModelLoaded:
            errorDialog = QtGui.QErrorMessage(self)
            errorDialog.setModal(True)
            errorDialog.showMessage('<p>You must load a model first.</p>')
            return
        # The run for update interval and replot data until the full runtime has been executed
        # But this too is unresponsive
        self.mooseHandler.run()

    def updatePlots(self):        
        """Update the plots"""
        if self.plots is not None:
            self.plots.updatePlots(self.mooseHandler)
            self.update()
        self.currentTimeLabel.setText(self.tr('Current time (seconds): %g' %  self.mooseHandler.currentTime()))

    def reset(self):
        if not self.isModelLoaded:
            QtGui.QErrorMessage.showMessage('<p>You must load a model first.</p>')
        else:
            self.mooseHandler.reset()
            self.plots.resetPlots()
        self.currentTimeLabel.setText(self.tr('Current time (seconds): %g' % self.mooseHandler.currentTime()))
                
    
    def load(self, fileName, fileType):
 #      if self.isModelLoaded:            
#            import subprocess
#            subprocess.call(['python', 'main.py', fileName, fileType])
        fileType = FileTypeChecker(str(fileName)).fileType()
        print 'File is of type:', fileType
        self.mooseHandler.context.setCwe(self.modelTreeWidget.currentItem().getMooseObject().path)
        self.mooseHandler.load(fileName, fileType)
        self.isModelLoaded = True
        self.modelTreeWidget.recreateTree()
        if fileType is FileTypeChecker.type_sbml:
            self.moleculeListWidget = QtGui.QListWidget(self)
            self.moleculeItems = []
            for molecule in self.mooseHandler.moleculeList:
                item = QtGui.QListWidgetItem(self.moleculeListWidget)
                item.setText(molecule.name)
                item.setData(QtCore.Qt.UserRole, QtCore.QVariant(self.tr(molecule.path)))
                self.moleculeItems.append(item)
            self.simulationWidget.layout().addWidget(self.moleculeListWidget)
            self.connect(self.moleculeListWidget, 
                         QtCore.SIGNAL('itemDoubleClicked(QListWidgetItem*)'),
                         self.addMoleculeInPlot)
            
            self.moleculeListWidget.show()

        self.plots.loadPlots(self.mooseHandler, fileType)
        self.currentTimeLabel.setText(self.tr('Current time (seonds): %g' % self.mooseHandler.currentTime()))
#         self.update()

    def addMoleculeInPlot(self, item):
        self.mooseHandler.createTableForMolecule(str(item.text()))
        self.plots.loadPlots(self.mooseHandler, FileTypeChecker.type_sbml)
        self.plots.setVisible(True)
        self.modelTreeWidget.recreateTree()
        self.update()

    # Until MOOSE has a way of getting stop command from outside
    def stop(self):
        self.mooseHandler.stop()

    def insertMooseObjectSlot(self, item):
        self.modelTreeWidget.insertMooseObjectSlot(item.text())

    def popupSettings(self):
        self.settingsDialog.show()
        result = self.settingsDialog.exec_()
        if result == self.settingsDialog.Accepted:
            self.mooseHandler.addSimPathList(self.settingsDialog.simPathList())

    def popupFieldMenu(self, clickpoint):
        print 'PopupFieldMenu'
        index = self.propertyEditor.indexAt(clickpoint)
        data = self.propertyModel.data(self.propertyModel.createIndex(index.row(), 0))
        print data
        menu = QtGui.QMenu(self.propertyEditor)
        self.actionPlotField = menu.addAction('Plot this field')
        self.connect(self.actionPlotField, QtCore.SIGNAL('triggered()'), self.plotThisFieldSlot)
        menu.popup(clickpoint)

    def plotThisFieldSlot(self):
        print 'plotThisFieldSlot'
        moose_object = self.modelTreeWidget.currentItem().getMooseObject()
        row = self.propertyEditor.currentIndex().row()
        index = self.propertyModel.createIndex(row, 0)
        print index.row(), index.column()
        field_name = self.propertyModel.data(index)        
        table = self.mooseHandler.createTableForMolecule(moose_object, field_name)
        print table.path
Exemplo n.º 54
0
 def showSettings(self):
     dlg = SettingsDialog(self)
     dlg.exec_()
Exemplo n.º 55
0
 def _settings_click_cb(self, widget):
     dialog = SettingsDialog(widget.get_toplevel())
     dialog.show()