class ToggleActiveLayerPlugin: def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.action = None self.tool = ToggleActiveLayerMapTool( self.iface ) def initGui(self): title = "Toggle visibility of active layer" icon = QIcon( os.path.join( os.path.dirname(__file__), 'toggleactivelayer.png' ) ) self.action = QAction( icon, title, self.iface.mainWindow() ) self.action.setObjectName( "ToggleActiveLayerPlugin" ) self.action.setWhatsThis( title ) self.action.setStatusTip( title ) self.action.triggered.connect( self.run ) # Maptool self.action.setCheckable( True ) self.tool.setAction( self.action ) self.iface.addToolBarIcon( self.action ) def unload(self): self.canvas.unsetMapTool( self.tool ) self.iface.removeToolBarIcon( self.action ) del self.action @pyqtSlot() def run(self): if self.canvas.mapTool() != self.tool: self.canvas.setMapTool( self.tool)
def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action
class MapSwipePlugin: def __init__(self, iface): def translate(): # # For create file 'qm' # 1) Define that files need for translation: mapswipetool.pro # 2) Create 'ts': pylupdate4 -verbose mapswipetool.pro # 3) Edit your translation: QtLinquist # 4) Create 'qm': lrelease *.ts # dirname = os.path.dirname( os.path.abspath(__file__) ) locale = QSettings().value("locale/userLocale") localePath = os.path.join( dirname, "i18n", "%s_%s.qm" % ( name_src, locale ) ) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.iface = iface self.canvas = iface.mapCanvas() self.action = None # Define by initGui self.tool = MapSwipeTool( self.iface ) self.prevTool = None # Define by run name_src = "mapswipetool" translate() def initGui(self): title = "Map swipe tool" icon = QIcon( os.path.join( os.path.dirname(__file__), 'mapswipetool.png' ) ) self.action = QAction( icon, title, self.iface.mainWindow() ) self.action.setObjectName( "MapSwipeTool" ) self.action.setWhatsThis( title ) self.action.setStatusTip( title ) self.action.triggered.connect( self.run ) self.menu = "&Map swipe tool" # Maptool self.action.setCheckable( True ) self.tool.setAction( self.action ) self.iface.addToolBarIcon( self.action ) self.iface.addPluginToMenu( self.menu, self.action ) def unload(self): self.canvas.unsetMapTool( self.tool ) self.iface.removeToolBarIcon( self.action ) self.iface.removePluginMenu( self.menu, self.action ) del self.action @pyqtSlot() def run(self): if self.canvas.mapTool() != self.tool: self.prevTool = self.canvas.mapTool() self.canvas.setMapTool( self.tool ) else: self.canvas.setMapTool( self.prevTool )
class ProcessingDirnoProviderPlugin: def __init__(self, iface): self.provider = DirnoAlgorithmProvider() self.iface = iface def initGui(self): Processing.addProvider(self.provider) self.profilAction = QAction(QIcon(os.path.dirname(__file__) + "/icons/iconProvider.png"), "Ajouter un profil", self.iface.mainWindow()) self.profilAction.setObjectName("dirnoAction") self.profilAction.setWhatsThis("Dirno plugin") self.profilAction.setStatusTip("This is status tip") #QObject.connect(self.profilAction, SIGNAL("triggered()"), self.run) # add toolbar button and menu item #self.iface.addToolBarIcon(self.profilAction) self.iface.addPluginToMenu("&Dirno scripts", self.profilAction) self.profilAction.triggered.connect(self.launchDirnoAlgorithProfilDialog) def unload(self): Processing.removeProvider(self.provider) self.iface.removePluginMenu("&Dirno scripts", self.profilAction) #self.iface.removeToolBarIcon(self.profilAction) def launchDirnoAlgorithProfilDialog(self): return DirnoAlgorithmProfilDialog()
def addNewAction( self, iconPath, text, callback=None, enabled=True, checkable=False, addToMenu=True, addToToolbar=True, tip=None, whatsThis=None, parent=None): """Add a toolbar icon to the toolbar""" if parent is None: parent = self.iface.mainWindow() action = QAction(QIcon(iconPath), text, parent) if tip is not None: action.setStatusTip(tip) if whatsThis is not None: action.setWhatsThis(whatsThis) if callback is not None: action.triggered.connect(callback) action.setEnabled(enabled) action.setCheckable(checkable) self.addAction(action, addToMenu, addToToolbar) return action
class MetaSearchPlugin(object): """base plugin""" def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.dialog = None self.web_menu = "&MetaSearch" def initGui(self): """startup""" # run run_icon = QIcon("%s/%s" % (self.context.ppath, "images/MetaSearch.png")) self.action_run = QAction(run_icon, "MetaSearch", self.iface.mainWindow()) self.action_run.setWhatsThis(QCoreApplication.translate("MetaSearch", "MetaSearch plugin")) self.action_run.setStatusTip(QCoreApplication.translate("MetaSearch", "Search Metadata Catalogues")) self.action_run.triggered.connect(self.run) self.iface.addWebToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon("%s/%s" % (self.context.ppath, "images/help.png")) self.action_help = QAction(help_icon, "Help", self.iface.mainWindow()) self.action_help.setWhatsThis(QCoreApplication.translate("MetaSearch", "MetaSearch plugin help")) self.action_help.setStatusTip(QCoreApplication.translate("MetaSearch", "Get Help on MetaSearch")) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface) def unload(self): """teardown""" # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_run) self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.iface.removeWebToolBarIcon(self.action_run) def run(self): """open MetaSearch""" self.dialog.exec_() def help(self): """open help in user's default web browser""" open_url(self.context.metadata.get("general", "homepage"))
class MultiQmlPlugin(): def __init__( self, iface ): self.iface = iface def initGui( self ): self.actionRun = QAction( QIcon( ":/plugins/multiqml/icon.png" ),\ QApplication.translate("MultiQmlPlugin", "MultiQml" ), self.iface.mainWindow() ) self.actionRun.setWhatsThis( QApplication.translate("MultiQmlPlugin", "Apply single qml style to multiple raster or vector layers") ) self.actionAbout = QAction( QApplication.translate("MultiQmlPlugin", "About" ), self.iface.mainWindow() ) QObject.connect( self.actionRun, SIGNAL( "triggered()" ), self.run ) QObject.connect( self.actionAbout, SIGNAL( "triggered()" ), self.about ) self.iface.addToolBarIcon(self.actionRun) self.iface.addPluginToMenu( QApplication.translate("MultiQmlPlugin", "&MultiQml" ), self.actionRun ) self.iface.addPluginToMenu( QApplication.translate("MultiQmlPlugin", "&MultiQml" ), self.actionAbout ) self.isMultiQmlRun = False def unload( self ): self.iface.removePluginMenu( QApplication.translate("MultiQmlPlugin", "&MultiQml" ), self.actionRun ) self.iface.removePluginMenu( QApplication.translate("MultiQmlPlugin", "&MultiQml" ), self.actionAbout ) self.iface.removeToolBarIcon(self.actionRun) def run( self ): if not self.isMultiQmlRun: self.isMultiQmlRun = True dlgMain = MultiQmlDlg( self.iface.mainWindow(), self.iface ) dlgMain.show() dlgMain.exec_() self.isMultiQmlRun = False def about( self ): dlgAbout = QDialog() dlgAbout.setWindowTitle( QApplication.translate("MultiQmlPlugin", "About", "Window title") ) lines = QVBoxLayout( dlgAbout ) lines.addWidget( QLabel( QApplication.translate("MultiQmlPlugin", "<b>MultiQml (Version %1):</b>" ).arg(mVersion) ) ) lines.addWidget( QLabel( QApplication.translate("MultiQmlPlugin", " This plugin takes single qml style and\n applies it to multiple raster or vector layers" ) ) ) lines.addWidget( QLabel( QApplication.translate("MultiQmlPlugin", "<b>Developers:</b>" ) ) ) lines.addWidget( QLabel( " Lynx ([email protected])" ) ) lines.addWidget( QLabel( " Maxim Dubinin ([email protected])" ) ) lines.addWidget( QLabel( QApplication.translate("MultiQmlPlugin", "<b>Link:</b>") ) ) # lines.addWidget( QLabel( "<homepage>http://gis-lab.info/qa/qgis-multiqml-eng.html</homepage>" ) ) link = QLabel( QApplication.translate("MultiQmlPlugin", "<a href=\"http://gis-lab.info/qa/qgis-multiqml-eng.html\">http://gis-lab.info/qa/qgis-multiqml-eng.html</a>" ) ) link.setOpenExternalLinks( True ) lines.addWidget( link ) pbnClose = QPushButton(QApplication.translate("MultiQmlPlugin", "Close")) lines.addWidget(pbnClose) QObject.connect(pbnClose, SIGNAL("clicked()"), dlgAbout, SLOT("close()")) dlgAbout.exec_()
def addDockAction(self, iconPath, text, callback=None, enabled=True, checkable=False, tip=None, whatsThis=None): action = QAction(QIcon(iconPath), text, self._dock) if callback is not None: action.triggered.connect(callback) action.setEnabled(enabled) action.setCheckable(checkable) if tip is not None: action.setStatusTip(tip) if whatsThis is not None: action.setWhatsThis(whatsThis) self._dock.toolbar.addAction(action) # self.actions.append(action) return action
class GeoJSONExportPlugin: """QGIS Plugin that export geojson into a remote place""" def __init__(self, iface): """Initialization of the plugin""" # save reference to the QGIS interface self.iface = iface def initGui(self): """Initialize the GUI of the plugin""" self.action = QAction( QIcon(":/plugins/GeoJSONExportPlugin/img/icon.png"), "GeoJSON Export Plugin", self.iface.mainWindow()) self.action.setObjectName("testAction") self.action.setWhatsThis("Configuration for test plugin") self.action.setStatusTip("This is status tip") QObject.connect(self.action, SIGNAL("triggered()"), self.run) self.iface.addToolBarIcon(self.action) def unload(self): """Unload the plugin""" self.iface.removeToolBarIcon(self.action) def get_vector_layers(self): """Returns all the opened vector layers""" layers = self.iface.legendInterface().layers() vector_layers = [] for layer in layers: print layer.id() layerType = layer.type() if layerType == qgis.core.QgsMapLayer.VectorLayer: vector_layers.append(layer) return vector_layers def run(self): """Runs the plugin when the user activate it""" project_filename = qgis.core.QgsProject.instance().fileName() print '-' print project_filename if not project_filename: project_filename = u'Undefined' project_filename = project_filename.encode('utf-8') vector_layers = self.get_vector_layers() dlg = GeoJSONExportPluginDialog(project_filename, vector_layers) dlg.exec_()
class AuxiliaryWindowPlugin: def __init__(self, iface): self.iface = iface self.plugin = ContainerAuxiliaryWindow( iface.mainWindow() ) self.namePlugin = "&Auxiliary Window" def _connect(self, isConnect = True): signal_slot = ( { 'signal': QgsProject.instance().readProject, 'slot': self.plugin.onReadProject }, { 'signal': QgsProject.instance().writeProject, 'slot': self.plugin.onWriteProject } ) if isConnect: for item in signal_slot: item['signal'].connect( item['slot'] ) else: for item in signal_slot: item['signal'].disconnect( item['slot'] ) def initGui(self): title = "Auxiliary window" icon = QIcon( os.path.join( os.path.dirname(__file__), 'auxiliarywindow.png' ) ) self.action = QAction( icon, title, self.iface.mainWindow() ) self.action.setObjectName( "AuxiliaryWindow" ) self.action.setWhatsThis( title ) self.action.setStatusTip( title ) self.action.triggered.connect( self.run ) self.iface.addToolBarIcon( self.action ) self.iface.addPluginToMenu( self.namePlugin, self.action) self._connect() def unload(self): self.iface.removeToolBarIcon( self.action ) self.iface.removePluginMenu( self.namePlugin, self.action) del self.action self._connect( False ) self.plugin.close() @pyqtSlot() def run(self): self.plugin.run()
def addToolbarAction( self, iconPath, text, callback=None, enabled=True, checkable=False, tip=None, whatsThis=None ): """Add a toolbar icon to the toolbar""" action = QAction(QIcon(iconPath), text, self) if tip is not None: action.setStatusTip(tip) if whatsThis is not None: action.setWhatsThis(whatsThis) if callback is not None: action.triggered.connect(callback) action.setEnabled(enabled) action.setCheckable(checkable) self.toolbar.addAction(action) return action
def initGui(self): """Create the plugin entries inside the QGIS GUI.""" # create the configure entry icon = QIcon(':/plugins/MenuBuilder/resources/settings.svg') configure = QAction(icon, self.tr('&Configure Menus'), self.iface.mainWindow()) configure.triggered.connect(self.run_configure) configure.setEnabled(True) configure.setStatusTip(self.tr("Configure menus with drag&drop from qgisbrowser")) configure.setWhatsThis(self.tr("Configure menus with drag&drop from qgisbrowser")) self.iface.addPluginToMenu(self.plugin_name, configure) self.actions.append(configure) # restore previous session if exists try: self.dlg.restore_session() except Exception as exc: QMessageBox( QMessageBox.Warning, "Restoring MenuBuilder last session", exc.message.decode(self.dlg.pgencoding), QMessageBox.Ok, self.dlg ).exec_()
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 (str) :param text: text that should be shown in menu items for this action (str) :param callback: function to be called when the action is triggered (function) :param enabled_flag: a flag indicating if the action should be enabled by default (bool). Defaults to True. :param add_to_menu: flag indicating whether the action should also be added to the menu (bool). Defaults to True. :param add_to_toolbar: flag indicating whether the action should also be added to the toolbar (bool). Defaults to True. :param status_tip: optional text to show in a popup when mouse pointer hovers over the action (str) :param parent: parent widget for the new action (QWidget). Defaults None. :param whats_this: optional text to show in the status bar when the mouse pointer hovers over the action (str) :returns: the action that was created (Qaction). Note that the action is also added to self.actions list. """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_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 registerAction(self, name, **kwargs): """ Registers given action name, optional arguments like a parent, icon, slot etc ... can be given. :param name: Action to register. :type name: unicode :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: Action. :rtype: QAction """ settings = foundations.dataStructures.Structure(**{"parent": None, "text": None, "icon": None, "iconText": None, "checkable": None, "checked": None, "statusTip": None, "whatsThis": None, "toolTip": None, "shortcut": None, "shortcutContext": None, "slot": None}) settings.update(kwargs) name = self.__normalizeName(name) category = foundations.namespace.getNamespace(name) name = foundations.namespace.removeNamespace(name) action = QAction(name, settings.parent or self) self.addToCategory(category, name, action) settings.text and action.setText(settings.text) settings.icon and action.setIcon(settings.icon) settings.iconText and action.setIconText(settings.iconText) settings.checkable and action.setCheckable(settings.checkable) settings.checked and action.setChecked(settings.checked) settings.statusTip and action.setStatusTip(settings.statusTip) settings.whatsThis and action.setWhatsThis(settings.whatsThis) settings.toolTip and action.setToolTip(settings.toolTip) settings.shortcut and action.setShortcut(QKeySequence(settings.shortcut)) settings.shortcutContext and action.setShortcutContext(settings.shortcutContext) if settings.slot: self.__actionsSignalsSlots[action] = settings.slot action.triggered.connect(settings.slot) return action
def __init__(self, parent=None, host="localhost", port=5432, home="index.html", paths=None): QWidget.__init__(self, parent) self.parent = parent self.viewer = self.HtmlViewer(self.parent, host, port, home, paths) homeButton = QToolButton(self) homeAction = QAction("&Home", self) homeAction.setToolTip("Return to start page") homeAction.setWhatsThis("Return to start page") homeAction.setIcon(QIcon(":go-home")) homeButton.setDefaultAction(homeAction) homeAction.setEnabled(True) homeButton.setAutoRaise(True) backwardButton = QToolButton(self) backwardAction = QAction("&Back", self) backwardAction.setToolTip("Move to previous page") backwardAction.setWhatsThis("Move to previous page") backwardAction.setIcon(QIcon(":go-previous")) backwardButton.setDefaultAction(backwardAction) backwardAction.setEnabled(False) backwardButton.setAutoRaise(True) forwardButton = QToolButton(self) forwardAction = QAction("&Forward", self) forwardAction.setToolTip("Move to next page") forwardAction.setWhatsThis("Move to next page") forwardAction.setIcon(QIcon(":go-next")) forwardButton.setDefaultAction(forwardAction) forwardAction.setEnabled(False) forwardButton.setAutoRaise(True) vert = QVBoxLayout(self) horiz = QHBoxLayout() horiz.addStretch() horiz.addWidget(backwardButton) horiz.addWidget(homeButton) horiz.addWidget(forwardButton) horiz.addStretch() vert.addLayout(horiz) vert.addWidget(self.viewer) self.connect(self.viewer, SIGNAL("forwardAvailable(bool)"), forwardAction.setEnabled) self.connect(self.viewer, SIGNAL("backwardAvailable(bool)"), backwardAction.setEnabled) self.connect(homeAction, SIGNAL("triggered()"), self.home) self.connect(backwardAction, SIGNAL("triggered()"), self.backward) self.connect(forwardAction, SIGNAL("triggered()"), self.forward)
def load_menus(self, profile=None, schema=None): """ Load menus in the main windows qgis bar """ if not schema: schema = self.combo_schema.currentText() if not profile: profile = self.combo_profile.currentText() # remove previous menus for menu in self.uiparent.menus: self.uiparent.iface.mainWindow().menuBar().removeAction(menu.menuAction()) with self.transaction(): cur = self.connection.cursor() select = """ select name, profile, model_index, datasource_uri from {}.{} where profile = '{}' """.format(schema, self.table, profile) cur.execute(select) rows = cur.fetchall() # item accessor ex: '0-menu/0-submenu/1-item/' menudict = {} # reference to parent item parent = '' # reference to qgis main menu bar menubar = self.uiparent.iface.mainWindow().menuBar() for name, profile, model_index, datasource_uri in self.sortby_modelindex(rows): uri_struct = QgsMimeDataUtils.Uri(datasource_uri) indexes = json.loads(model_index) # root menu parent = '{}-{}/'.format(indexes[0][0], indexes[0][1]) if parent not in menudict: menu = QMenu(self.uiparent.iface.mainWindow()) self.uiparent.menus.append(menu) menu.setObjectName(indexes[0][1]) menu.setTitle(indexes[0][1]) menubar.insertMenu( self.uiparent.iface.firstRightStandardMenu().menuAction(), menu) menudict[parent] = menu else: # menu already there menu = menudict[parent] for idx, subname in indexes[1:-1]: # intermediate submenus parent += '{}-{}/'.format(idx, subname) if parent not in menudict: submenu = menu.addMenu(subname) submenu.setObjectName(subname) submenu.setTitle(subname) menu = submenu # store it for later use menudict[parent] = menu continue # already treated menu = menudict[parent] # last item = layer layer = QAction(name, self.uiparent.iface.mainWindow()) if uri_struct.providerKey in ICON_MAPPER: layer.setIcon(QIcon(ICON_MAPPER[uri_struct.providerKey])) if uri_struct.providerKey == 'postgres': # set tooltip to postgres comment comment = self.get_table_comment(uri_struct.uri) layer.setStatusTip(comment) layer.setToolTip(comment) layer.setData(uri_struct.uri) layer.setWhatsThis(uri_struct.providerKey) layer.triggered.connect(self.layer_handler[uri_struct.layerType]) menu.addAction(layer)
def add_action( self, name, icon_path, text, callback, toggle_flag=False, enabled_flag=True, checkable_flag=False, visible_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 name: Objectname of the action. Serves also as key for the stored actions. :type name: str :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 toggle_flag: A flag indicating if the action should connect the toggled or triggered signal by default. Defaults to triggered (False) :type toggle_flag: bool :param checkable_flag: A flag indicating if the action should be checkable by default. Defaults to False. :type checkable: bool :param visible_flag: A flag indicating if the action should be displayed by default. Defaults to True. :type visible: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.setObjectName(name) if toggle_flag: action.toggled.connect(callback) else: action.triggered.connect(callback) action.setEnabled(enabled_flag) action.setCheckable(checkable_flag) action.setVisible(visible_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[name] = action return action
class Plugin: """The QGIS interface implementation for the Risk in a box plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menubar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. Args: iface - a Quantum GIS QGisAppInterface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. Returns: None. Raises: no exceptions explicitly raised. """ # Save reference to the QGIS interface self.iface = iface self.translator = None self.setupI18n() #print self.tr('InaSAFE') def setupI18n(self, thePreferredLocale=None): """Setup internationalisation for the plugin. See if QGIS wants to override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. Args: thePreferredLocale - optional parameter which if set will override any other way of determining locale.. Returns: None. Raises: no exceptions explicitly raised. """ myOverrideFlag = QSettings().value('locale/overrideFlag', QVariant(False)).toBool() myLocaleName = None if thePreferredLocale is not None: myLocaleName = thePreferredLocale elif myOverrideFlag: myLocaleName = QSettings().value('locale/userLocale', QVariant('')).toString() else: myLocaleName = QLocale.system().name() # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(myLocaleName) myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) myTranslationPath = os.path.join(myRoot, 'safe_qgis', 'i18n', 'inasafe_' + str(myLocaleName) + '.qm') if os.path.exists(myTranslationPath): self.translator = QTranslator() myResult = self.translator.load(myTranslationPath) if not myResult: myMessage = 'Failed to load translation for %s' % myLocaleName raise TranslationLoadException(myMessage) QCoreApplication.installTranslator(self.translator) def tr(self, theString): """We implement this ourself since we do not inherit QObject. Args: theString - string for translation. Returns: Translated version of theString. Raises: no exceptions explicitly raised. """ return QCoreApplication.translate('Plugin', theString) def initGui(self): """Gui initialisation procedure (for QGIS plugin api). This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Import dock here as it needs to be imported AFTER i18n is set up from safe_qgis.dock import Dock self.dockWidget = None #-------------------------------------- # Create action for plugin dockable window (show/hide) #-------------------------------------- # pylint: disable=W0201 self.actionDock = QAction(QIcon(':/plugins/inasafe/icon.png'), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.actionDock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.actionDock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.actionDock.setCheckable(True) self.actionDock.setChecked(True) QObject.connect(self.actionDock, SIGNAL('triggered()'), self.showHideDockWidget) # add to plugin toolbar self.iface.addToolBarIcon(self.actionDock) # add to plugin menu self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionDock) #-------------------------------------- # Create action for keywords editor #-------------------------------------- self.actionKeywordsDialog = QAction( QIcon(':/plugins/inasafe/keywords.png'), self.tr('Keyword Editor'), self.iface.mainWindow()) self.actionKeywordsDialog.setStatusTip(self.tr( 'Open the keywords editor')) self.actionKeywordsDialog.setWhatsThis(self.tr( 'Open the keywords editor')) QObject.connect(self.actionKeywordsDialog, SIGNAL('triggered()'), self.showKeywordsEditor) self.iface.addToolBarIcon(self.actionKeywordsDialog) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionKeywordsDialog) #-------------------------------------- # Create action for reset icon #-------------------------------------- self.actionResetDock = QAction( QIcon(':/plugins/inasafe/reload.png'), self.tr('Reset Dock'), self.iface.mainWindow()) self.actionResetDock.setStatusTip(self.tr( 'Reset the InaSAFE Dock')) self.actionResetDock.setWhatsThis(self.tr( 'Reset the InaSAFE Dock')) QObject.connect(self.actionResetDock, SIGNAL('triggered()'), self.resetDock) self.iface.addToolBarIcon(self.actionResetDock) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionResetDock) #-------------------------------------- # Create action for options dialog #-------------------------------------- self.actionOptions = QAction( QIcon(':/plugins/inasafe/options.png'), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.actionOptions.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.actionOptions.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) QObject.connect(self.actionOptions, SIGNAL('triggered()'), self.showOptions) self.iface.addToolBarIcon(self.actionOptions) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionOptions) #-------------------------------------- # create dockwidget and tabify it with the legend #-------------------------------------- self.dockWidget = Dock(self.iface) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget) myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend') if myLegendTab: self.iface.mainWindow().tabifyDockWidget( myLegendTab, self.dockWidget) self.dockWidget.raise_() # # Hook up a slot for when the current layer is changed # QObject.connect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged) # pylint: disable=W0201 def unload(self): """Gui breakdown procedure (for QGIS plugin api). This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Remove the plugin menu item and icon self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionDock) self.iface.removeToolBarIcon(self.actionDock) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionKeywordsDialog) self.iface.removeToolBarIcon(self.actionKeywordsDialog) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionResetDock) self.iface.removeToolBarIcon(self.actionResetDock) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionOptions) self.iface.removeToolBarIcon(self.actionOptions) self.iface.mainWindow().removeDockWidget(self.dockWidget) self.dockWidget.setVisible(False) self.dockWidget.destroy() QObject.disconnect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged) # Run method that performs all the real work def showHideDockWidget(self): """Show or hide the dock widget. This slot is called when the user clicks the toolbar icon or menu item associated with this plugin. It will hide or show the dock depending on its current state. .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ if self.dockWidget.isVisible(): self.dockWidget.setVisible(False) else: self.dockWidget.setVisible(True) self.dockWidget.raise_() def showOptions(self): """Show the options dialog. This slot is called when the user clicks the options toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.options_dialog import OptionsDialog myDialog = OptionsDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.show() def showKeywordsEditor(self): """Show the keywords editor. This slot is called when the user clicks the keyword editor toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.keywords_dialog import KeywordsDialog if self.iface.activeLayer() is None: return myDialog = KeywordsDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.show() def resetDock(self): """Reset the dock to its default state. This slot is called when the user clicks the reset icon in the toolbar or the reset menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ self.dockWidget.getLayers() def layerChanged(self, theLayer): """Enable or disable the keywords editor icon. This slot is called when the user clicks the keyword editor toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ if theLayer is None: self.actionKeywordsDialog.setEnabled(False) else: self.actionKeywordsDialog.setEnabled(True) self.dockWidget.layerChanged(theLayer)
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 = GisGrimeFocusDialog() 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) ###########aca las conexiones a los botones############################ # set the default crs system dest_crs = self.dlg.mpsw_crs.setCrs(QgsCoordinateReferenceSystem(3116)) # funcion que guarda la ruta del archivo de salida en el text # correspondiente self.dlg.pBSearchFile.clicked.connect(self.readInputData) #funcionque conecta al boton con la funcion de convertir el scv en shape # y cargarlo self.dlg.pBImport.clicked.connect(self.validations) self.dlg.mcb_lista_csv.layerChanged.connect(self.load_fields) self.dlg.pb_clean.clicked.connect(self.clean) # funcion que habilita el radio buton de numero de features al seleccionar # el cuadro de cifras self.dlg.dsb_bandwith.valueChanged.connect(self.radio_custom_click) return action
class Plugin(object): """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menu bar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Save reference to the QGIS interface self.iface = iface self.dock_widget = None # Actions self.action_add_layers = None self.action_add_osm_layer = None self.action_add_petabencana_layer = None self.action_batch_runner = None self.action_dock = None self.action_extent_selector = None self.action_field_mapping = None self.action_multi_exposure = None self.action_function_centric_wizard = None self.action_import_dialog = None self.action_keywords_wizard = None self.action_minimum_needs = None self.action_minimum_needs_config = None self.action_multi_buffer = None self.action_options = None self.action_run_tests = None self.action_save_scenario = None self.action_shake_converter = None self.action_show_definitions = None self.action_toggle_rubberbands = None self.action_metadata_converter = None self.translator = None self.toolbar = None self.wizard = None self.actions = [] # list of all QActions we create for InaSAFE self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) developer_mode = setting('developer_mode', False, expected_type=bool) self.hide_developer_buttons = (inasafe_release_status == 'final' and not developer_mode) # 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('Plugin', message) def add_action(self, action, add_to_toolbar=True, add_to_legend=False): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool :param add_to_legend: Flag indicating whether the action should also be added to the layer legend menu. Default to False. :type add_to_legend: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) if add_to_legend: # The id is the action name without spaces, tabs ... self.iface.legendInterface().addLegendLayerAction( action, self.tr('InaSAFE'), ''.join(action.text().split()), QgsMapLayer.VectorLayer, True) self.iface.legendInterface().addLegendLayerAction( action, self.tr('InaSAFE'), ''.join(action.text().split()), QgsMapLayer.RasterLayer, True) def _create_dock_toggle_action(self): """Create action for plugin dockable window (show/hide).""" # pylint: disable=W0201 icon = resources_path('img', 'icons', 'icon.svg') self.action_dock = QAction(QIcon(icon), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.action_dock.setObjectName('InaSAFEDockToggle') self.action_dock.setStatusTip(self.tr('Show/hide InaSAFE dock widget')) self.action_dock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget')) self.action_dock.setCheckable(True) self.action_dock.setChecked(True) self.action_dock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.action_dock) # -------------------------------------- # Create action for keywords creation wizard # ------------------------------------- def _create_keywords_wizard_action(self): """Create action for keywords creation wizard.""" icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('Keywords Creation Wizard'), self.iface.mainWindow()) self.action_keywords_wizard.setStatusTip( self.tr('Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setWhatsThis( self.tr('Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setEnabled(False) self.action_keywords_wizard.triggered.connect( self.show_keywords_wizard) self.add_action(self.action_keywords_wizard, add_to_legend=True) def _create_analysis_wizard_action(self): """Create action for IF-centric wizard.""" icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('Impact Function Centric Wizard'), self.iface.mainWindow()) self.action_function_centric_wizard.setStatusTip( self.tr('Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setWhatsThis( self.tr('Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setEnabled(True) self.action_function_centric_wizard.triggered.connect( self.show_function_centric_wizard) self.add_action(self.action_function_centric_wizard) def _create_options_dialog_action(self): """Create action for options dialog.""" icon = resources_path('img', 'icons', 'configure-inasafe.svg') self.action_options = QAction(QIcon(icon), self.tr('Options'), self.iface.mainWindow()) self.action_options.setStatusTip( self.tr('Open InaSAFE options dialog')) self.action_options.setWhatsThis( self.tr('Open InaSAFE options dialog')) self.action_options.triggered.connect(self.show_options) self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_action(self): """Create action for minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.action_minimum_needs = QAction( QIcon(icon), self.tr('Minimum Needs Calculator'), self.iface.mainWindow()) self.action_minimum_needs.setStatusTip( self.tr('Open InaSAFE minimum needs calculator')) self.action_minimum_needs.setWhatsThis( self.tr('Open InaSAFE minimum needs calculator')) self.action_minimum_needs.triggered.connect(self.show_minimum_needs) self.add_action(self.action_minimum_needs, add_to_toolbar=self.full_toolbar) def _create_multi_buffer_action(self): """Create action for multi buffer dialog.""" icon = resources_path('img', 'icons', 'show-multi-buffer.svg') self.action_multi_buffer = QAction(QIcon(icon), self.tr('Multi Buffer'), self.iface.mainWindow()) self.action_multi_buffer.setStatusTip( self.tr('Open InaSAFE multi buffer')) self.action_multi_buffer.setWhatsThis( self.tr('Open InaSAFE multi buffer')) self.action_multi_buffer.triggered.connect(self.show_multi_buffer) self.add_action(self.action_multi_buffer, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_options_action(self): """Create action for global minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg') self.action_minimum_needs_config = QAction( QIcon(icon), self.tr('Minimum Needs Configuration'), self.iface.mainWindow()) self.action_minimum_needs_config.setStatusTip( self.tr('Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.setWhatsThis( self.tr('Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.triggered.connect( self.show_minimum_needs_configuration) self.add_action(self.action_minimum_needs_config, add_to_toolbar=self.full_toolbar) def _create_shakemap_converter_action(self): """Create action for converter dialog.""" icon = resources_path('img', 'icons', 'show-converter-tool.svg') self.action_shake_converter = QAction(QIcon(icon), self.tr('Shakemap Converter'), self.iface.mainWindow()) self.action_shake_converter.setStatusTip( self.tr('Open InaSAFE Converter')) self.action_shake_converter.setWhatsThis( self.tr('Open InaSAFE Converter')) self.action_shake_converter.triggered.connect( self.show_shakemap_importer) self.add_action(self.action_shake_converter, add_to_toolbar=self.full_toolbar) def _create_batch_runner_action(self): """Create action for batch runner dialog.""" icon = resources_path('img', 'icons', 'show-batch-runner.svg') self.action_batch_runner = QAction(QIcon(icon), self.tr('Batch Runner'), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr('Open Batch Runner')) self.action_batch_runner.setWhatsThis(self.tr('Open Batch Runner')) self.action_batch_runner.triggered.connect(self.show_batch_runner) self.add_action(self.action_batch_runner, add_to_toolbar=self.full_toolbar) def _create_save_scenario_action(self): """Create action for save scenario dialog.""" icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction(QIcon(icon), self.tr('Save Current Scenario'), self.iface.mainWindow()) message = self.tr('Save current scenario to text file') self.action_save_scenario.setStatusTip(message) self.action_save_scenario.setWhatsThis(message) # noinspection PyUnresolvedReferences self.action_save_scenario.triggered.connect(self.save_scenario) self.add_action(self.action_save_scenario, add_to_toolbar=self.full_toolbar) def _create_osm_downloader_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'show-osm-download.svg') self.action_import_dialog = QAction( QIcon(icon), self.tr('OpenStreetMap Downloader'), self.iface.mainWindow()) self.action_import_dialog.setStatusTip( self.tr('OpenStreetMap Downloader')) self.action_import_dialog.setWhatsThis( self.tr('OpenStreetMap Downloader')) self.action_import_dialog.triggered.connect(self.show_osm_downloader) self.add_action(self.action_import_dialog, add_to_toolbar=True) def _create_geonode_uploader_action(self): """Create action for Geonode uploader dialog.""" if self.hide_developer_buttons: return icon = resources_path('img', 'icons', 'geonode.png') label = tr('Geonode Uploader') self.action_geonode = QAction(QIcon(icon), label, self.iface.mainWindow()) self.action_geonode.setStatusTip(label) self.action_geonode.setWhatsThis(label) self.action_geonode.triggered.connect(self.show_geonode_uploader) self.add_action(self.action_geonode, add_to_toolbar=False) def _create_add_osm_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-osm-tiles-layer.svg') self.action_add_osm_layer = QAction( QIcon(icon), self.tr('Add OpenStreetMap Tile Layer'), self.iface.mainWindow()) self.action_add_osm_layer.setStatusTip( self.tr('Add OpenStreetMap Tile Layer')) self.action_add_osm_layer.setWhatsThis( self.tr('Use this to add an OSM layer to your map. ' 'It needs internet access to function.')) self.action_add_osm_layer.triggered.connect(self.add_osm_layer) self.add_action(self.action_add_osm_layer, add_to_toolbar=True) def _create_show_definitions_action(self): """Create action for showing definitions / help.""" icon = resources_path('img', 'icons', 'show-inasafe-help.svg') self.action_show_definitions = QAction(QIcon(icon), self.tr('InaSAFE Help'), self.iface.mainWindow()) self.action_show_definitions.setStatusTip(self.tr('Show InaSAFE Help')) self.action_show_definitions.setWhatsThis( self. tr('Use this to show a document describing all InaSAFE concepts.')) self.action_show_definitions.triggered.connect(self.show_definitions) self.add_action(self.action_show_definitions, add_to_toolbar=True) def _create_metadata_converter_action(self): """Create action for showing metadata converter dialog.""" icon = resources_path('img', 'icons', 'show-metadata-converter.svg') self.action_metadata_converter = QAction( QIcon(icon), self.tr('InaSAFE Metadata Converter'), self.iface.mainWindow()) self.action_metadata_converter.setStatusTip( self.tr('Convert metadata from version 4.3 to version 3.5.')) self.action_metadata_converter.setWhatsThis( self.tr('Use this tool to convert metadata 4.3 to version 3.5')) self.action_metadata_converter.triggered.connect( self.show_metadata_converter) self.add_action(self.action_metadata_converter, add_to_toolbar=self.full_toolbar) def _create_field_mapping_action(self): """Create action for showing field mapping dialog.""" icon = resources_path('img', 'icons', 'show-mapping-tool.svg') self.action_field_mapping = QAction( QIcon(icon), self.tr('InaSAFE Field Mapping Tool'), self.iface.mainWindow()) self.action_field_mapping.setStatusTip( self.tr('Assign field mapping to layer.')) self.action_field_mapping.setWhatsThis( self.tr('Use this tool to assign field mapping in layer.')) self.action_field_mapping.setEnabled(False) self.action_field_mapping.triggered.connect(self.show_field_mapping) self.add_action(self.action_field_mapping, add_to_toolbar=self.full_toolbar) def _create_multi_exposure_action(self): """Create action for showing the multi exposure tool.""" self.action_multi_exposure = QAction( QIcon(resources_path('img', 'icons', 'show-multi-exposure.svg')), self.tr('InaSAFE Multi Exposure Tool'), self.iface.mainWindow()) self.action_multi_exposure.setStatusTip( self.tr('Open the multi exposure tool.')) self.action_multi_exposure.setWhatsThis( self.tr('Open the multi exposure tool.')) self.action_multi_exposure.setEnabled(True) self.action_multi_exposure.triggered.connect(self.show_multi_exposure) self.add_action(self.action_multi_exposure, add_to_toolbar=self.full_toolbar) def _create_add_petabencana_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-petabencana-layer.svg') self.action_add_petabencana_layer = QAction( QIcon(icon), self.tr('Add PetaBencana Flood Layer'), self.iface.mainWindow()) self.action_add_petabencana_layer.setStatusTip( self.tr('Add PetaBencana Flood Layer')) self.action_add_petabencana_layer.setWhatsThis( self.tr('Use this to add a PetaBencana layer to your map. ' 'It needs internet access to function.')) self.action_add_petabencana_layer.triggered.connect( self.add_petabencana_layer) self.add_action(self.action_add_petabencana_layer, add_to_toolbar=self.full_toolbar) def _create_rubber_bands_action(self): """Create action for toggling rubber bands.""" icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg') self.action_toggle_rubberbands = QAction( QIcon(icon), self.tr('Toggle Scenario Outlines'), self.iface.mainWindow()) message = self.tr('Toggle rubber bands showing scenario extents.') self.action_toggle_rubberbands.setStatusTip(message) self.action_toggle_rubberbands.setWhatsThis(message) # Set initial state self.action_toggle_rubberbands.setCheckable(True) flag = setting('showRubberBands', False, expected_type=bool) self.action_toggle_rubberbands.setChecked(flag) # noinspection PyUnresolvedReferences self.action_toggle_rubberbands.triggered.connect( self.dock_widget.toggle_rubber_bands) self.add_action(self.action_toggle_rubberbands) def _create_analysis_extent_action(self): """Create action for analysis extent dialog.""" icon = resources_path('img', 'icons', 'set-extents-tool.svg') self.action_extent_selector = QAction(QIcon(icon), self.tr('Set Analysis Area'), self.iface.mainWindow()) self.action_extent_selector.setStatusTip( self.tr('Set the analysis area for InaSAFE')) self.action_extent_selector.setWhatsThis( self.tr('Set the analysis area for InaSAFE')) self.action_extent_selector.triggered.connect( self.show_extent_selector) self.add_action(self.action_extent_selector) def _create_test_layers_action(self): """Create action for adding layers (developer mode, non final only).""" if self.hide_developer_buttons: return icon = resources_path('img', 'icons', 'add-test-layers.svg') self.action_add_layers = QAction(QIcon(icon), self.tr('Add Test Layers'), self.iface.mainWindow()) self.action_add_layers.setStatusTip(self.tr('Add test layers')) self.action_add_layers.setWhatsThis(self.tr('Add test layers')) self.action_add_layers.triggered.connect(self.add_test_layers) self.add_action(self.action_add_layers) def _create_run_test_action(self): """Create action for running tests (developer mode, non final only).""" if self.hide_developer_buttons: return default_package = unicode( setting('testPackage', 'safe', expected_type=str)) msg = self.tr('Run tests in %s' % default_package) self.test_button = QToolButton() self.test_button.setMenu(QMenu()) self.test_button.setPopupMode(QToolButton.MenuButtonPopup) icon = resources_path('img', 'icons', 'run-tests.svg') self.action_run_tests = QAction(QIcon(icon), msg, self.iface.mainWindow()) self.action_run_tests.setStatusTip(msg) self.action_run_tests.setWhatsThis(msg) self.action_run_tests.triggered.connect(self.run_tests) self.test_button.menu().addAction(self.action_run_tests) self.test_button.setDefaultAction(self.action_run_tests) self.action_select_package = QAction(QIcon(icon), self.tr('Select package'), self.iface.mainWindow()) self.action_select_package.setStatusTip(self.tr('Select Test Package')) self.action_select_package.setWhatsThis(self.tr('Select Test Package')) self.action_select_package.triggered.connect(self.select_test_package) self.test_button.menu().addAction(self.action_select_package) self.toolbar.addWidget(self.test_button) self.add_action(self.action_run_tests, add_to_toolbar=False) self.add_action(self.action_select_package, add_to_toolbar=False) def _create_dock(self): """Create dockwidget and tabify it with the legend.""" # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = Dock(self.iface) self.dock_widget.setObjectName('InaSAFE-Dock') self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend') if legend_tab: self.iface.mainWindow().tabifyDockWidget(legend_tab, self.dock_widget) self.dock_widget.raise_() # noinspection PyPep8Naming def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') self.dock_widget = None # Now create the actual dock self._create_dock() # And all the menu actions # Configuration Group self._create_dock_toggle_action() self._create_options_dialog_action() self._create_minimum_needs_options_action() self._create_analysis_extent_action() self._create_rubber_bands_action() self._add_spacer_to_menu() self._create_keywords_wizard_action() self._create_analysis_wizard_action() self._add_spacer_to_menu() self._create_field_mapping_action() self._create_multi_exposure_action() self._create_metadata_converter_action() self._create_osm_downloader_action() self._create_add_osm_layer_action() self._create_add_petabencana_layer_action() self._create_geonode_uploader_action() self._create_shakemap_converter_action() self._create_minimum_needs_action() self._create_multi_buffer_action() self._create_test_layers_action() self._create_run_test_action() self._add_spacer_to_menu() self._create_batch_runner_action() self._create_save_scenario_action() self._add_spacer_to_menu() self._create_show_definitions_action() # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action) # Also deal with the fact that on start of QGIS dock may already be # hidden. self.action_dock.setChecked(self.dock_widget.isVisible()) self.iface.initializationCompleted.connect( partial(self.show_welcome_message)) def _add_spacer_to_menu(self): """Create a spacer to the menu to separate action groups.""" separator = QAction(self.iface.mainWindow()) separator.setSeparator(True) self.iface.addPluginToMenu(self.tr('InaSAFE'), separator) @staticmethod def clear_modules(): """Unload inasafe functions and try to return QGIS to before InaSAFE. .. todo:: I think this function can be removed. TS. """ # next lets force remove any inasafe related modules modules = [] for module in sys.modules: if 'inasafe' in module: # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module.split('.') path = '' for myToken in tokens: path += os.path.sep + myToken parent = os.path.abspath( os.path.join(__file__, os.path.pardir, os.path.pardir)) full_path = os.path.join(parent, path + '.py') if os.path.exists(os.path.abspath(full_path)): LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) for module in sys.modules: if 'inasafe' in module: print module # Lets also clean up all the path additions that were made package_path = os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon if self.wizard: self.wizard.deleteLater() for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.legendInterface().removeLegendLayerAction(myAction) self.iface.mainWindow().removeDockWidget(self.dock_widget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dock_widget.setVisible(False) self.dock_widget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) # Unload QGIS expressions loaded by the plugin. for qgis_expression in qgis_expressions().keys(): QgsExpression.unregisterFunction(qgis_expression) def toggle_inasafe_action(self, checked): """Check or un-check the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.action_dock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dock_widget.isVisible(): self.dock_widget.setVisible(False) else: self.dock_widget.setVisible(True) self.dock_widget.raise_() def add_test_layers(self): """Add standard test layers.""" from safe.test.utilities import load_standard_layers load_standard_layers() rect = QgsRectangle(106.806, -6.195, 106.837, -6.167) self.iface.mapCanvas().setExtent(rect) def select_test_package(self): """Select the test package.""" default_package = 'safe' user_package = unicode( setting('testPackage', default_package, expected_type=str)) test_package, _ = QInputDialog.getText( self.iface.mainWindow(), self.tr('Select the python test package'), self.tr('Select the python test package'), QLineEdit.Normal, user_package) if test_package == '': test_package = default_package set_setting('testPackage', test_package) msg = self.tr('Run tests in %s' % test_package) self.action_run_tests.setWhatsThis(msg) self.action_run_tests.setText(msg) def run_tests(self): """Run unit tests in the python console.""" from PyQt4.QtGui import QDockWidget main_window = self.iface.mainWindow() action = main_window.findChild(QAction, 'mActionShowPythonDialog') action.trigger() package = unicode(setting('testPackage', 'safe', expected_type=str)) for child in main_window.findChildren(QDockWidget, 'PythonConsole'): if child.objectName() == 'PythonConsole': child.show() for widget in child.children(): if 'PythonConsoleWidget' in str(widget.__class__): # print "Console widget found" shell = widget.shell shell.runCommand( 'from inasafe.test_suite import test_package') shell.runCommand('test_package(\'%s\')' % package) break def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, self.iface.mainWindow(), extent=self.dock_widget.extent.user_extent, crs=self.dock_widget.extent.crs) widget.clear_extent.connect( self.dock_widget.extent.clear_user_analysis_extent) widget.extent_defined.connect( self.dock_widget.define_user_analysis_extent) # This ensures that run button state is updated on dialog close widget.extent_selector_closed.connect( self.dock_widget.validate_impact_function) # Needs to be non modal to support hide -> interact with map -> show widget.show() # non modal def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.exec_() def show_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog(parent=self.iface.mainWindow(), dock=self.dock_widget) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog dialog = OptionsDialog(iface=self.iface, parent=self.iface.mainWindow()) dialog.show_option_dialog() if dialog.exec_(): # modal self.dock_widget.read_settings() from safe.gui.widgets.message import getting_started_message send_static_message(self.dock_widget, getting_started_message()) # Issue #4734, make sure to update the combobox after update the # InaSAFE option self.dock_widget.get_layers() def show_welcome_message(self): """Show the welcome message.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog # Do not show by default show_message = False previous_version = StrictVersion(setting('previous_version')) current_version = StrictVersion(inasafe_version) # Set previous_version to the current inasafe_version set_setting('previous_version', inasafe_version) if setting('always_show_welcome_message', expected_type=bool): # Show if it the setting said so show_message = True elif previous_version < current_version: # Always show if the user installed new version show_message = True if show_message: dialog = OptionsDialog(iface=self.iface, parent=self.iface.mainWindow()) dialog.show_welcome_dialog() if dialog.exec_(): # modal self.dock_widget.read_settings() def show_keywords_wizard(self): """Show the keywords creation wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog if self.iface.activeLayer() is None: return # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since the IFCW is non modal if not self.wizard: self.wizard = WizardDialog(self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_keywords_creation_mode() self.wizard.exec_() # modal def show_function_centric_wizard(self): """Show the function centric wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since it is non modal if not self.wizard: self.wizard = WizardDialog(self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_function_centric_mode() # non-modal in order to hide for selecting user extent self.wizard.show() def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) dialog = ShakemapConverterDialog(self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_() # modal def show_multi_buffer(self): """Show the multi buffer tool.""" from safe.gui.tools.multi_buffer_dialog import (MultiBufferDialog) dialog = MultiBufferDialog(self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_() # modal def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def show_geonode_uploader(self): """Show the Geonode uploader dialog.""" from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog dialog = GeonodeUploaderDialog(self.iface.mainWindow()) dialog.show() # non modal def add_osm_layer(self): """Add OSM tile layer to the map. This uses a gdal wrapper around the OSM tile service - see the WorldOSM.gdal file for how it is constructed. """ path = resources_path('osm', 'WorldOSM.gdal') layer = QgsRasterLayer(path, self.tr('OpenStreetMap')) registry = QgsMapLayerRegistry.instance() # Try to add it as the last layer in the list # False flag prevents layer being added to legend registry.addMapLayer(layer, False) root = QgsProject.instance().layerTreeRoot() index = len(root.findLayers()) + 1 # LOGGER.info('Inserting layer %s at position %s' % ( # layer.source(), index)) root.insertLayer(index, layer) QgsMapLayerRegistry.instance().addMapLayer(layer) def show_definitions(self): """Show InaSAFE Definitions (a report showing all key metadata).""" from safe.gui.tools.help_dialog import HelpDialog from safe.gui.tools.help import definitions_help dialog = HelpDialog(self.iface.mainWindow(), definitions_help.definitions_help()) dialog.show() # non modal def show_field_mapping(self): """Show InaSAFE Field Mapping.""" from safe.gui.tools.field_mapping_dialog import FieldMappingDialog dialog = FieldMappingDialog( parent=self.iface.mainWindow(), iface=self.iface, ) if dialog.exec_(): # modal LOGGER.debug('Show field mapping accepted') self.dock_widget.layer_changed(self.iface.activeLayer()) else: LOGGER.debug('Show field mapping not accepted') def show_metadata_converter(self): """Show InaSAFE Metadata Converter.""" from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) dialog = MetadataConverterDialog( parent=self.iface.mainWindow(), iface=self.iface, ) dialog.exec_() def show_multi_exposure(self): """Show InaSAFE Multi Exposure.""" from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog dialog = MultiExposureDialog(self.iface.mainWindow(), self.iface) dialog.exec_() # modal def add_petabencana_layer(self): """Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods """ from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog dialog = PetaBencanaDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def show_batch_runner(self): """Show the batch runner dialog.""" from safe.gui.tools.batch.batch_dialog import BatchDialog dialog = BatchDialog(parent=self.iface.mainWindow(), iface=self.iface, dock=self.dock_widget) dialog.exec_() # modal def save_scenario(self): """Save current scenario to text file.""" from safe.gui.tools.save_scenario import SaveScenarioDialog dialog = SaveScenarioDialog(iface=self.iface, dock=self.dock_widget) dialog.save_scenario() def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if not layer: enable_keyword_wizard = False elif not hasattr(layer, 'providerType'): enable_keyword_wizard = False elif layer.providerType() == 'wms': enable_keyword_wizard = False else: enable_keyword_wizard = True try: if layer: if is_raster_layer(layer): enable_field_mapping_tool = False else: keywords = KeywordIO().read_keywords(layer) keywords_version = keywords.get('keyword_version') if not keywords_version: supported = False else: supported = ( is_keyword_version_supported(keywords_version)) if not supported: enable_field_mapping_tool = False else: layer_purpose = keywords.get('layer_purpose') if not layer_purpose: enable_field_mapping_tool = False else: if layer_purpose == layer_purpose_exposure['key']: layer_subcategory = keywords.get('exposure') elif layer_purpose == layer_purpose_hazard['key']: layer_subcategory = keywords.get('hazard') else: layer_subcategory = None field_groups = get_field_groups( layer_purpose, layer_subcategory) if len(field_groups) == 0: # No field group, disable field mapping tool. enable_field_mapping_tool = False else: enable_field_mapping_tool = True else: enable_field_mapping_tool = False except (KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError): # No keywords, disable field mapping tool. enable_field_mapping_tool = False self.action_keywords_wizard.setEnabled(enable_keyword_wizard) self.action_field_mapping.setEnabled(enable_field_mapping_tool) def shortcut_f7(self): """Executed when user press F7 - will show the shakemap importer.""" self.show_shakemap_importer()
class QGISEducation: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.constants = TerreImageConstant() self.constants.iface = self.iface self.constants.canvas = self.iface.mapCanvas() self.constants.legendInterface = self.iface.legendInterface() def initGui(self): """ Initialisation on the widget interface """ # Create action that will start plugin configuration self.action = QAction(QIcon(":/plugins/qgiseducation/img/icon.png"), u"Terre Image", self.iface.mainWindow()) self.action.setWhatsThis("Terre Image") # connect the action to the run method self.action.triggered.connect(self.run) self.aboutAction = QAction( QIcon(":/plugins/DockableMirrorMap/icons/about.png"), "About", self.iface.mainWindow()) QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u"&TerreImage", self.action) self.iface.addPluginToMenu("TerreImage", self.aboutAction) self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None QObject.connect(self.iface, SIGNAL("projectRead()"), self.onProjectLoaded) QObject.connect(QgsProject.instance(), SIGNAL("writeProject(QDomDocument &)"), self.onWriteProject) QObject.connect(self.iface, SIGNAL("newProjectCreated()"), self.newProject) def do_display_one_band(self, who, qgis_layer, working_directory, mirror_tool): logger.debug("who" + str(who)) # manage_QGIS.display_one_band(self.qgis_education_manager.layer, who, self.iface) if qgis_layer: my_process = TerreImageDisplay(self.iface, working_directory, ProcessingManager().working_layer, mirror_tool, who, None, qgis_layer) else: my_process = TerreImageDisplay(self.iface, working_directory, ProcessingManager().working_layer, mirror_tool, who) # ProcessingManager().add_processing(my_process) self.educationWidget.set_combobox_histograms() def unload(self): """ Defines the unload of the plugin """ self.unload_interface() # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&TerreImage", self.action) self.iface.removeToolBarIcon(self.action) def unload_interface(self): if self.qgisedudockwidget is not None and self.educationWidget is not None: self.qgisedudockwidget.close() self.educationWidget.disconnectP() # run method that performs all the real work def run(self): """ Defines the behavior of the plugin """ timeBegin = time.time() # self.educationWidget.set_working_message(True) self.iface.newProject(True) # self.qgis_education_manager = TerreImageManager(self.iface) # _, bands = self.qgis_education_manager.set_current_layer( ) _, bands, working_dir = terre_image_utils.set_current_layer(self.iface) timeEnd = time.time() timeExec = timeEnd - timeBegin logger.info("temps de chargement: " + str(timeExec)) self.show_education_widget(bands, working_dir) # self.educationWidget.set_working_message(False) def show_education_widget(self, bands, working_dir): if ProcessingManager().working_layer and bands: if not self.dockOpened: # create the widget to display information self.educationWidget = QGISEducationWidget(self.iface) QObject.connect(self.educationWidget, SIGNAL("terminated()"), self.unload_interface) # self.educationWidget.qgis_education_manager = self.qgis_education_manager self.educationWidget.qgis_education_manager = TerreImageManager( self.iface) self.educationWidget.qgis_education_manager.working_directory = working_dir self.educationWidget.lineEdit_working_dir.setText(working_dir) self.educationWidget.qgis_education_manager.classif_tool.set_layers( ProcessingManager().get_qgis_working_layers(), ProcessingManager().working_layer.get_qgis_layer(), ProcessingManager().working_layer.band_invert) self.educationWidget.qgis_education_manager.classif_tool.set_directory( working_dir) self.educationWidget.qgis_education_manager.classif_tool.setupUi( ) # create the dockwidget with the correct parent and add the valuewidget self.qgisedudockwidget = Terre_Image_Main_Dock_widget( "Terre Image", self.iface.mainWindow(), self.iface) self.qgisedudockwidget.setObjectName("Terre Image") self.qgisedudockwidget.setWidget(self.educationWidget) QObject.connect(self.qgisedudockwidget, SIGNAL("closed(PyQt_PyObject)"), self.close_dock) # add the dockwidget to iface self.iface.addDockWidget(Qt.RightDockWidgetArea, self.qgisedudockwidget) self.educationWidget.set_comboBox_sprectral_band_display() text = "Plan R <- BS_PIR \nPlan V <- BS_R \nPlan B <- BS_V" self.qgisedudockwidget.show() self.dockOpened = True def about(self): from terre_image_about import DlgAbout DlgAbout(self.iface.mainWindow()).exec_() def close_dock(self, object): self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None if self.iface.legendInterface().layers() != []: self.iface.newProject() def newProject(self): for item in self.iface.mapCanvas().scene().items(): if isinstance(item, QgsRubberBand): item.reset(QGis.Point) if self.educationWidget is not None: self.educationWidget.disconnect_interface() if self.qgisedudockwidget is not None: self.qgisedudockwidget.close() self.educationWidget.disconnectP() self.dockOpened = False self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None def onWriteProject(self, domproject): if ProcessingManager().working_layer is None: return # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer", self.qgis_education_manager.layer.source_file ) # # write band orders # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_bands", str(self.qgis_education_manager.layer.bands) ) # logger.debug( str(self.qgis_education_manager.layer.bands) ) # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_type", self.qgis_education_manager.layer.type ) # QgsProject.instance().writeEntry( "QGISEducation", "/working_directory", self.qgis_education_manager.working_directory ) QgsProject.instance().writeEntry( "QGISEducation", "/working_layer", ProcessingManager().working_layer.source_file) # write band orders QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_bands", str(ProcessingManager().working_layer.bands)) logger.debug(str(ProcessingManager().working_layer.bands)) QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_type", ProcessingManager().working_layer.type) QgsProject.instance().writeEntry( "QGISEducation", "/working_directory", self.educationWidget.qgis_education_manager.working_directory) p = [] for process in ProcessingManager().get_processings(): p.append((process.processing_name, process.output_working_layer.get_source())) # print "process", p QgsProject.instance().writeEntry("QGISEducation", "/process", str(p)) QgsProject.instance().writeEntry("QGISEducation", "/index_group", self.constants.index_group) if "Angle Spectral" in ProcessingManager().get_processings_name(): # delete rubberband for item in self.iface.mapCanvas().scene().items(): # item is a rubberband if isinstance(item, QgsRubberBand): # get point if item.size() > 0: point = item.getPoint(0) # print point QgsProject.instance().writeEntryDouble( "QGISEducation", "/angle_spectral_point_x", point.x()) QgsProject.instance().writeEntryDouble( "QGISEducation", "/angle_spectral_point_y", point.y()) p = TerreImageParamaters() if p.is_complete(): QgsProject.instance().writeEntryDouble("QGISEducation", "/red_x_min", p.red_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/red_x_max", p.red_max) QgsProject.instance().writeEntryDouble("QGISEducation", "/green_x_min", p.green_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/green_x_max", p.green_max) QgsProject.instance().writeEntryDouble("QGISEducation", "/blue_x_min", p.blue_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/blue_x_max", p.blue_max) def onProjectLoaded(self): # does not work stops the project reading. # should desactivate all interface and read the project again # self.newProject( True ) # restore mirrors? wl, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer") if not ok or wl == "": pass if not wl == "": bands, ok = QgsProject.instance().readEntry( "QGISEducation", "/working_layer_bands") logger.debug("is ok" + str(ok)) logger.debug(bands) # working_layer = WorkingLayer(wl, None, bands) # TODO interpreter bands type, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer_type") working_dir, ok = QgsProject.instance().readEntry( "QGISEducation", "/working_directory") layer, bands = terre_image_utils.restore_working_layer( wl, eval(bands), type) ProcessingManager().working_layer = layer self.show_education_widget(bands, working_dir) # self.qgis_education_manager = TerreImageManager( self.iface ) # self.qgis_education_manager.restore_processing_manager(wl, eval(bands), type, working_dir) # if self.qgis_education_manager: process, ok = QgsProject.instance().readEntry( "QGISEducation", "/process") logger.debug(eval(process)) index_group, ok = QgsProject.instance().readDoubleEntry( "QGISEducation", "/index_group") self.constants.index_group = int(float(index_group)) process = eval(process) for qgis_layer in self.iface.legendInterface().layers(): # print "layer loading ", qgis_layer.name() if qgis_layer.name() in [ "NDVI", "NDTI", "Indice de brillance", "KMEANS" ]: process = TerreImageProcessing( self.iface, working_dir, ProcessingManager().working_layer, self. educationWidget.qgis_education_manager.mirror_map_tool, qgis_layer.name(), None, qgis_layer) elif "Angle Spectral" in qgis_layer.name(): process = TerreImageProcessing( self.iface, working_dir, ProcessingManager().working_layer, self. educationWidget.qgis_education_manager.mirror_map_tool, qgis_layer.name(), qgis_layer.source(), qgis_layer) # ProcessingManager().add_processing(process) elif "couleur_naturelles" in qgis_layer.name(): try: self.do_display_one_band( 'nat', qgis_layer, working_dir, self.educationWidget.qgis_education_manager. mirror_map_tool) except AttributeError: QMessageBox.warning( None, "Erreur", u'Le projet ne peut être lu. Essayez de créer un projet vierge, puis de réouvrir le projet souhaité.', QMessageBox.Ok) # self.newProject( ) return None # ProcessingManager().add_display( process ) else: corres = { 'red': "_bande_rouge", 'green': "_bande_verte", 'blue': "_bande_bleue", 'pir': "_bande_pir", 'mir': "_bande_mir", "nat": "_couleurs_naturelles" } result = [ x for x in corres if qgis_layer.name().endswith(corres[x]) ] # print result if result: # print "the couleur", result[0] try: self.do_display_one_band( result[0], qgis_layer, working_dir, self.educationWidget.qgis_education_manager. mirror_map_tool) except AttributeError: QMessageBox.warning( None, "Erreur", u'Le projet ne peut être lu. Essayez de créer un projet vierge, puis de réouvrir le projet souhaité.', QMessageBox.Ok) # self.newProject( ) return None # ProcessingManager().add_display( process ) angle_spectral_point_x, ok_x = QgsProject.instance( ).readDoubleEntry("QGISEducation", "/angle_spectral_point_x") angle_spectral_point_y, ok_y = QgsProject.instance( ).readDoubleEntry("QGISEducation", "/angle_spectral_point_y") # print "angle_spectral_point_x, angle_spectral_point_y", angle_spectral_point_x, angle_spectral_point_y if ok_x and ok_y: # print "angle_spectral_point_x, angle_spectral_point_y", angle_spectral_point_x, angle_spectral_point_y p = ProcessingManager().processing_from_name("Angle Spectral") if p: rubberband = p[0].rubberband rubberband.setWidth(10) rubberband.setColor(QColor(Qt.yellow)) rubberband.addPoint( QgsPoint(float(angle_spectral_point_x), float(angle_spectral_point_y))) p = TerreImageParamaters() p.red_min = QgsProject.instance().readDoubleEntry( "QGISEducation", "/red_x_min")[0] p.red_max = QgsProject.instance().readDoubleEntry( "QGISEducation", "/red_x_max")[0] p.green_min = QgsProject.instance().readDoubleEntry( "QGISEducation", "/green_x_min")[0] p.green_max = QgsProject.instance().readDoubleEntry( "QGISEducation", "/green_x_max")[0] p.blue_min = QgsProject.instance().readDoubleEntry( "QGISEducation", "/blue_x_min")[0] p.blue_max = QgsProject.instance().readDoubleEntry( "QGISEducation", "/blue_x_max")[0] self.educationWidget.set_combobox_histograms() self.iface.mapCanvas().refresh() self.iface.mapCanvas().repaint()
class QgepPlugin: """ A plugin for wastewater management http://www.github.com/qgep/QGEP """ # The networkAnalyzer will manage the networklayers and pathfinding networkAnalyzer = None # Remember not to reopen the dock if there's already one opened dockWidget = None # The layer ids the plugin will need edgeLayer = None nodeLayer = None specialStructureLayer = None profile = None def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.initLogger() setupI18n() def tr(self, sourceText): return QCoreApplication.translate("qgepplugin", sourceText) def initLogger(self): """ Initializes the logger """ self.logger = logging.getLogger(__package__) settings = QSettings() loglevel = settings.value("/QGEP/LogLevel", "Warning") logfile = settings.value("/QGEP/LogFile", None) if hasattr(self.logger, "qgepFileHandler"): self.logger.removeHandler(self.logger.qgepFileHandler) del self.logger.qgepFileHandler self.logger.addHandler(QgepQgsLogHandler()) if logfile: hLog = logging.FileHandler(logfile) fmt = logging.Formatter(LOGFORMAT) hLog.setFormatter(fmt) self.logger.addHandler(hLog) self.logger.fileHandler = hLog if "Debug" == loglevel: self.logger.setLevel(logging.DEBUG) elif "Info" == loglevel: self.logger.setLevel(logging.INFO) elif "Warning" == loglevel: self.logger.setLevel(logging.WARNING) elif "Error" == loglevel: self.logger.setLevel(logging.ERROR) fp = os.path.join(os.path.abspath(os.path.dirname(__file__)), "metadata.txt") iniText = QSettings(fp, QSettings.IniFormat) verno = iniText.value("version") self.logger.info("QGEP plugin version " + verno + " started") def initGui(self): """ Called to setup the plugin GUI """ self.toolbarButtons = [] # Create toolbar button self.profileAction = QAction( QIcon(":/plugins/qgepplugin/icons/wastewater-profile.svg"), "Profile", self.iface.mainWindow() ) self.profileAction.setWhatsThis(self.tr("Reach trace")) self.profileAction.setEnabled(False) self.profileAction.setCheckable(True) self.profileAction.triggered.connect(self.profileToolClicked) self.downstreamAction = QAction( QIcon(":/plugins/qgepplugin/icons/wastewater-downstream.svg"), "Downstream", self.iface.mainWindow() ) self.downstreamAction.setWhatsThis(self.tr("Downstream reaches")) self.downstreamAction.setEnabled(False) self.downstreamAction.setCheckable(True) self.downstreamAction.triggered.connect(self.downstreamToolClicked) self.upstreamAction = QAction( QIcon(":/plugins/qgepplugin/icons/wastewater-upstream.svg"), "Upstream", self.iface.mainWindow() ) self.upstreamAction.setWhatsThis(self.tr("Upstream reaches")) self.upstreamAction.setEnabled(False) self.upstreamAction.setCheckable(True) self.upstreamAction.triggered.connect(self.upstreamToolClicked) self.aboutAction = QAction(self.tr("About"), self.iface.mainWindow()) self.aboutAction.triggered.connect(self.about) self.settingsAction = QAction(self.tr("Settings"), self.iface.mainWindow()) self.settingsAction.triggered.connect(self.showSettings) # Add toolbar button and menu item self.iface.addToolBarIcon(self.profileAction) self.iface.addToolBarIcon(self.upstreamAction) self.iface.addToolBarIcon(self.downstreamAction) self.iface.addPluginToMenu("&QGEP", self.profileAction) self.iface.addPluginToMenu("&QGEP", self.settingsAction) self.iface.addPluginToMenu("&QGEP", self.aboutAction) # Local array of buttons to enable / disable based on context self.toolbarButtons.append(self.profileAction) self.toolbarButtons.append(self.upstreamAction) self.toolbarButtons.append(self.downstreamAction) # Init the object maintaining the network self.networkAnalyzer = QgepGraphManager(self.iface) # Create the map tool for profile selection self.profileTool = QgepProfileMapTool(self.iface, self.profileAction, self.networkAnalyzer) self.profileTool.profileChanged.connect(self.onProfileChanged) self.upstreamTreeTool = QgepTreeMapTool(self.iface, self.upstreamAction, self.networkAnalyzer) self.upstreamTreeTool.setDirection("upstream") self.downstreamTreeTool = QgepTreeMapTool(self.iface, self.downstreamAction, self.networkAnalyzer) self.downstreamTreeTool.setDirection("downstream") # Connect to events that can change layers self.iface.projectRead.connect(self.onProjectRead) QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.layersWillBeRemoved) QgsMapLayerRegistry.instance().layersAdded.connect(self.layersAdded) def unload(self): """ Called when unloading """ self.iface.removeToolBarIcon(self.profileAction) self.iface.removeToolBarIcon(self.upstreamAction) self.iface.removeToolBarIcon(self.downstreamAction) self.iface.removePluginMenu("&QGEP", self.profileAction) self.iface.removePluginMenu("&QGEP", self.aboutAction) def profileToolClicked(self): """ Is executed when the profile button is clicked """ self.openDock() # Set the profile map tool self.profileTool.setActive() def upstreamToolClicked(self): """ Is executed when the user clicks the upstream search tool """ self.upstreamTreeTool.setActive() def downstreamToolClicked(self): """ Is executed when the user clicks the downstream search tool """ self.downstreamTreeTool.setActive() def openDock(self): """ Opens the dock """ if self.dockWidget is None: self.logger.debug("Open dock") self.dockWidget = QgepDockWidget(self.iface.mainWindow(), self.iface.mapCanvas(), self.iface.addDockWidget) self.dockWidget.closed.connect(self.onDockClosed) self.dockWidget.showIt() self.plotWidget = QgepPlotSVGWidget(self.dockWidget, self.networkAnalyzer) self.plotWidget.specialStructureMouseOver.connect(self.highlightProfileElement) self.plotWidget.specialStructureMouseOut.connect(self.unhighlightProfileElement) self.plotWidget.reachMouseOver.connect(self.highlightProfileElement) self.plotWidget.reachMouseOut.connect(self.unhighlightProfileElement) self.dockWidget.addPlotWidget(self.plotWidget) @pyqtSlot() def onDockClosed(self): # used when Dock dialog is closed """ Gets called when the dock is closed All the cleanup of the dock has to be done here """ self.dockWidget = None def layersWillBeRemoved(self, layerList): """ Gets called when a layer is removed @param layerList: The layers about to be removed """ for layerId in layerList: if 0 != self.networkAnalyzer.getNodeLayer(): if self.networkAnalyzer.getNodeLayerId() == layerId: self.networkAnalyzer.setNodeLayer(0) self.layersChanged() if 0 != self.networkAnalyzer.getReachLayer(): if self.networkAnalyzer.getReachLayerId() == layerId: self.networkAnalyzer.setReachLayer(0) self.layersChanged() def layersAdded(self, layers): """ Gets called when a layer is added @param layers: the layers to check """ for newLayer in layers: if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id() == self.nodeLayer: self.networkAnalyzer.setNodeLayer(newLayer) self.layersChanged() if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id() == self.edgeLayer: self.networkAnalyzer.setReachLayer(newLayer) self.layersChanged() if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id() == self.specialStructureLayer: self.networkAnalyzer.setSpecialStructureLayer(newLayer) self.layersChanged() def layersChanged(self): """ Gets called when the layers have changed """ buttonsEnabled = False if self.networkAnalyzer.getNodeLayer() and self.networkAnalyzer.getReachLayer(): buttonsEnabled = True for button in self.toolbarButtons: button.setEnabled(buttonsEnabled) @pyqtSlot() def onProjectRead(self): """ Gets called when a new project gets loaded. Updates the layers """ project = QgsProject.instance() specialStructureLayer = project.readEntry("QGEP", "SpecialStructureLayer") graphEdgeLayer = project.readEntry("QGEP", "GraphEdgeLayer") graphNodeLayer = project.readEntry("QGEP", "GraphNodeLayer") if graphNodeLayer[1] is not False: self.nodeLayer = graphNodeLayer[0] else: self.nodeLayer = None if graphEdgeLayer[1] is not False: self.edgeLayer = graphEdgeLayer[0] else: self.edgeLayer = None if specialStructureLayer[1] is not False: self.specialStructureLayer = specialStructureLayer[0] else: self.specialStructureLayer = None if self.nodeLayer is not None and self.edgeLayer is not None and self.specialStructureLayer is not None: reg = QgsMapLayerRegistry.instance() self.layersAdded([layer for layer in reg.mapLayers().itervalues()]) else: if self.dockWidget is not None: self.dockWidget.close() def onProfileChanged(self, profile): """ The profile changed: update the plot @param profile: The profile to plot """ self.profile = profile.copy() if self.plotWidget: self.plotWidget.setProfile(profile) @pyqtSlot(unicode) def highlightProfileElement(self, objId): if self.profile is not None: self.profile.highlight(unicode(objId)) @pyqtSlot() def unhighlightProfileElement(self): if self.profile is not None: self.profile.highlight(None) def about(self): from ui.dlgabout import DlgAbout DlgAbout(self.iface.mainWindow()).exec_() def showSettings(self): settingsDlg = QgepSettingsDialog(self.iface.mainWindow()) settingsDlg.exec_()
class Plugin: """The QGIS interface implementation for the Risk in a box plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menubar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. Args: iface - a Quantum GIS QGisAppInterface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. Returns: None. Raises: no exceptions explicitly raised. """ # Save reference to the QGIS interface self.iface = iface self.translator = None self.setupI18n() #print self.tr('InaSAFE') utilities.setupLogger() def setupI18n(self, thePreferredLocale=None): """Setup internationalisation for the plugin. See if QGIS wants to override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. Args: thePreferredLocale - optional parameter which if set will override any other way of determining locale.. Returns: None. Raises: no exceptions explicitly raised. """ myOverrideFlag = QSettings().value('locale/overrideFlag', QVariant(False)).toBool() myLocaleName = None if thePreferredLocale is not None: myLocaleName = thePreferredLocale elif myOverrideFlag: myLocaleName = QSettings().value('locale/userLocale', QVariant('')).toString() else: myLocaleName = QLocale.system().name() # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc myLocaleName = str(myLocaleName).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(myLocaleName) LOGGER.debug( ('%s %s %s %s') % (thePreferredLocale, myOverrideFlag, QLocale.system().name(), os.environ['LANG'])) myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) myTranslationPath = os.path.join( myRoot, 'safe_qgis', 'i18n', 'inasafe_' + str(myLocaleName) + '.qm') if os.path.exists(myTranslationPath): self.translator = QTranslator() myResult = self.translator.load(myTranslationPath) if not myResult: myMessage = 'Failed to load translation for %s' % myLocaleName raise TranslationLoadException(myMessage) QCoreApplication.installTranslator(self.translator) LOGGER.debug( ('%s %s') % (myTranslationPath, os.path.exists(myTranslationPath))) def tr(self, theString): """We implement this ourself since we do not inherit QObject. Args: theString - string for translation. Returns: Translated version of theString. Raises: no exceptions explicitly raised. """ return QCoreApplication.translate('Plugin', theString) def initGui(self): """Gui initialisation procedure (for QGIS plugin api). This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Import dock here as it needs to be imported AFTER i18n is set up from safe_qgis.dock import Dock self.dockWidget = None #-------------------------------------- # Create action for plugin dockable window (show/hide) #-------------------------------------- # pylint: disable=W0201 self.actionDock = QAction(QIcon(':/plugins/inasafe/icon.png'), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.actionDock.setObjectName('InaSAFEDockToggle') self.actionDock.setStatusTip(self.tr('Show/hide InaSAFE dock widget')) self.actionDock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget')) self.actionDock.setCheckable(True) self.actionDock.setChecked(True) QObject.connect(self.actionDock, SIGNAL('triggered()'), self.showHideDockWidget) # add to plugin toolbar self.iface.addToolBarIcon(self.actionDock) # add to plugin menu self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionDock) #-------------------------------------- # Create action for keywords editor #-------------------------------------- self.actionKeywordsDialog = QAction( QIcon(':/plugins/inasafe/keywords.png'), self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow()) self.actionKeywordsDialog.setStatusTip( self.tr('Open InaSAFE keywords editor')) self.actionKeywordsDialog.setWhatsThis( self.tr('Open InaSAFE keywords editor')) self.actionKeywordsDialog.setEnabled(False) QObject.connect(self.actionKeywordsDialog, SIGNAL('triggered()'), self.showKeywordsEditor) self.iface.addToolBarIcon(self.actionKeywordsDialog) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionKeywordsDialog) #-------------------------------------- # Create action for reset icon #-------------------------------------- self.actionResetDock = QAction(QIcon(':/plugins/inasafe/reload.png'), self.tr('Reset Dock'), self.iface.mainWindow()) self.actionResetDock.setStatusTip(self.tr('Reset the InaSAFE Dock')) self.actionResetDock.setWhatsThis(self.tr('Reset the InaSAFE Dock')) QObject.connect(self.actionResetDock, SIGNAL('triggered()'), self.resetDock) self.iface.addToolBarIcon(self.actionResetDock) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionResetDock) #-------------------------------------- # Create action for options dialog #-------------------------------------- self.actionOptions = QAction(QIcon(':/plugins/inasafe/options.png'), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.actionOptions.setStatusTip(self.tr('Open InaSAFE options dialog')) self.actionOptions.setWhatsThis(self.tr('Open InaSAFE options dialog')) QObject.connect(self.actionOptions, SIGNAL('triggered()'), self.showOptions) self.iface.addToolBarIcon(self.actionOptions) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionOptions) #-------------------------------------- # Create action for impact functions doc dialog #-------------------------------------- self.actionImpactFunctionsDoc = QAction( QIcon(':/plugins/inasafe/functions-table.png'), self.tr('InaSAFE Impact Functions Browser'), self.iface.mainWindow()) self.actionImpactFunctionsDoc.setStatusTip( self.tr('Open InaSAFE Impact Functions Browser')) self.actionImpactFunctionsDoc.setWhatsThis( self.tr('Open InaSAFE Impact Functions Browser')) QObject.connect(self.actionImpactFunctionsDoc, SIGNAL('triggered()'), self.showImpactFunctionsDoc) self.iface.addToolBarIcon(self.actionImpactFunctionsDoc) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionImpactFunctionsDoc) # Short cut for Open Impact Functions Doc self.keyAction = QAction("Test Plugin", self.iface.mainWindow()) self.iface.registerMainWindowAction(self.keyAction, "F7") QObject.connect(self.keyAction, SIGNAL("triggered()"), self.keyActionF7) #-------------------------------------- # create dockwidget and tabify it with the legend #-------------------------------------- self.dockWidget = Dock(self.iface) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget) myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend') if myLegendTab: self.iface.mainWindow().tabifyDockWidget(myLegendTab, self.dockWidget) self.dockWidget.raise_() # # Hook up a slot for when the current layer is changed # QObject.connect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged) # # Hook up a slot for when the dock is hidden using its close button # or view-panels # QObject.connect(self.dockWidget, SIGNAL("visibilityChanged (bool)"), self.toggleActionDock) # pylint: disable=W0201 def unload(self): """Gui breakdown procedure (for QGIS plugin api). This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Remove the plugin menu item and icon self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionDock) self.iface.removeToolBarIcon(self.actionDock) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionKeywordsDialog) self.iface.removeToolBarIcon(self.actionKeywordsDialog) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionResetDock) self.iface.removeToolBarIcon(self.actionResetDock) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionOptions) self.iface.removeToolBarIcon(self.actionOptions) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionImpactFunctionsDoc) self.iface.removeToolBarIcon(self.actionImpactFunctionsDoc) self.iface.mainWindow().removeDockWidget(self.dockWidget) self.dockWidget.setVisible(False) self.dockWidget.destroy() QObject.disconnect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged) def toggleActionDock(self, checked): """check or uncheck the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels .. see also:: :func:`Plugin.initGui`. Args: checked - if actionDock has to be checked or not Returns: None. Raises: no exceptions explicitly raised. """ self.actionDock.setChecked(checked) # Run method that performs all the real work def showHideDockWidget(self): """Show or hide the dock widget. This slot is called when the user clicks the toolbar icon or menu item associated with this plugin. It will hide or show the dock depending on its current state. .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ if self.dockWidget.isVisible(): self.dockWidget.setVisible(False) else: self.dockWidget.setVisible(True) self.dockWidget.raise_() def showOptions(self): """Show the options dialog. This slot is called when the user clicks the options toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.options_dialog import OptionsDialog myDialog = OptionsDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.show() def showKeywordsEditor(self): """Show the keywords editor. This slot is called when the user clicks the keyword editor toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.keywords_dialog import KeywordsDialog if self.iface.activeLayer() is None: return myDialog = KeywordsDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.setModal(True) myDialog.show() def showImpactFunctionsDoc(self): """Show the keywords editor. This slot is called when the user clicks the impact functions toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.impact_functions_doc import ImpactFunctionsDoc myDialog = ImpactFunctionsDoc(self.iface.mainWindow()) myDialog.show() def resetDock(self): """Reset the dock to its default state. This slot is called when the user clicks the reset icon in the toolbar or the reset menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ self.dockWidget.getLayers() def layerChanged(self, theLayer): """Enable or disable the keywords editor icon. This slot is called when the user clicks the keyword editor toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ if theLayer is None: self.actionKeywordsDialog.setEnabled(False) else: self.actionKeywordsDialog.setEnabled(True) self.dockWidget.layerChanged(theLayer) def keyActionF7(self): '''Executed when user press F7''' self.showImpactFunctionsDoc()
class CatalogOTFPlugin: def __init__(self, iface): def translate(): # # For create file 'qm' # 1) Define that files need for translation: catalogotf.pro # 2) Create 'ts': pylupdate4 -verbose catalogotf.pro # 3) Edit your translation: QtLinquist # 4) Create 'qm': lrelease catalogotf_pt_BR.ts # dirname = os.path.dirname(os.path.abspath(__file__)) locale = QSettings().value("locale/userLocale") localePath = os.path.join(dirname, "i18n", "%s_%s.qm" % (name_src, locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.iface = iface self.projOTF = ProjectDockWidgetCatalogOTF(iface) self.name = u"&Catalog OTF" self.dock = None name_src = "catalogotf" translate() def _connect(self, isConnect=True): signal_slot = ({ 'signal': QgsProject.instance().readProject, 'slot': self.projOTF.onReadProject }, { 'signal': QgsProject.instance().writeProject, 'slot': self.projOTF.onWriteProject }) if isConnect: for item in signal_slot: item['signal'].connect(item['slot']) else: for item in signal_slot: item['signal'].disconnect(item['slot']) def initGui(self): msgtrans = QCoreApplication.translate("CatalogOTF", "Catalog on the fly") icon = QIcon(os.path.join(os.path.dirname(__file__), 'catalogotf.svg')) self.action = QAction(icon, msgtrans, self.iface.mainWindow()) self.action.setObjectName("CatalogOTF") self.action.setWhatsThis(msgtrans) self.action.setStatusTip(msgtrans) self.action.triggered.connect(self.run) self.iface.addToolBarIcon(self.action) self.iface.addPluginToRasterMenu(self.name, self.action) self._connect() def unload(self): self.iface.removePluginMenu(self.name, self.action) self.iface.removeToolBarIcon(self.action) del self.action del self.dock self._connect(False) @pyqtSlot() def run(self): self.dock = DockWidgetCatalogOTF(self.iface) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock) self.action.setEnabled(False)
class MetaSearchPlugin(object): """base plugin""" def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.dialog = None self.web_menu = '&MetaSearch' def initGui(self): """startup""" # run run_icon = QIcon('%s/%s' % (self.context.ppath, 'images/MetaSearch.png')) self.action_run = QAction(run_icon, 'MetaSearch', self.iface.mainWindow()) self.action_run.setWhatsThis( QCoreApplication.translate('MetaSearch', 'MetaSearch plugin')) self.action_run.setStatusTip( QCoreApplication.translate('MetaSearch', 'Search Metadata Catalogues')) self.action_run.triggered.connect(self.run) self.iface.addWebToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png')) self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow()) self.action_help.setWhatsThis( QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help')) self.action_help.setStatusTip( QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch')) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface) def unload(self): """teardown""" # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_run) self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.iface.removeWebToolBarIcon(self.action_run) def run(self): """open MetaSearch""" self.dialog.exec_() def help(self): """open help in user's default web browser""" open_url(self.context.metadata.get('general', 'homepage'))
class QgepPlugin: """ A plugin for wastewater management http://www.github.com/qgep/QGEP """ # The networkAnalyzer will manage the networklayers and pathfinding network_analyzer = None # Remember not to reopen the dock if there's already one opened profileDock = None # Wizard wizarddock = None # The layer ids the plugin will need edgeLayer = None nodeLayer = None specialStructureLayer = None networkElementLayer = None profile = None def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.nodes = None self.edges = None self.initLogger() setup_i18n() def tr(self, source_text): """ This does not inherit from QObject but for the translation to work (in particular to have translatable strings picked up) we need a tr method. :rtype : unicode :param source_text: The text to translate :return: The translated text """ return QApplication.translate('QgepPlugin', source_text) def initLogger(self): """ Initializes the logger """ self.logger = logging.getLogger(__package__) settings = QSettings() loglevel = settings.value("/QGEP/LogLevel", 'Warning') logfile = settings.value("/QGEP/LogFile", None) if hasattr(self.logger, 'qgepFileHandler'): self.logger.removeHandler(self.logger.qgepFileHandler) del self.logger.qgepFileHandler self.logger.addHandler(QgepQgsLogHandler()) if logfile: log_handler = logging.FileHandler(logfile) fmt = logging.Formatter(LOGFORMAT) log_handler.setFormatter(fmt) self.logger.addHandler(log_handler) self.logger.fileHandler = log_handler if 'Debug' == loglevel: self.logger.setLevel(logging.DEBUG) elif 'Info' == loglevel: self.logger.setLevel(logging.INFO) elif 'Warning' == loglevel: self.logger.setLevel(logging.WARNING) elif 'Error' == loglevel: self.logger.setLevel(logging.ERROR) fp = os.path.join(os.path.abspath(os.path.dirname(__file__)), "metadata.txt") ini_text = QSettings(fp, QSettings.IniFormat) verno = ini_text.value("version") self.logger.info('QGEP plugin version ' + verno + ' started') def initGui(self): """ Called to setup the plugin GUI """ self.network_layer_notifier = QgepLayerNotifier( self.iface.mainWindow(), ['vw_network_node', 'vw_network_segment']) self.wastewater_networkelement_layer_notifier = QgepLayerNotifier( self.iface.mainWindow(), ['vw_wastewater_node', 'vw_qgep_reach']) self.toolbarButtons = [] # Create toolbar button self.profileAction = QAction( QIcon(":/plugins/qgepplugin/icons/wastewater-profile.svg"), self.tr("Profile"), self.iface.mainWindow()) self.profileAction.setWhatsThis(self.tr("Reach trace")) self.profileAction.setEnabled(False) self.profileAction.setCheckable(True) self.profileAction.triggered.connect(self.profileToolClicked) self.downstreamAction = QAction( QIcon(":/plugins/qgepplugin/icons/wastewater-downstream.svg"), self.tr("Downstream"), self.iface.mainWindow()) self.downstreamAction.setWhatsThis(self.tr("Downstream reaches")) self.downstreamAction.setEnabled(False) self.downstreamAction.setCheckable(True) self.downstreamAction.triggered.connect(self.downstreamToolClicked) self.upstreamAction = QAction( QIcon(":/plugins/qgepplugin/icons/wastewater-upstream.svg"), self.tr("Upstream"), self.iface.mainWindow()) self.upstreamAction.setWhatsThis(self.tr("Upstream reaches")) self.upstreamAction.setEnabled(False) self.upstreamAction.setCheckable(True) self.upstreamAction.triggered.connect(self.upstreamToolClicked) self.wizardAction = QAction( QIcon(":/plugins/qgepplugin/icons/wizard.svg"), "Wizard", self.iface.mainWindow()) self.wizardAction.setWhatsThis( self.tr("Create new manholes and reaches")) self.wizardAction.setEnabled(False) self.wizardAction.setCheckable(True) self.wizardAction.triggered.connect(self.wizard) self.connectNetworkElementsAction = QAction( QIcon( ":/plugins/qgepplugin/icons/link-wastewater-networkelement.svg" ), QApplication.translate('qgepplugin', 'Connect wastewater networkelements'), self.iface.mainWindow()) self.connectNetworkElementsAction.setEnabled(False) self.connectNetworkElementsAction.setCheckable(True) self.connectNetworkElementsAction.triggered.connect( self.connectNetworkElements) self.refreshNetworkTopologyAction = QAction( QIcon(":/plugins/qgepplugin/icons/refresh-network.svg"), "Refresh network topology", self.iface.mainWindow()) self.refreshNetworkTopologyAction.setWhatsThis( self.tr("Refresh network topology")) self.refreshNetworkTopologyAction.setEnabled(False) self.refreshNetworkTopologyAction.setCheckable(False) self.refreshNetworkTopologyAction.triggered.connect( self.refreshNetworkTopologyActionClicked) self.aboutAction = QAction(self.tr('About'), self.iface.mainWindow()) self.aboutAction.triggered.connect(self.about) self.settingsAction = QAction(self.tr('Settings'), self.iface.mainWindow()) self.settingsAction.triggered.connect(self.showSettings) # Add toolbar button and menu item self.toolbar = QToolBar(QApplication.translate('qgepplugin', 'QGEP')) self.toolbar.addAction(self.profileAction) self.toolbar.addAction(self.upstreamAction) self.toolbar.addAction(self.downstreamAction) self.toolbar.addAction(self.wizardAction) self.toolbar.addAction(self.refreshNetworkTopologyAction) self.toolbar.addAction(self.connectNetworkElementsAction) self.iface.addPluginToMenu("&QGEP", self.profileAction) self.iface.addPluginToMenu("&QGEP", self.settingsAction) self.iface.addPluginToMenu("&QGEP", self.aboutAction) self.iface.addToolBar(self.toolbar) # Local array of buttons to enable / disable based on context self.toolbarButtons.append(self.profileAction) self.toolbarButtons.append(self.upstreamAction) self.toolbarButtons.append(self.downstreamAction) self.toolbarButtons.append(self.wizardAction) self.toolbarButtons.append(self.refreshNetworkTopologyAction) self.network_layer_notifier.layersAvailable.connect( self.onLayersAvailable) self.network_layer_notifier.layersUnavailable.connect( self.onLayersUnavailable) # Init the object maintaining the network self.network_analyzer = QgepGraphManager(self.iface) # Create the map tool for profile selection self.profile_tool = QgepProfileMapTool(self.iface, self.profileAction, self.network_analyzer) self.profile_tool.profileChanged.connect(self.onProfileChanged) self.upstream_tree_tool = QgepTreeMapTool(self.iface, self.upstreamAction, self.network_analyzer) self.upstream_tree_tool.setDirection("upstream") self.upstream_tree_tool.treeChanged.connect(self.onTreeChanged) self.downstream_tree_tool = QgepTreeMapTool(self.iface, self.downstreamAction, self.network_analyzer) self.downstream_tree_tool.setDirection("downstream") self.downstream_tree_tool.treeChanged.connect(self.onTreeChanged) self.maptool_connect_networkelements = QgepMapToolConnectNetworkElements( self.iface, self.connectNetworkElementsAction) self.wastewater_networkelement_layer_notifier.layersAvailableChanged.connect( self.connectNetworkElementsAction.setEnabled) self.processing_provider = QgepProcessingProvider() Processing.addProvider(self.processing_provider) def unload(self): """ Called when unloading """ self.toolbar.removeAction(self.profileAction) self.toolbar.removeAction(self.upstreamAction) self.toolbar.removeAction(self.downstreamAction) self.toolbar.removeAction(self.wizardAction) self.toolbar.removeAction(self.refreshNetworkTopologyAction) self.toolbar.removeAction(self.connectNetworkElementsAction) self.toolbar.deleteLater() self.iface.removePluginMenu("&QGEP", self.profileAction) self.iface.removePluginMenu("&QGEP", self.aboutAction) def onLayersAvailable(self, layers): for b in self.toolbarButtons: b.setEnabled(True) self.network_analyzer.setReachLayer(layers['vw_network_segment']) self.network_analyzer.setNodeLayer(layers['vw_network_node']) def onLayersUnavailable(self): for b in self.toolbarButtons: b.setEnabled(False) def profileToolClicked(self): """ Is executed when the profile button is clicked """ self.openDock() # Set the profile map tool self.profile_tool.setActive() def upstreamToolClicked(self): """ Is executed when the user clicks the upstream search tool """ self.openDock() self.upstream_tree_tool.setActive() def downstreamToolClicked(self): """ Is executed when the user clicks the downstream search tool """ self.openDock() self.downstream_tree_tool.setActive() def refreshNetworkTopologyActionClicked(self): """ Is executed when the user clicks the refreshNetworkTopologyAction tool """ self.network_analyzer.refresh() def wizard(self): """ """ if not self.wizarddock: self.wizarddock = QgepWizard(self.iface.mainWindow(), self.iface) self.logger.debug('Opening Wizard') self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.wizarddock) self.wizarddock.show() @pyqtSlot() def connectNetworkElements(self): print 'Copnnet them' self.iface.mapCanvas().setMapTool(self.maptool_connect_networkelements) def openDock(self): """ Opens the dock """ if self.profileDock is None: self.logger.debug('Open dock') self.profileDock = QgepProfileDockWidget(self.iface.mainWindow(), self.iface.mapCanvas(), self.iface.addDockWidget) self.profileDock.closed.connect(self.onDockClosed) self.profileDock.showIt() self.plotWidget = QgepPlotSVGWidget(self.profileDock, self.network_analyzer) self.plotWidget.specialStructureMouseOver.connect( self.highlightProfileElement) self.plotWidget.specialStructureMouseOut.connect( self.unhighlightProfileElement) self.plotWidget.reachMouseOver.connect( self.highlightProfileElement) self.plotWidget.reachMouseOut.connect( self.unhighlightProfileElement) self.profileDock.addPlotWidget(self.plotWidget) self.profileDock.setTree(self.nodes, self.edges) @pyqtSlot() def onDockClosed(self): # used when Dock dialog is closed """ Gets called when the dock is closed All the cleanup of the dock has to be done here """ self.profileDock = None def onProfileChanged(self, profile): """ The profile changed: update the plot @param profile: The profile to plot """ self.profile = profile.copy() if self.plotWidget: self.plotWidget.setProfile(profile) def onTreeChanged(self, nodes, edges): if self.profileDock: self.profileDock.setTree(nodes, edges) self.nodes = nodes self.edges = edges @pyqtSlot(unicode) def highlightProfileElement(self, obj_id): if self.profile is not None: self.profile.highlight(unicode(obj_id)) @pyqtSlot() def unhighlightProfileElement(self): if self.profile is not None: self.profile.highlight(None) def about(self): from ui.dlgabout import DlgAbout DlgAbout(self.iface.mainWindow()).exec_() def showSettings(self): settings_dlg = QgepSettingsDialog(self.iface.mainWindow()) settings_dlg.exec_()
class TemporalSpectralProfilePlugin: POINT_SELECTION = 0 SELECTED_POLYGON = 1 def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.wdg = None self.pointTool = None def initGui(self): # create action self.action = QAction( QIcon( ":/plugins/temporalprofiletool/icons/temporalProfileIcon.png"), "Temporal/Spectral Profile", self.iface.mainWindow()) self.action.setWhatsThis("Plots temporal/spectral profiles") QObject.connect(self.action, SIGNAL("triggered()"), self.run) self.aboutAction = QAction("About", self.iface.mainWindow()) QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about) # add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu("&Profile Tool", self.action) self.iface.addPluginToMenu("&Profile Tool", self.aboutAction) #Init class variables self.pointTool = ProfiletoolMapTool(self.iface.mapCanvas(), self.action) #the mouselistener self.dockOpened = False #remember for not reopening dock if there's already one opened self.pointstoDraw = None #Polyline in mapcanvas CRS analysed self.dblclktemp = None #enable disctinction between leftclick and doubleclick self.mdl = None #the model whitch in are saved layers analysed caracteristics self.selectionmethod = 0 #The selection method defined in option self.saveTool = self.canvas.mapTool( ) #Save the standard mapttool for restoring it at the end self.plotlibrary = None #The plotting library to use self.pointSelectionInstructions = "Click on a raster for temporal/spectral profile (right click to cancel then quit)" self.selectedPolygonInstructions = 'Use "Select Features" tool to select polygon(s) designating AOI for which temporal/spectral profile should be calculated' def unload(self): if not self.wdg is None: self.wdg.close() self.iface.removeToolBarIcon(self.action) self.iface.removePluginMenu("&Profile Tool", self.action) self.iface.removePluginMenu("&Profile Tool", self.aboutAction) def run(self): # first, check posibility if self.checkIfOpening() == False: return #if dock not already opened, open the dock and all the necessary thing (model,doProfile...) if self.dockOpened == False: self.mdl = QStandardItemModel(0, 6) self.wdg = PTDockWidget(self.iface.mainWindow(), self.iface, self.mdl) self.wdg.showIt() self.doprofile = DoProfile(self.iface, self.wdg, self.pointTool, self) self.tableViewTool = TableViewTool() QObject.connect(self.wdg, SIGNAL("closed(PyQt_PyObject)"), self.cleaning2) QObject.connect(self.wdg.tableView, SIGNAL("clicked(QModelIndex)"), self._onClick) QObject.connect(self.wdg.pushButton_2, SIGNAL("clicked()"), self.addLayer) QObject.connect(self.wdg.pushButton, SIGNAL("clicked()"), self.removeLayer) QObject.connect(self.wdg.comboBox, SIGNAL("currentIndexChanged(int)"), self.selectionMethod) QObject.connect(self.wdg.cboLibrary, SIGNAL("currentIndexChanged(int)"), self.changePlotLibrary) QObject.connect(self.wdg.cboXAxis, SIGNAL("currentIndexChanged(int)"), self.changeXAxisLabeling) QObject.connect(self.wdg.leXAxisSteps, SIGNAL("editingFinished()"), self.changeXAxisLabeling) QObject.connect(self.wdg.dateTimeEditCurrentTime, SIGNAL("editingFinished()"), self.changeXAxisLabeling) QObject.connect(self.wdg.spinBoxTimeExtent, SIGNAL("editingFinished()"), self.changeXAxisLabeling) QObject.connect(self.wdg.cboTimeExtent, SIGNAL("currentIndexChanged(int)"), self.changeXAxisLabeling) QObject.connect(self.wdg.cbTimeDimension, SIGNAL("stateChanged(int)"), self.changeXAxisLabeling) self.wdg.addOptionComboboxItems() self.addLayer() self.dockOpened = True #Listeners of mouse self.connectPointMapTool() #init the mouse listener comportement and save the classic to restore it on quit self.canvas.setMapTool(self.pointTool) #Help about what doing if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.iface.mainWindow().statusBar().showMessage( self.pointSelectionInstructions) elif self.selectionmethod == TemporalSpectralProfilePlugin.SELECTED_POLYGON: self.iface.mainWindow().statusBar().showMessage( self.selectedPolygonInstructions) QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL("layersWillBeRemoved (QStringList)"), self.onLayersWillBeRemoved) #************************************* Canvas listener actions ********************************************** # Used when layer is about to be removed from QGIS Map Layer Registry def onLayersWillBeRemoved(self, layersIds): if self.mdl is not None: for layerId in layersIds: for row in range(self.mdl.rowCount()): if layerId == self.mdl.index(row, 3).data().id(): self.removeLayer(row) self.onLayersWillBeRemoved(layersIds) break # Use for selected polygon option def selectionChanged(self, layer): if not layer.geometryType() == QGis.Polygon: return fullGeometry = QgsGeometry() for feature in layer.selectedFeatures(): if fullGeometry.isEmpty(): fullGeometry = QgsGeometry(feature.constGeometry()) else: fullGeometry = fullGeometry.combine(feature.constGeometry()) if not fullGeometry.isEmpty(): crs = osr.SpatialReference() crs.ImportFromProj4(str(layer.crs().toProj4())) self.doprofile.calculatePolygonProfile(fullGeometry, crs, self.mdl, self.plotlibrary) #************************************* Mouse listener actions *********************************************** # Used for point selection option def moved(self, point): if self.wdg and not self.wdg.cbPlotWhenClick.isChecked(): if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.doubleClicked(point) if self.selectionmethod == TemporalSpectralProfilePlugin.SELECTED_POLYGON: pass def rightClicked(self, point): #used to quit the current action self.cleaning() def leftClicked(self, point): self.doubleClicked(point) def doubleClicked(self, point): if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.iface.mainWindow().statusBar().showMessage( str(point.x()) + ", " + str(point.y())) self.doprofile.calculatePointProfile(point, self.mdl, self.plotlibrary) if self.selectionmethod == TemporalSpectralProfilePlugin.SELECTED_POLYGON: return #***************************** open and quit options ******************************************* def checkIfOpening(self): if self.iface.mapCanvas().layerCount() == 0: #Check a layer is opened QMessageBox.warning(self.iface.mainWindow(), "Profile", "First open a raster layer, please") return False layer = self.iface.activeLayer() if layer == None or not isProfilable( layer): #Check if a raster layer is opened and selected if self.mdl == None or self.mdl.rowCount() == 0: QMessageBox.warning(self.iface.mainWindow(), "Profile Tool", "Please select a raster layer") return False return True def connectPointMapTool(self): QObject.connect(self.pointTool, SIGNAL("moved"), self.moved) QObject.connect(self.pointTool, SIGNAL("rightClicked"), self.rightClicked) QObject.connect(self.pointTool, SIGNAL("leftClicked"), self.leftClicked) QObject.connect(self.pointTool, SIGNAL("doubleClicked"), self.doubleClicked) QObject.connect(self.pointTool, SIGNAL("deactivate"), self.deactivatePointMapTool) def deactivatePointMapTool(self): #enable clean exit of the plugin QObject.disconnect(self.pointTool, SIGNAL("moved"), self.moved) QObject.disconnect(self.pointTool, SIGNAL("leftClicked"), self.leftClicked) QObject.disconnect(self.pointTool, SIGNAL("rightClicked"), self.rightClicked) QObject.disconnect(self.pointTool, SIGNAL("doubleClicked"), self.doubleClicked) self.iface.mainWindow().statusBar().showMessage("") def connectSelectedPolygonsTool(self): QObject.connect(self.iface.mapCanvas(), SIGNAL("selectionChanged(QgsMapLayer *)"), self.selectionChanged) def deactivateSelectedPolygonsTools(self): QObject.disconnect(self.iface.mapCanvas(), SIGNAL("selectionChanged(QgsMapLayer *)"), self.selectionChanged) def cleaning(self): #used on right click self.canvas.unsetMapTool(self.pointTool) self.canvas.setMapTool(self.saveTool) self.iface.mainWindow().statusBar().showMessage("") def cleaning2(self): #used when Dock dialog is closed QObject.disconnect(self.wdg.tableView, SIGNAL("clicked(QModelIndex)"), self._onClick) if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.deactivatePointMapTool() else: self.deactivateSelectedPolygonsTools() self.selectionmethod = TemporalSpectralProfilePlugin.POINT_SELECTION QObject.disconnect(self.wdg.comboBox, SIGNAL("currentIndexChanged(int)"), self.selectionMethod) QObject.disconnect(QgsMapLayerRegistry.instance(), SIGNAL("layersWillBeRemoved (QStringList)"), self.onLayersWillBeRemoved) self.mdl = None self.dockOpened = False self.cleaning() self.wdg = None #***************************** Options ******************************************* def selectionMethod(self, item): if item == TemporalSpectralProfilePlugin.POINT_SELECTION: self.selectionmethod = TemporalSpectralProfilePlugin.POINT_SELECTION self.pointTool.setCursor(Qt.CrossCursor) self.deactivateSelectedPolygonsTools() self.connectPointMapTool() if not self.canvas.mapTool() == self.pointTool: self.canvas.setMapTool(self.pointTool) self.iface.mainWindow().statusBar().showMessage( self.pointSelectionInstructions) self.wdg.changeStatComboBoxItems( self.doprofile.getPointProfileStatNames()) elif item == TemporalSpectralProfilePlugin.SELECTED_POLYGON: self.selectionmethod = TemporalSpectralProfilePlugin.SELECTED_POLYGON self.deactivatePointMapTool() self.connectSelectedPolygonsTool() self.iface.actionSelectRectangle().trigger() self.iface.mainWindow().statusBar().showMessage( self.selectedPolygonInstructions) self.wdg.changeStatComboBoxItems( self.doprofile.getPolygonProfileStatNames(), "mean") def changePlotLibrary(self, item): self.plotlibrary = self.wdg.cboLibrary.itemText(item) self.wdg.addPlotWidget(self.plotlibrary) self.changeXAxisLabeling() def changeXAxisLabeling(self): self.xAxisSteps = {} # default band number labeling if self.wdg.cboXAxis.currentIndex() == 0: self.doprofile.xAxisSteps = None # Labels from string elif self.wdg.cboXAxis.currentIndex() == 1: self.doprofile.xAxisSteps = self.wdg.leXAxisSteps.text().split(';') try: self.doprofile.xAxisSteps = [ float(x) for x in self.doprofile.xAxisSteps ] except ValueError: self.doprofile.xAxisSteps = None text = "Temporal/Spectral Profile Tool: The X-axis steps' string " + \ "is invalid. Using band numbers instead." self.iface.messageBar().pushWidget( self.iface.messageBar().createMessage(text), QgsMessageBar.WARNING, 5) # Labels based on time elif self.wdg.cboXAxis.currentIndex() == 2: self.doprofile.xAxisSteps = [ "Timesteps", self.wdg.dateTimeEditCurrentTime.dateTime().toPyDateTime(), int(self.wdg.spinBoxTimeExtent.cleanText()), self.wdg.cboTimeExtent.currentText(), self.wdg.cbTimeDimension.isChecked() ] if self.plotlibrary == "Qwt5": text = "Temporal/Spectral Profile Tool: There is currently no support using " + \ "Time steps while using the Qwt plotlibrary" self.iface.messageBar().pushWidget( self.iface.messageBar().createMessage(text), QgsMessageBar.WARNING, 5) self.doprofile.xAxisSteps = None #************************* tableview function ****************************************** def addLayer(self): layer = self.iface.activeLayer() if isProfilable(layer): self.tableViewTool.addLayer(self.iface, self.mdl, layer) def _onClick(self, index1): #action when clicking the tableview self.tableViewTool.onClick(self.iface, self.wdg, self.mdl, self.plotlibrary, index1) def removeLayer(self, index=None): if index is None: index = self.tableViewTool.chooseLayerForRemoval( self.iface, self.mdl) if index is not None: self.tableViewTool.removeLayer(self.mdl, index) PlottingTool().clearData(self.wdg, self.mdl, self.plotlibrary) def about(self): from ui.dlgabout import DlgAbout DlgAbout(self.iface.mainWindow()).exec_()
class ValidaFlags: def __init__(self, iface): self.iface = iface self.tableSchema = 'edgv' self.geometryColumn = 'geom' self.keyColumn = 'id' self.angle = 10 def initGui(self): # cria uma ação que iniciará a configuração do plugin pai = self.iface.mainWindow() icon_path = ':/plugins/ValidaFlags/icon.png' self.action = QAction( QIcon(icon_path), u"Acessa banco de dados para encontrar erros de validação.", pai) self.action.setObjectName("Validation Flags test ") self.action.setStatusTip(None) self.action.setWhatsThis(None) # Adicionar o botão icone self.iface.addToolBarIcon(self.action) # SLOTS self.action.triggered.connect(self.validate) def unload(self): # remove o item de ícone do QGIS GUI. self.iface.removeToolBarIcon(self.action) def validate(self): self.layer = self.iface.activeLayer() if not self.layer: self.iface.messageBar().pushMessage("Erro", u"Esperando uma Active Layer!", level=QgsMessageBar.CRITICAL, duration=4) return if self.layer.featureCount() == 0: self.iface.messageBar().pushMessage( "Erro", u"a camada não possui feições!", level=QgsMessageBar.CRITICAL, duration=4) return self.notSimple = StartNotSimple(self.iface, self.layer) self.intersect = StartTestIntersection(self.iface, self.layer) self.outOfBounds = StartOutofBoundsAngles(self.iface, self.layer) self.duplicate = StartDuplic(self.iface, self.layer) flagId = self.notSimple.run(0) flagId = self.intersect.run(flagId) flagId = self.outOfBounds.run(flagId) flagId = self.duplicate.run(flagId) self.iface.messageBar().pushMessage("Aviso", "foram geradas " + str(flagId) + " flags para a camada \"" + self.layer.name() + "\" !", level=QgsMessageBar.INFO, duration=4)
class RECS: """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', 'RECS_HOME_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.initdlg = InitTaskDialog() self.selectdlg = SelectTaskDialog() self.loginDlg = LogInDialog() self.taskMgrDlg = TaskManagerDialog() self.taskInfoDlg = taskInfo() self.taskFeaturesDlg = taskFeatures() #self.loadmapDlg=LoadMapDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Task') self.logIn() self.selectTask() self.actions = [] self.toolbar = self.iface.addToolBar(u'Recs') self.toolbar.setObjectName(u'Recs') # layer.editingStarted.connect(editLayer() ) # TODO: We are going to let the user set this up in a future iteration #self.toolbar = self.iface.addToolBar(u'SelectTask') #self.toolbar.setObjectName(u'SelectTask') # 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('Tasks', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: # self.menu = QMenu( "&Task", self.iface.mainWindow().menuBar() ) action = self.iface.mainWindow().menuBar().actions() lastAction = action[-1] self.iface.addPluginToMenu(self.menu, lastAction) self.actions.append(lastAction) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" """Create the menu entries and toolbar icons inside the QGIS GUI.""" """ Task menu setting """ self.menu = QMenu(self.iface.mainWindow()) self.menu.setObjectName("task_menu_object") self.menu.setTitle("Task") """ Task """ self.action_tasks = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Tasks", self.iface.mainWindow()) self.action_tasks.setObjectName("Task_action_object") self.action_tasks.setWhatsThis("Task Initialized") #QtCore.QObject.connect(self.action_tasks, SIGNAL("triggered()"), self.tasks) """ Initializing Task """ self.action_init_task = QAction( QIcon('::/plugins/RECS/aacadisicon.png'), "Initialize ", self.iface.mainWindow()) self.action_init_task.setObjectName("Task_action_object") self.action_init_task.setWhatsThis("Task Initialize") QtCore.QObject.connect(self.action_init_task, SIGNAL("triggered()"), self.initTask) """ Select Task """ self.action_select_task = QAction( QIcon(':/plugins/RECS/aacadisicon.png'), "Select Task", self.iface.mainWindow()) self.action_select_task.setObjectName("Task_Select_object") self.action_select_task.setWhatsThis("Select Task") QtCore.QObject.connect(self.action_select_task, SIGNAL("triggered()"), self.selectTask) """ Reload Task """ self.action_reload_task = QAction( QIcon(':/plugins/RECS/aacadisicon.png'), "Reload Task", self.iface.mainWindow()) self.action_reload_task.setObjectName("Task_Reload_object") self.action_reload_task.setWhatsThis("Reload Task") QtCore.QObject.connect(self.action_reload_task, SIGNAL("triggered()"), self.taskManager) """ Edit Task """ self.action_edit_task = QAction( QIcon(':/plugins/RECS/aacadisicon.png'), "Edit Task", self.iface.mainWindow()) self.action_edit_task.setObjectName("Task_Edit_object") self.action_edit_task.setWhatsThis("Edit Task") QtCore.QObject.connect(self.action_edit_task, SIGNAL("triggered()"), self.editLayer) """ Finish Task """ self.action_finish_task = QAction( QIcon(':/plugins/RECS/aacadisicon.png'), "Finish Task", self.iface.mainWindow()) self.action_finish_task.setObjectName("Task_Finish_object") self.action_finish_task.setWhatsThis("Edit Task") QtCore.QObject.connect(self.action_finish_task, SIGNAL("triggered()"), self.finishEditngLayer) """ Add action to the menu list """ #self.menuTask.addAction(self.action_tasks) self.menu.addAction(self.action_init_task) self.menu.addAction(self.action_select_task) self.menu.addAction(self.action_reload_task) self.menu.addAction(self.action_edit_task) self.menu.addAction(self.action_finish_task) """ Add menu to the menubar """ menubar = self.iface.mainWindow().menuBar() menubar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu) """ Add icon to the toolbar """ #self.iface.addPluginToMenu(u"&load Map", self.action_loadmap) #self.iface.addToolBarIcon(self.action_init_task) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Task_Manager'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def initTask(self): layers = self.iface.legendInterface().layers() #layer_list = [] for layer in layers: #layer_list.append(layer.name()) if layer.name() == 'PARCEL': self.iface.setActiveLayer(layer) self.initdlg.show() #layer_list=list(set(layer_list)) #self.initdlg.comboBox.addItems(layer_list) self.initdlg.setFixedSize(self.initdlg.size()) result = self.initdlg.exec_() if result: pass def selectTask(self): self.selectdlg.show() self.selectdlg.setFixedSize(self.selectdlg.size()) self.selectdlg.loadLayer() self.selectdlg.populate() result = self.selectdlg.exec_() if result: # self.selectdlg.close() pass def showTaskInfo(self): self.taskInfoDlg.show() t_id = self.taskMgrDlg.retTaskID() self.taskInfoDlg.getAttribData(t_id) #self.taskInfoDlg.populate() def taskManager(self): if self.taskMgrDlg.isVisible(): self.taskMgrDlg.loadTaskClicked() # self.taskMgrDlg.close() # self.apdockwidget.close() else: self.taskMgrDlg.show() self.apdockwidget = QDockWidget("Task Manager", self.iface.mainWindow()) self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint) self.apdockwidget.setWidget(self.taskMgrDlg) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget) self.taskMgrDlg.populate() self.taskFeatures() # rows = self.taskMgrDlg.taskListTable.rowCount() # createdByList=[] # # # for row in range(0,rows): # createdByItems=self.taskMgrDlg.taskListTable.item(row,1) # createdByList.append(createdByItems.text()) # # # createdByList=list(set(createdByList)) # self.taskMgrDlg.createByComboBox.addItems(createdByList) # self.taskMgrDlg.createByComboBox.setCurrentIndex(createdByList.index()) self.menu = QtGui.QMenu() #newTask=self.menu.addAction("New Task",self.newTask,"") newTask = self.menu.addAction("New Task", self.newTaskEvent) loadTask = self.menu.addAction("Load Task", self.loadTaskEvent) cancelTask = self.menu.addAction("Cancel Task", self.cancelTaskEvent) showTaskArea = self.menu.addAction("Show Task Area", self.showTaskAreaEvent) noTask = self.menu.addAction("No Task", self.noTaskEvent) showTaskInfo = self.menu.addAction("Show Task Info", self.showTaskInfoEvent) updateFeature = self.menu.addAction("Update Features", self.updateFeatureEvent) self.taskMgrDlg.taskListTable.addAction(newTask) self.taskMgrDlg.taskListTable.addAction(loadTask) self.taskMgrDlg.taskListTable.addAction(cancelTask) self.taskMgrDlg.taskListTable.addAction(showTaskArea) self.taskMgrDlg.taskListTable.addAction(noTask) self.taskMgrDlg.taskListTable.addAction(showTaskInfo) self.taskMgrDlg.taskListTable.addAction(updateFeature) self.taskMgrDlg.taskListTable.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.taskMgrDlg.taskListTable.customContextMenuRequested.connect( self.contextMenuEvent) result = self.taskMgrDlg.exec_() if result: self.taskMgrDlg.populate() #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange def contextMenuEvent(self, point): self.menu.exec_(self.taskMgrDlg.taskListTable.mapToGlobal(point)) def newTaskEvent(self): self.initTask() def loadTaskEvent(self): self.taskMgrDlg.loadTaskClicked() t_id = self.taskMgrDlg.retTaskID() self.taskFeaturesDlg.populate(t_id) def cancelTaskEvent(self): self.taskMgrDlg.cancelTask() def showTaskAreaEvent(self): self.taskMgrDlg.showTaskAreaClicked() def noTaskEvent(self): print "noTask Called" def showTaskInfoEvent(self): self.showTaskInfo() def updateFeatureEvent(self): print "updateFeature" def logIn(self): self.loginDlg.show() self.loginDlg.setWindowFlags(Qt.FramelessWindowHint) result = self.loginDlg.exec_() if result: pass def loadLayer(self): self.mlr = None # QgsMapLayerRegistry.instance().removeAllMapLayers() self.mlr = QgsMapLayerRegistry.instance() uri = QgsDataSourceURI() uri.setConnection("172.20.0.71", "5432", "ncrprs_db", "postgres", "123456") uri.setDataSource("recs", "t_parcel", "parcelgeometry", "") vlayer = QgsVectorLayer(uri.uri(), "Parcel", "postgres") if vlayer.isValid(): self.mlr.addMapLayer(vlayer) else: QMessageBox.information( None, "Unable to Laod Data", "Unable to Load Layers from the Database!") return None def editLayer(self): global taskLayer global featCount layers = self.iface.legendInterface().layers() for layer in layers: if layer.name() == 'TaskLayer': taskLayer = layer taskLayerID = layer.id() self.iface.setActiveLayer(taskLayer) featCount = taskLayer.featureCount() print featCount taskLayer.startEditing() QgsProject.instance().setSnapSettingsForLayer(taskLayerID, True, 2, 1, 20, True) def finishEditngLayer(self): """ change the edits to GML again to detect the changes """ print featCount taskLayer_shape = iface.activeLayer() QgsVectorFileWriter.writeAsVectorFormat(taskLayer_shape, "Z:\\GMLEdited\\temp.gml", "utf-8", None, "GML") #QgsMapLayerRegistry.instance().removeAllMapLayers() iface.addVectorLayer("Z:\\GMLEdited\\temp.gml", "EditedTaskLayer", "ogr") """ Compare the two gml geometries """ doc_edited = xml.dom.minidom.parse("Z:\\GMLEdited\\temp.gml") doc_origion = xml.dom.minidom.parse("Z:\\GMLFile\\ogrGML.gml") editedParcel = doc_edited.getElementsByTagName("gml:featureMember") epLength = editedParcel.length print epLength obj = GeometryEdit() if epLength > featCount: obj.split(doc_edited, doc_origion) print "split" elif epLength < featCount: obj.merge(doc_edited, doc_origion) print "merge" else: obj.updateGeom() print "update" def taskFeatures(self): self.taskFeaturesDlg.show() self.apdockwidget = QDockWidget("Features Of Current Task", self.iface.mainWindow()) self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint) self.apdockwidget.setWidget(self.taskFeaturesDlg) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget) self.menu_feature = QtGui.QMenu() #newTask=self.menu.addAction("New Task",self.newTask,"") editAttr = self.menu_feature.addAction("Edit", self.editEvent) self.taskFeaturesDlg.currentTaskTable.addAction(editAttr) self.taskFeaturesDlg.currentTaskTable.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.taskFeaturesDlg.currentTaskTable.customContextMenuRequested.connect( self.contextMenuEvent2) #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange def contextMenuEvent2(self, point): self.menu_feature.exec_( self.taskFeaturesDlg.currentTaskTable.mapToGlobal(point)) def editEvent(self): self.showTaskInfo()
class GDALLocationInfoPlugin: """QGIS Plugin Implementation.""" 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] locale_path = os.path.join( self.plugin_dir, 'i18n', 'GDALLocationInfoPlugin_{}.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'&GDALLocationInfo') # 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('AGSInfo', message) def initGui(self): self.actionRun = QAction(QCoreApplication.translate("GDALLocationInfo", "GDALLocationInfo"), self.iface.mainWindow()) self.actionRun.setIcon(QIcon(":/plugins/AGSInfo/icons/icon.png")) self.actionRun.setWhatsThis("Identify tool for raster layer") self.actionRun.setCheckable(True) self.iface.addRasterToolBarIcon(self.actionRun) self.iface.addPluginToRasterMenu(QCoreApplication.translate("GDALLocationInfo", "GDALLocationInfo"),self.actionRun) self.actionRun.triggered.connect(self.run) # prepare map tool self.mapTool = GDALLocationInfoMapTool(self.iface.mapCanvas()) self.iface.mapCanvas().mapToolSet.connect(self.mapToolChanged) # handle layer changes self.iface.currentLayerChanged.connect(self.toggleTool) def unload(self): self.iface.removeRasterToolBarIcon(self.actionRun) if self.iface.mapCanvas().mapTool() == self.mapTool: self.iface.mapCanvas().unsetMapTool(self.mapTool) del self.mapTool def mapToolChanged(self, tool): if tool != self.mapTool: self.actionRun.setChecked(False) def run(self): self.iface.mapCanvas().setMapTool(self.mapTool) self.actionRun.setChecked(True) def toggleTool(self, layer): if layer is None: return if layer.type() != QgsMapLayer.RasterLayer: self.actionRun.setEnabled(False) if self.iface.mapCanvas().mapTool() == self.mapTool: self.iface.mapCanvas().unsetMapTool(self.mapTool) else: self.actionRun.setEnabled(True)
class ReshapeGeom(): def __init__(self, iface): self.iface = iface def initGui(self): # cria uma ação que iniciará a configuração do plugin self.initVariables() self.initSignals() def initVariables(self): # Criação da action e da toolbar self.toolbar = self.iface.addToolBar("Reshape") path = self.iface.mainWindow() icon_path = ':/plugins/ReshapeGeom/icon.png' self.action = QAction(QIcon(icon_path), u"Reshape feature.", path) self.action.setObjectName("ReshapeGeom") self.action.setStatusTip(None) self.action.setWhatsThis(None) self.action.setCheckable(True) self.toolbar.addAction(self.action) self.lastButton = Qt.RightButton self.controlStatus = False self.createRubberBand() self.previousMapTool = self.iface.mapCanvas().mapTool() self.isEditing = 0 #self.start() def initSignals(self): # self.action.toggled.connect(self.initRubberBand) #self.myMapTool.canvasClicked.connect(self.mouseClick) self.iface.mapCanvas().currentLayerChanged.connect(self.start) def createRubberBand(self): self.myRubberBand = QgsRubberBand(self.iface.mapCanvas()) color = QColor(78, 97, 114) color.setAlpha(190) self.myRubberBand.setColor(color) self.myRubberBand.setFillColor(QColor(255, 0, 0, 40)) self.myRubberBand.setBorderColor(QColor(255, 0, 0, 200)) def start(self): #self.myRubberBand.reset() self.createRubberBand() # Set MapTool self.myMapTool = QgsMapToolEmitPoint(self.iface.mapCanvas()) self.iface.mapCanvas().setMapTool(self.myMapTool) self.iface.mapCanvas().xyCoordinates.connect(self.mouseMove) self.iface.mapCanvas().keyPressed.connect(self.keyPressEvent) self.iface.mapCanvas().keyReleased.connect(self.keyReleaseEvent) # self.myMapTool.canvasClicked.connect(self.mouseClick) def initRubberBand(self, b): if b: self.start() else: self.disconnect() def disconnect(self): self.iface.mapCanvas().setMapTool(self.previousMapTool) try: self.iface.mapCanvas().xyCoordinates.disconnect(self.mouseMove) self.myMapTool.canvasClicked.disconnect(self.mouseClick) self.isEditing = 0 self.lastButton = Qt.RightButton self.myRubberBand.reset() except: pass try: #self.myRubberBand.reset() del self.myRubberBand # del self.myMapTool except: pass def unload(self): self.disconnect() # def mouseClick(self, currentPos, clickedButton): # if self.iface.mapCanvas().currentLayer().type() != QgsMapLayer.VectorLayer: # return # else: # if self.iface.mapCanvas().currentLayer().geometryType() != QGis.Polygon and self.iface.mapCanvas().currentLayer().geometryType() != QGis.Line: # # return # if clickedButton == Qt.LeftButton: # if self.lastButton == Qt.RightButton: # self.myRubberBand.reset() # self.lastButton = Qt.LeftButton # self.isEditing = 1 # elif clickedButton == Qt.RightButton and self.myRubberBand.numberOfVertices() > 2: # self.lastButton = Qt.RightButton # self.doReshape() #____________________________________________________________________________________________________________________ def doReshape(self): self.isEditing = 0 layer = self.iface.mapCanvas().currentLayer() # layer atual layer.startEditing() # Ligando a edição da layer line = self.myRubberBand.asGeometry() # Linha do rubberband for feat in layer.getFeatures(): geom = feat.geometry() # geometria que receberá o reshape. if geom.intersects(line): # Se intersecta geom.reshapeGeometry(line.asPolyline( )) # realiza o reshape entre a linha e a geometria. layer.changeGeometry(feat.id(), geom) self.iface.mapCanvas().refresh( ) # Refresh para atualizar, mas não salvar as alterações self.myRubberBand.reset() #___________________________________________________________________________________________________________________ def mouseMove(self, currentPos): # FreeHand if self.isEditing == 1: # self.myRubberBand.movePoint(QgsPoint(currentPos)) # Rubberband self.myRubberBand.addPoint(QgsPoint(currentPos)) # Freehand def keyPressEvent(self, event): if event.key( ) == QtCore.Qt.Key_Control: #Preciso implementar o Ctrl corretamente. if self.iface.mapCanvas().currentLayer().type( ) != QgsMapLayer.VectorLayer: event.accept() elif self.controlStatus == False: self.controlStatus = True self.isEditing = 1 self.previousMapTool = self.iface.mapCanvas().mapTool() self.action.setChecked(True) self.start() else: event.accept() def keyReleaseEvent(self, event): if event.key( ) == QtCore.Qt.Key_Control: #Preciso implementar o Ctrl corretamente. #self.iface.mapCanvas().setMapTool(self.previousMapTool) if self.iface.mapCanvas().currentLayer().type( ) != QgsMapLayer.VectorLayer: event.accept() elif self.controlStatus == True: if self.myRubberBand.numberOfVertices() > 2: self.doReshape() self.controlStatus = False self.action.setChecked(False) self.iface.mapCanvas().unsetMapTool(self.myMapTool) self.iface.mapCanvas().setMapTool(self.previousMapTool) self.disconnect() else: event.accept()
class GeomFilterEPSG(): def __init__(self, iface): self.iface = iface def initGui(self): # cria uma ação que iniciará a configuração do plugin #self.myMapTool = QgsMapToolEmitPoint( self.iface.mapCanvas() ) self.initVariables() self.initSignals() def initVariables(self): self.coordinates = [] # Criação da action e da toolbar self.toolbar = self.iface.addToolBar("My_ToolBar") pai = self.iface.mainWindow() icon_path = ':/plugins/GeomFilterEPSG/icon.png' self.action = QAction(QIcon(icon_path), u"Filtro EPSG.", pai) self.action.setObjectName("Filtro EPSG.") self.action.setStatusTip(None) self.action.setWhatsThis(None) self.action.setCheckable(True) self.toolbar.addAction(self.action) self.previousMapTool = self.iface.mapCanvas().mapTool() self.myMapTool = QgsMapToolEmitPoint(self.iface.mapCanvas()) self.isEditing = 0 def initSignals(self): self.action.toggled.connect(self.RubberBand) self.myMapTool.canvasClicked.connect(self.mouseClick) def RubberBand(self, bolean): if bolean: self.myRubberBand = QgsRubberBand(self.iface.mapCanvas(), QGis.Polygon) color = QColor(78, 97, 114) color.setAlpha(190) self.myRubberBand.setColor(color) self.myRubberBand.setFillColor(QColor(255, 0, 0, 40)) self.myRubberBand.setBorderColor(QColor(255, 0, 0, 200)) # Set MapTool self.iface.mapCanvas().setMapTool(self.myMapTool) self.iface.mapCanvas().xyCoordinates.connect(self.mouseMove) else: self.disconnect() def disconnect(self): self.iface.mapCanvas().unsetMapTool(self.myMapTool) try: self.iface.mapCanvas().xyCoordinates.disconnect(self.mouseMove) except: pass try: self.myRubberBand.reset() except: pass def unChecked(self): self.action.setCheckable(False) self.action.setCheckable(True) def unload(self): self.disconnect() def mouseClick(self, currentPos, clickedButton): if clickedButton == Qt.LeftButton: # and myRubberBand.numberOfVertices() == 0: self.myRubberBand.addPoint(QgsPoint(currentPos)) self.coordinates.append(QgsPoint(currentPos)) self.isEditing = 1 elif clickedButton == Qt.RightButton and self.myRubberBand.numberOfVertices( ) > 2: self.isEditing = 0 # create feature and set geometry. poly = QgsFeature() geomP = self.myRubberBand.asGeometry() poly.setGeometry(geomP) g = geomP.exportToWkt() # Get WKT coordenates. #print g canvas = self.iface.mapCanvas() c = canvas.mapRenderer().destinationCrs().authid() # Get EPSG. rep = c.replace("EPSG:", "") string = U"st_intersects(geom,st_geomfromewkt('SRID=" + rep + ";" + g + "'))" self.layers = self.iface.mapCanvas().layers() for layer in self.layers: layer.setSubsetString(string) self.myRubberBand.reset(QGis.Polygon) self.disconnect() self.unChecked() def mouseMove(self, currentPos): if self.isEditing == 1: self.myRubberBand.movePoint(QgsPoint(currentPos))
class Plugin(object): """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menu bar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Register all the impact functions register_impact_functions() # Save reference to the QGIS interface self.iface = iface self.dock_widget = None self.action_import_dialog = None self.action_save_scenario = None self.action_batch_runner = None self.action_shake_converter = None self.action_minimum_needs = None self.action_global_minimum_needs = None self.action_impact_merge_dlg = None self.key_action = None self.action_options = None self.action_keywords_dialog = None self.action_keywords_wizard = None self.action_function_centric_wizard = None self.action_extent_selector = None self.translator = None self.toolbar = None self.actions = [] # list of all QActions we create for InaSAFE self.action_dock = None self.action_toggle_rubberbands = None self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) # noinspection PyArgumentList def change_i18n(self, new_locale): """Change internationalisation for the plugin. Override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param new_locale: The new locale i.e. 'id', 'af', etc. :type new_locale: str :raises: TranslationLoadException """ os.environ['INASAFE_LANG'] = str(new_locale) LOGGER.debug('%s %s %s' % ( new_locale, QLocale.system().name(), os.environ['INASAFE_LANG'])) root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) translation_path = os.path.join( root, 'safe_qgis', 'i18n', 'inasafe_' + str(new_locale) + '.qm') if os.path.exists(translation_path): self.translator = QTranslator() result = self.translator.load(translation_path) if not result: message = 'Failed to load translation for %s' % new_locale raise TranslationLoadError(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( translation_path, os.path.exists(translation_path))) # 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('Plugin', message) def add_action(self, action, add_to_toolbar=True): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) def _create_dock_toggle_action(self): """Create action for plugin dockable window (show/hide).""" # pylint: disable=W0201 icon = resources_path('img', 'icons', 'icon.svg') self.action_dock = QAction( QIcon(icon), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.action_dock.setObjectName('InaSAFEDockToggle') self.action_dock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setCheckable(True) self.action_dock.setChecked(True) self.action_dock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.action_dock) def _create_keywords_action(self): """Create action for keywords editor.""" icon = resources_path('img', 'icons', 'show-keyword-editor.svg') self.action_keywords_dialog = QAction( QIcon(icon), self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow()) self.action_keywords_dialog.setStatusTip(self.tr( 'Open InaSAFE keywords editor')) self.action_keywords_dialog.setWhatsThis(self.tr( 'Open InaSAFE keywords editor')) self.action_keywords_dialog.setEnabled(False) self.action_keywords_dialog.triggered.connect( self.show_keywords_editor) self.add_action( self.action_keywords_dialog, add_to_toolbar=self.full_toolbar) def _create_keywords_wizard_action(self): """Create action for keywords creation wizard.""" icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('InaSAFE Keywords Creation Wizard'), self.iface.mainWindow()) self.action_keywords_wizard.setStatusTip(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setWhatsThis(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setEnabled(False) self.action_keywords_wizard.triggered.connect( self.show_keywords_wizard) self.add_action(self.action_keywords_wizard) def _create_analysis_wizard_action(self): """Create action for IF-centric wizard.""" icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('InaSAFE Impact Function Centric Wizard'), self.iface.mainWindow()) self.action_function_centric_wizard.setStatusTip(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setWhatsThis(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setEnabled(True) self.action_function_centric_wizard.triggered.connect( self.show_function_centric_wizard) self.add_action(self.action_function_centric_wizard) def _create_options_dialog_action(self): """Create action for options dialog.""" icon = resources_path('img', 'icons', 'configure-inasafe.svg') self.action_options = QAction( QIcon(icon), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.action_options.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.action_options.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) self.action_options.triggered.connect(self.show_options) self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_action(self): """Create action for minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.action_minimum_needs = QAction( QIcon(icon), self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow()) self.action_minimum_needs.setStatusTip(self.tr( 'Open InaSAFE minimum needs tool')) self.action_minimum_needs.setWhatsThis(self.tr( 'Open InaSAFE minimum needs tool')) self.action_minimum_needs.triggered.connect(self.show_minimum_needs) self.add_action( self.action_minimum_needs, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_options_action(self): """Create action for global minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg') self.action_global_minimum_needs = QAction( QIcon(icon), self.tr('InaSAFE Global Minimum Needs Configuration'), self.iface.mainWindow()) self.action_global_minimum_needs.setStatusTip(self.tr( 'Open InaSAFE global minimum needs configuration')) self.action_global_minimum_needs.setWhatsThis(self.tr( 'Open InaSAFE global minimum needs configuration')) self.action_global_minimum_needs.triggered.connect( self.show_global_minimum_needs_configuration) self.add_action( self.action_global_minimum_needs, add_to_toolbar=self.full_toolbar) def _create_shakemap_converter_action(self): """Create action for converter dialog.""" icon = resources_path('img', 'icons', 'show-converter-tool.svg') self.action_shake_converter = QAction( QIcon(icon), self.tr('InaSAFE Converter'), self.iface.mainWindow()) self.action_shake_converter.setStatusTip(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.setWhatsThis(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.triggered.connect( self.show_shakemap_importer) self.add_action( self.action_shake_converter, add_to_toolbar=self.full_toolbar) def _create_batch_runner_action(self): """Create action for batch runner dialog.""" icon = resources_path('img', 'icons', 'show-batch-runner.svg') self.action_batch_runner = QAction( QIcon(icon), self.tr('InaSAFE Batch Runner'), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr( 'Open InaSAFE Batch Runner')) self.action_batch_runner.setWhatsThis(self.tr( 'Open InaSAFE Batch Runner')) self.action_batch_runner.triggered.connect(self.show_batch_runner) self.add_action( self.action_batch_runner, add_to_toolbar=self.full_toolbar) def _create_save_scenario_action(self): """Create action for save scenario dialog.""" icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction( QIcon(icon), self.tr('Save Current Scenario'), self.iface.mainWindow()) message = self.tr('Save current scenario to text file') self.action_save_scenario.setStatusTip(message) self.action_save_scenario.setWhatsThis(message) # noinspection PyUnresolvedReferences self.action_save_scenario.triggered.connect(self.save_scenario) self.add_action( self.action_save_scenario, add_to_toolbar=self.full_toolbar) def _create_osm_downloader_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'show-osm-download.svg') self.action_import_dialog = QAction( QIcon(icon), self.tr('InaSAFE OpenStreetMap Downloader'), self.iface.mainWindow()) self.action_import_dialog.setStatusTip(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.action_import_dialog.setWhatsThis(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.action_import_dialog.triggered.connect(self.show_osm_downloader) self.add_action(self.action_import_dialog) def _create_impact_merge_action(self): """Create action for impact layer merge Dialog.""" icon = resources_path('img', 'icons', 'show-impact-merge.svg') self.action_impact_merge_dlg = QAction( QIcon(icon), self.tr('InaSAFE Impact Layer Merge'), self.iface.mainWindow()) self.action_impact_merge_dlg.setStatusTip(self.tr( 'InaSAFE Impact Layer Merge')) self.action_impact_merge_dlg.setWhatsThis(self.tr( 'InaSAFE Impact Layer Merge')) self.action_impact_merge_dlg.triggered.connect(self.show_impact_merge) self.add_action( self.action_impact_merge_dlg, add_to_toolbar=self.full_toolbar) def _create_rubber_bands_action(self): """Create action for toggling rubber bands.""" icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg') self.action_toggle_rubberbands = QAction( QIcon(icon), self.tr('Toggle Scenario Outlines'), self.iface.mainWindow()) message = self.tr('Toggle rubber bands showing scenarion extents.') self.action_toggle_rubberbands.setStatusTip(message) self.action_toggle_rubberbands.setWhatsThis(message) # Set initial state self.action_toggle_rubberbands.setCheckable(True) settings = QSettings() flag = bool(settings.value( 'inasafe/showRubberBands', False, type=bool)) self.action_toggle_rubberbands.setChecked(flag) # noinspection PyUnresolvedReferences self.action_toggle_rubberbands.triggered.connect( self.dock_widget.toggle_rubber_bands) self.add_action(self.action_toggle_rubberbands) def _create_analysis_extent_action(self): """Create action for analysis extent dialog.""" icon = resources_path('img', 'icons', 'set-extents-tool.svg') self.action_extent_selector = QAction( QIcon(icon), self.tr('Set InaSAFE Analysis Area'), self.iface.mainWindow()) self.action_extent_selector.setStatusTip(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.setWhatsThis(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.triggered.connect( self.show_extent_selector) self.add_action(self.action_extent_selector) def _create_test_layers_action(self): """Create action for adding layers (developer mode, non final only).""" final_release = release_status() == 'final' settings = QSettings() self.developer_mode = settings.value( 'inasafe/developer_mode', False, type=bool) if not final_release and self.developer_mode: icon = resources_path('img', 'icons', 'add-test-layers.svg') self.action_add_layers = QAction( QIcon(icon), self.tr('Add Some Test Layers'), self.iface.mainWindow()) self.action_add_layers.setStatusTip(self.tr( 'Add some test layers')) self.action_add_layers.setWhatsThis(self.tr( 'Add some test layers')) self.action_add_layers.triggered.connect( self.add_test_layers) self.add_action(self.action_add_layers) def _create_dock(self): """Create dockwidget and tabify it with the legend.""" # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = Dock(self.iface) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend') if legend_tab: self.iface.mainWindow().tabifyDockWidget( legend_tab, self.dock_widget) self.dock_widget.raise_() def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') self.dock_widget = None # Now create the actual dock self._create_dock() # And all the menu actions # Configuration Group self._create_options_dialog_action() self._create_minimum_needs_options_action() self._create_analysis_extent_action() self._create_dock_toggle_action() self._create_rubber_bands_action() # TODO: add menu separator - Wizards self._create_keywords_wizard_action() self._create_analysis_wizard_action() # TODO: add menu separator - Data self._create_osm_downloader_action() self._create_shakemap_converter_action() self._create_minimum_needs_action() self._create_test_layers_action() # TODO: add menu separator - Analysis self._create_batch_runner_action() self._create_impact_merge_action() self._create_save_scenario_action() # TODO: This action (and related code) will be deprecated # keywords dialog to be replaced by keywords wizard self._create_keywords_action() # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action) # Also deal with the fact that on start of QGIS dock may already be # hidden. self.action_dock.setChecked(self.dock_widget.isVisible()) def clear_modules(self): """Unload inasafe functions and try to return QGIS to before InaSAFE. .. todo:: I think this function can be removed. TS. """ # next lets force remove any inasafe related modules modules = [] for module in sys.modules: if 'inasafe' in module: # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module.split('.') path = '' for myToken in tokens: path += os.path.sep + myToken parent = os.path.abspath(os.path.join( __file__, os.path.pardir, os.path.pardir)) full_path = os.path.join(parent, path + '.py') if os.path.exists(os.path.abspath(full_path)): LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) for module in sys.modules: if 'inasafe' in module: print module # Lets also clean up all the path additions that were made package_path = os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.mainWindow().removeDockWidget(self.dock_widget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dock_widget.setVisible(False) self.dock_widget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) def toggle_inasafe_action(self, checked): """Check or un-check the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.action_dock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dock_widget.isVisible(): self.dock_widget.setVisible(False) else: self.dock_widget.setVisible(True) self.dock_widget.raise_() def add_test_layers(self): """Add standard test layers.""" from safe.test.utilities import load_standard_layers load_standard_layers() def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, self.iface.mainWindow(), extent=self.dock_widget.extent.user_extent, crs=self.dock_widget.extent.user_extent_crs) widget.clear_extent.connect( self.dock_widget.extent.clear_user_analysis_extent) widget.extent_defined.connect( self.dock_widget.define_user_analysis_extent) # Needs to be non modal to support hide -> interact with map -> show widget.show() # non modal def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.show() # non modal def show_global_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog( parent=self.iface.mainWindow(), dock=self.dock_widget) dialog.exec_() # modal def show_impact_merge(self): """Show the impact layer merge dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.impact_merge_dialog import ImpactMergeDialog dialog = ImpactMergeDialog(self.iface.mainWindow()) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog dialog = OptionsDialog( self.iface, self.dock_widget, self.iface.mainWindow()) dialog.exec_() # modal def show_keywords_editor(self): """Show the keywords editor.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.keywords_dialog import KeywordsDialog # Next block is a fix for #776 if self.iface.activeLayer() is None: return try: keyword_io = KeywordIO() keyword_io.read_keywords(self.iface.activeLayer()) except UnsupportedProviderError: # noinspection PyUnresolvedReferences,PyCallByClass # noinspection PyTypeChecker,PyArgumentList QMessageBox.warning( None, self.tr('Unsupported layer type'), self.tr( 'The layer you have selected cannot be used for ' 'analysis because its data type is unsupported.')) return # End of fix for #776 # Fix for #793 except NoKeywordsFoundError: # we will create them from scratch in the dialog pass # End of fix for #793 # Fix for filtered-layer except InvalidParameterError, e: # noinspection PyTypeChecker,PyTypeChecker,PyArgumentList QMessageBox.warning( None, self.tr('Invalid Layer'), e.message ) return dialog = KeywordsDialog( self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_() # modal
class HmvPlugin(QObject): """Plugin object to initialize pipe network analyzer as a QGIS plugin """ def __init__(self, iface): super(HmvPlugin, self).__init__() self.iniConfig = ConfigParser.ConfigParser() self.iniConfig.readfp( open( os.path.join(qgis.core.QgsApplication.qgisSettingsDirPath(), 'python/plugins/hmv/hmv.ini'))) # Reference to the QGIS Qt environment self.iface = iface self.dock = None self.stPluginAction = None # Setting up the application log self.configureLogging() # Used to store the network environment once initialized self.netEnv = None # Model for GUI size list self.sizeListModel = None self.resultsWin = None self.resultsModel = None self.pressureResultsWin = None self.pressureResultsModel = None self.chartWin = None self.elementErrTableModel = None def initGui(self): # create Qt action that will open the plugin self.stPluginAction = QAction(u"HMV Méretezés", self.iface.mainWindow()) # pylint: disable=E0602 self.stPluginAction.setObjectName("pipeAnalyticsStart") self.stPluginAction.setWhatsThis( "Option to start pipe network analysis") self.stPluginAction.setStatusTip(u"Méretező plugin indítása") # We run the widget when the action is triggered QObject.connect(self.stPluginAction, SIGNAL("triggered()"), self.startPlugin) # pylint: disable=E1101 # add toolbar button and menu item # self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u'HMV Méretezés', self.stPluginAction) def unload(self): self.iface.removePluginMenu(u'HMV Méretezés', self.stPluginAction) QObject.disconnect(self.stPluginAction, SIGNAL("triggered()"), self.startPlugin) # pylint: disable=E1101 def startPlugin(self): # We set up the network environment self.netEnv = NetworkEnvironment() # Instantiate the models required for view objects self.sizeListModel = SizeListModel(self.netEnv.sizes) self.elementErrTableModel = ElementErrorTableModel() # Instantiate the UI object self.dock = Ui_HmvWidget() self.dock.setupUi(self.dock) self.dock.sizeList.setModel(self.sizeListModel) self.dock.errElements_table.setModel(self.elementErrTableModel) # Analysis buttons are disabled by default self.dock.theAnalysis_btn.setEnabled(False) # We add the dock widget to the QGIS window self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock) self.setDefaultValues() self.bindConnections() def bindConnections(self): """Binds actions to GUI object signals""" # Analysis actions QObject.connect(self.dock.validateStart_btn, SIGNAL("clicked()"), self.startNetworkValidation) # pylint: disable=E1101 QObject.connect(self.dock.theAnalysis_btn, SIGNAL("clicked()"), self.startAllCalc) # pylint: disable=E1101 # Settings QObject.connect(self.dock.addSize_btn, SIGNAL("clicked()"), self.addSizeToList) # pylint: disable=E1101 QObject.connect(self.dock.removeSize_btn, SIGNAL("clicked()"), self.removeSizeFromList) # pylint: disable=E1101 QObject.connect(self.dock.saveSettings_btn, SIGNAL("clicked()"), self.saveSettings) # pylint: disable=E1101 QObject.connect(self.dock.resetSettings_btn, SIGNAL("clicked()"), self.setDefaultValues) # pylint: disable=E1101 QObject.connect(self.dock.circFlow_combo, SIGNAL("activated(int)"), self.refreshCircFlowDisplay) # pylint: disable=E1101 # Result windows QObject.connect(self.dock.showResults_btn, SIGNAL("clicked()"), self.openResultsWindow) # pylint: disable=E1101 QObject.connect( self.dock.showPressureResults_btn, SIGNAL("clicked()"), # pylint: disable=E1101 self.openPressureResultsWindow) QObject.connect(self.dock.showPipeFlowChart_btn, SIGNAL("clicked()"), self.openChartWindow) # pylint: disable=E1101 # Layers QObject.connect(self.dock.refreshLayers_btn, SIGNAL("clicked()"), self.populateLayerChoice) # pylint: disable=E1101 QObject.connect( self.dock.nodeLayerSelect_combo, SIGNAL("activated(QString)"), # pylint: disable=E1101 self.netEnv.setNodeLayerName) QObject.connect( self.dock.pipeLayerSelect_combo, SIGNAL("activated(QString)"), # pylint: disable=E1101 self.netEnv.setPipeLayerName) QObject.connect(self.dock.formatLayers_btn, SIGNAL("clicked()"), self.formatLayerChoice) QObject.connect(self.dock.createNewLayer_btn, SIGNAL('clicked()'), self.createNewLayer) def startAllCalc(self): self.startHeatlossCalc() self.startFlowCalc() self.startPipeDiaCalc() self.startPipeDragCalc() self.startPressureCalc() def openResultsWindow(self): """Opens a new window with the analysis results like heatloss and related, results window #1""" self.resultsWin = Ui_result_widget() self.resultsWin.setupUi(self.resultsWin) self.resultsModel = ResultsTableModel(self.netEnv.generateResults()) self.resultsWin.results_table.setModel(self.resultsModel) QObject.connect(self.resultsWin.closeWindow_btn, SIGNAL("clicked()"), self.resultsWin.close) # pylint: disable=E1101 self.resultsWin.show() # pylint: disable=E1101 def openPressureResultsWindow(self): """Opens a new windo with the analysis results like pressure loss, results window #2""" self.pressureResultsWin = Ui_result_widget() self.pressureResultsWin.setupUi(self.pressureResultsWin) self.pressureResultsModel = PressureTableModel( self.netEnv.generatePressureResults()) self.pressureResultsWin.results_table.setModel( self.pressureResultsModel) QObject.connect( self.pressureResultsWin.closeWindow_btn, SIGNAL("clicked()"), # pylint: disable=E1101 self.pressureResultsWin.close) # pylint: disable=E1101 self.pressureResultsWin.show() # pylint: disable=E1101 def openChartWindow(self): self.chartWin = Ui_pipeFlowChart_wdg() self.chartWin.setupUi(self.chartWin) chart = PipeFlowChartCanvas( flowData=self.netEnv.generateFlowGraphResults(), parent=self.chartWin) self.chartWin.chartTarget_lo.addWidget(chart) self.chartWin.show() # pylint: disable=E1101 def setDefaultValues(self): self.dock.density_txtField.setText(str(self.netEnv.density)) self.dock.specificHeat_txtField.setText(str(self.netEnv.specificHeat)) self.dock.deltaTheta_txtField.setText(str(self.netEnv.deltaTheta)) self.dock.pipeSpeedLimit_txtField.setText( str(self.netEnv.pipeSpeedLimit)) # New layer creation interface self.dock.layerWorkingDirectory_txtField.setText( self.iniConfig.get('hmv', 'workdir')) self.dock.newLayerDbFile_txtField.setReadOnly(False) # Working layer selection interface self.populateLayerChoice() def populateLayerChoice(self): # Populating layer choice combo self.dock.nodeLayerSelect_combo.clear() self.dock.nodeLayerSelect_combo.addItems( self.netEnv.collectLayers(qgis.core.QGis.WKBPoint)) self.netEnv.setNodeLayerName( self.dock.nodeLayerSelect_combo.currentText()) self.dock.pipeLayerSelect_combo.clear() self.dock.pipeLayerSelect_combo.addItems( self.netEnv.collectLayers(qgis.core.QGis.WKBLineString)) self.netEnv.setPipeLayerName( self.dock.pipeLayerSelect_combo.currentText()) def formatLayerChoice(self): hmv_symbol_manager.setupNodeLayer( self.dock.nodeLayerSelect_combo.currentText()) hmv_symbol_manager.setupPipeLayer( self.dock.pipeLayerSelect_combo.currentText()) self.iface.mapCanvas().refreshAllLayers() def saveSettings(self): self.netEnv.density = float(self.dock.density_txtField.text()) self.netEnv.specificHeat = float( self.dock.specificHeat_txtField.text()) self.netEnv.deltaTheta = float(self.dock.deltaTheta_txtField.text()) self.netEnv.pipeSpeedLimit = float( self.dock.pipeSpeedLimit_txtField.text()) def addSizeToList(self): value = self.dock.insertSize_txtField.text() self.sizeListModel.insertRows(value) def removeSizeFromList(self): selected = self.dock.sizeList.selectedIndexes() for selection in selected: self.sizeListModel.removeRows(selection) def startNetworkValidation(self): if self.netEnv.pipeLayerName != None and self.netEnv.nodeLayerName != None: self.netEnv.buildObjects() status = self.netEnv.verifyObjectConnections() self.dock.checkStatusValue_label.setText( QtTranslate('HmvWidget', self.netEnv.statusCodes[status['overallStatus']], None)) self.dock.numberOfElementsValue_label.setText( str(status['allElementsCount'])) self.dock.numberOfErrElementsValue_label.setText( str(status['errElementsCount'])) self.elementErrTableModel.removeRows() self.elementErrTableModel.insertRows(status['errElements']) # If network validation is OK enable analysis buttons if status['overallStatus'] == 2: self.dock.theAnalysis_btn.setEnabled(True) self.dock.verifyNotification_lbl.setVisible(False) else: pass def startHeatlossCalc(self): anaHeat = AnalyzeHeatLoss(self.netEnv) logging.info('STAGE 1 | Starting heatloss analysis.' \ 'Calculating network heatloss for the first nodes after taps first.') anaHeat.doAnalyze() logging.info( 'STAGE 2 | Analyze network heatlos on next nodes in network.') anaHeat.analyzeNextNodes() self.dock.totalHeatloss_label.setText('{:.1f}'.format( round(self.netEnv.totalNetworkHeatloss, 1))) self.dock.circFlow_label.setText('{:.1f}'.format( round(self.netEnv.pumpFlow, 1))) def startFlowCalc(self): anaFlow = AnalyzeFlowRate(self.netEnv) logging.info('STAGE 1 | Starting flow rate analysis.' \ 'Calculating network heatloss at the pump pipe first.') anaFlow.doAnalyze() logging.info('STAGE 2 | Analyze flow rate on next nodes in network.') anaFlow.analyzeNextNodes() def configureLogging(self): """Configures the logging env""" logging.basicConfig(filename=self.iniConfig.get("hmv", "logdir") + 'plugin.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s') def startPipeDiaCalc(self): calcDia = AnalyzePipeDiameter(self.netEnv) calcDia.doAnalyze() def refreshCircFlowDisplay(self): logging.info('Flow dimension changed.') if self.dock.circFlow_combo.currentText() == 'm3/sec': self.dock.circFlow_label.setText(str(self.netEnv.pumpFlow / 3.6e6)) elif self.dock.circFlow_combo.currentText() == 'dm3/h': self.dock.circFlow_label.setText(str(self.netEnv.pumpFlow)) def startPipeDragCalc(self): calcDrag = AnalyzePipeDrag(self.netEnv) calcDrag.doAnalyze() def startPressureCalc(self): calcPress = AnalyzePressure(self.netEnv) calcPress.doAnalyze() def disableAnalysis(self): self.dock.theAnalysis_btn.setEnabled(False) self.dock.verifyNotification_lbl.setVisible(True) def createNewLayer(self): """Create a new datasource and layer, add to registry if needed""" try: dsPath = datasource_manager.createLayer( self.dock.newLayerName_txtField.text(), self.dock.newLayerDbFile_txtField.text(), self.dock.layerWorkingDirectory_txtField.text(), self.dock.newLayerType_combo.currentText()) except OSError as err: # Working dir doesn't exist or datasource file exists mBox = QMessageBox() mBox.setText('Datasource error: {}'.format(err)) mBox.setIcon(QMessageBox.Critical) mBox.exec_() else: if self.dock.newLayerAddToRegistry_checkbox.isChecked() == True: uri = qgis.core.QgsDataSourceURI() uri.setDatabase(dsPath) schema = '' table = self.dock.newLayerName_txtField.text() geom_column = 'GEOMETRY' uri.setDataSource(schema, table, geom_column) display_name = self.dock.newLayerName_txtField.text() vlayer = qgis.core.QgsVectorLayer(uri.uri(), display_name, 'spatialite') qgis.core.QgsMapLayerRegistry.instance().addMapLayer(vlayer)
def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: # self.menu = QMenu( "&Task", self.iface.mainWindow().menuBar() ) action = self.iface.mainWindow().menuBar().actions() lastAction = action[-1] self.iface.addPluginToMenu( self.menu, lastAction) self.actions.append(lastAction) return action
class Plugin(object): """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menu bar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Register all the impact functions register_impact_functions() # Save reference to the QGIS interface self.iface = iface self.dock_widget = None self.action_import_dialog = None self.action_save_scenario = None self.action_batch_runner = None self.action_shake_converter = None self.action_minimum_needs = None self.action_minimum_needs_config = None self.key_action = None self.action_options = None self.action_keywords_wizard = None self.action_function_centric_wizard = None self.action_extent_selector = None self.translator = None self.toolbar = None self.wizard = None self.actions = [] # list of all QActions we create for InaSAFE self.action_dock = None self.action_toggle_rubberbands = None self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) # noinspection PyArgumentList def change_i18n(self, new_locale): """Change internationalisation for the plugin. Override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param new_locale: The new locale i.e. 'id', 'af', etc. :type new_locale: str :raises: TranslationLoadException """ os.environ['INASAFE_LANG'] = str(new_locale) LOGGER.debug('%s %s %s' % ( new_locale, QLocale.system().name(), os.environ['INASAFE_LANG'])) root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) translation_path = os.path.join( root, 'safe_qgis', 'i18n', 'inasafe_' + str(new_locale) + '.qm') if os.path.exists(translation_path): self.translator = QTranslator() result = self.translator.load(translation_path) if not result: message = 'Failed to load translation for %s' % new_locale raise TranslationLoadError(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( translation_path, os.path.exists(translation_path))) # 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('Plugin', message) def add_action(self, action, add_to_toolbar=True): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) def _create_dock_toggle_action(self): """Create action for plugin dockable window (show/hide).""" # pylint: disable=W0201 icon = resources_path('img', 'icons', 'icon.svg') self.action_dock = QAction( QIcon(icon), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.action_dock.setObjectName('InaSAFEDockToggle') self.action_dock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setCheckable(True) self.action_dock.setChecked(True) self.action_dock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.action_dock) # -------------------------------------- # Create action for keywords creation wizard # ------------------------------------- def _create_keywords_wizard_action(self): """Create action for keywords creation wizard.""" icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('Keywords Creation Wizard'), self.iface.mainWindow()) self.action_keywords_wizard.setStatusTip(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setWhatsThis(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setEnabled(False) self.action_keywords_wizard.triggered.connect( self.show_keywords_wizard) self.add_action(self.action_keywords_wizard) def _create_analysis_wizard_action(self): """Create action for IF-centric wizard.""" icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('Impact Function Centric Wizard'), self.iface.mainWindow()) self.action_function_centric_wizard.setStatusTip(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setWhatsThis(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setEnabled(True) self.action_function_centric_wizard.triggered.connect( self.show_function_centric_wizard) self.add_action(self.action_function_centric_wizard) def _create_options_dialog_action(self): """Create action for options dialog.""" icon = resources_path('img', 'icons', 'configure-inasafe.svg') self.action_options = QAction( QIcon(icon), self.tr('Options'), self.iface.mainWindow()) self.action_options.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.action_options.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) self.action_options.triggered.connect(self.show_options) self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_action(self): """Create action for minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.action_minimum_needs = QAction( QIcon(icon), self.tr('Minimum Needs Calculator'), self.iface.mainWindow()) self.action_minimum_needs.setStatusTip(self.tr( 'Open InaSAFE minimum needs calculator')) self.action_minimum_needs.setWhatsThis(self.tr( 'Open InaSAFE minimum needs calculator')) self.action_minimum_needs.triggered.connect(self.show_minimum_needs) self.add_action( self.action_minimum_needs, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_options_action(self): """Create action for global minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg') self.action_minimum_needs_config = QAction( QIcon(icon), self.tr('Minimum Needs Configuration'), self.iface.mainWindow()) self.action_minimum_needs_config.setStatusTip(self.tr( 'Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.setWhatsThis(self.tr( 'Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.triggered.connect( self.show_minimum_needs_configuration) self.add_action( self.action_minimum_needs_config, add_to_toolbar=self.full_toolbar) def _create_shakemap_converter_action(self): """Create action for converter dialog.""" icon = resources_path('img', 'icons', 'show-converter-tool.svg') self.action_shake_converter = QAction( QIcon(icon), self.tr('Shakemap Converter'), self.iface.mainWindow()) self.action_shake_converter.setStatusTip(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.setWhatsThis(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.triggered.connect( self.show_shakemap_importer) self.add_action( self.action_shake_converter, add_to_toolbar=self.full_toolbar) def _create_batch_runner_action(self): """Create action for batch runner dialog.""" icon = resources_path('img', 'icons', 'show-batch-runner.svg') self.action_batch_runner = QAction( QIcon(icon), self.tr('Batch Runner'), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr( 'Open Batch Runner')) self.action_batch_runner.setWhatsThis(self.tr( 'Open Batch Runner')) self.action_batch_runner.triggered.connect(self.show_batch_runner) self.add_action( self.action_batch_runner, add_to_toolbar=self.full_toolbar) def _create_save_scenario_action(self): """Create action for save scenario dialog.""" icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction( QIcon(icon), self.tr('Save Current Scenario'), self.iface.mainWindow()) message = self.tr('Save current scenario to text file') self.action_save_scenario.setStatusTip(message) self.action_save_scenario.setWhatsThis(message) # noinspection PyUnresolvedReferences self.action_save_scenario.triggered.connect(self.save_scenario) self.add_action( self.action_save_scenario, add_to_toolbar=self.full_toolbar) def _create_osm_downloader_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'show-osm-download.svg') self.action_import_dialog = QAction( QIcon(icon), self.tr('OpenStreetMap Downloader'), self.iface.mainWindow()) self.action_import_dialog.setStatusTip(self.tr( 'OpenStreetMap Downloader')) self.action_import_dialog.setWhatsThis(self.tr( 'OpenStreetMap Downloader')) self.action_import_dialog.triggered.connect(self.show_osm_downloader) self.add_action(self.action_import_dialog) def _create_add_osm_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-osm-tiles-layer.svg') self.action_add_osm_layer = QAction( QIcon(icon), self.tr('Add OpenStreetMap Tile Layer'), self.iface.mainWindow()) self.action_add_osm_layer.setStatusTip(self.tr( 'Add OpenStreetMap Tile Layer')) self.action_add_osm_layer.setWhatsThis(self.tr( 'Use this to add an OSM layer to your map. ' 'It needs internet access to function.')) self.action_add_osm_layer.triggered.connect(self.add_osm_layer) self.add_action(self.action_add_osm_layer) def _create_add_petajakarta_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-petajakarta-layer.svg') self.action_add_petajakarta_layer = QAction( QIcon(icon), self.tr('Add PetaJakarta Flood Layer'), self.iface.mainWindow()) self.action_add_petajakarta_layer.setStatusTip(self.tr( 'Add PetaJakarta Flood Layer')) self.action_add_petajakarta_layer.setWhatsThis(self.tr( 'Use this to add a PetaJakarta layer to your map. ' 'It needs internet access to function.')) self.action_add_petajakarta_layer.triggered.connect( self.add_petajakarta_layer) self.add_action( self.action_add_petajakarta_layer, add_to_toolbar=False) def _create_raster_reclassify_layer_action(self): """Create action for Raster Reclassification to vector.""" # Disabled for 3.5 final_release = release_status() == 'final' settings = QSettings() self.developer_mode = settings.value( 'inasafe/developer_mode', False, type=bool) if not final_release and self.developer_mode: icon = resources_path( 'img', 'icons', 'raster-reclassify-layer.svg') self.action_raster_reclassify_layer = QAction( QIcon(icon), self.tr('Reclassify Raster to Vector Layer'), self.iface.mainWindow()) self.action_raster_reclassify_layer.setStatusTip(self.tr( 'Reclassify Raster to Vector Layer')) self.action_raster_reclassify_layer.setWhatsThis(self.tr( 'Use this to reclassify Raster Layer into Vector Layer ' 'with defined thresholds as classifier.')) self.action_raster_reclassify_layer.triggered.connect( self.raster_reclassify) self.add_action( self.action_raster_reclassify_layer, add_to_toolbar=False) def _create_rubber_bands_action(self): """Create action for toggling rubber bands.""" icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg') self.action_toggle_rubberbands = QAction( QIcon(icon), self.tr('Toggle Scenario Outlines'), self.iface.mainWindow()) message = self.tr('Toggle rubber bands showing scenario extents.') self.action_toggle_rubberbands.setStatusTip(message) self.action_toggle_rubberbands.setWhatsThis(message) # Set initial state self.action_toggle_rubberbands.setCheckable(True) settings = QSettings() flag = bool(settings.value( 'inasafe/showRubberBands', False, type=bool)) self.action_toggle_rubberbands.setChecked(flag) # noinspection PyUnresolvedReferences self.action_toggle_rubberbands.triggered.connect( self.dock_widget.toggle_rubber_bands) self.add_action(self.action_toggle_rubberbands) def _create_analysis_extent_action(self): """Create action for analysis extent dialog.""" icon = resources_path('img', 'icons', 'set-extents-tool.svg') self.action_extent_selector = QAction( QIcon(icon), self.tr('Set Analysis Area'), self.iface.mainWindow()) self.action_extent_selector.setStatusTip(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.setWhatsThis(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.triggered.connect( self.show_extent_selector) self.add_action(self.action_extent_selector) def _create_test_layers_action(self): """Create action for adding layers (developer mode, non final only).""" final_release = release_status() == 'final' settings = QSettings() self.developer_mode = settings.value( 'inasafe/developer_mode', False, type=bool) if not final_release and self.developer_mode: icon = resources_path('img', 'icons', 'add-test-layers.svg') self.action_add_layers = QAction( QIcon(icon), self.tr('Add Test Layers'), self.iface.mainWindow()) self.action_add_layers.setStatusTip(self.tr( 'Add test layers')) self.action_add_layers.setWhatsThis(self.tr( 'Add test layers')) self.action_add_layers.triggered.connect( self.add_test_layers) self.add_action(self.action_add_layers) def _create_run_test_action(self): """Create action for running tests (developer mode, non final only).""" final_release = release_status() == 'final' settings = QSettings() self.developer_mode = settings.value( 'inasafe/developer_mode', False, type=bool) if not final_release and self.developer_mode: default_package = unicode(settings.value( 'inasafe/testPackage', 'safe', type=str)) msg = self.tr('Run tests in %s' % default_package) self.test_button = QToolButton() self.test_button.setMenu(QMenu()) self.test_button.setPopupMode(QToolButton.MenuButtonPopup) icon = resources_path('img', 'icons', 'run-tests.svg') self.action_run_tests = QAction( QIcon(icon), msg, self.iface.mainWindow()) self.action_run_tests.setStatusTip(msg) self.action_run_tests.setWhatsThis(msg) self.action_run_tests.triggered.connect( self.run_tests) self.test_button.menu().addAction(self.action_run_tests) self.test_button.setDefaultAction(self.action_run_tests) self.action_select_package = QAction( QIcon(icon), self.tr('Select package'), self.iface.mainWindow()) self.action_select_package.setStatusTip(self.tr( 'Select Test Package')) self.action_select_package.setWhatsThis(self.tr( 'Select Test Package')) self.action_select_package.triggered.connect( self.select_test_package) self.test_button.menu().addAction(self.action_select_package) self.toolbar.addWidget(self.test_button) self.add_action(self.action_run_tests, add_to_toolbar=False) self.add_action(self.action_select_package, add_to_toolbar=False) def _create_dock(self): """Create dockwidget and tabify it with the legend.""" # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = Dock(self.iface) self.dock_widget.setObjectName('InaSAFE-Dock') self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend') if legend_tab: self.iface.mainWindow().tabifyDockWidget( legend_tab, self.dock_widget) self.dock_widget.raise_() def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') self.dock_widget = None # Now create the actual dock self._create_dock() # And all the menu actions # Configuration Group self._create_dock_toggle_action() self._create_options_dialog_action() self._create_minimum_needs_options_action() self._create_analysis_extent_action() self._create_rubber_bands_action() self._add_spacer_to_menu() self._create_keywords_wizard_action() self._create_analysis_wizard_action() self._add_spacer_to_menu() self._create_osm_downloader_action() self._create_add_osm_layer_action() self._create_add_petajakarta_layer_action() self._create_raster_reclassify_layer_action() self._create_shakemap_converter_action() self._create_minimum_needs_action() self._create_test_layers_action() self._create_run_test_action() self._add_spacer_to_menu() self._create_batch_runner_action() self._create_save_scenario_action() # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action) # Also deal with the fact that on start of QGIS dock may already be # hidden. self.action_dock.setChecked(self.dock_widget.isVisible()) def _add_spacer_to_menu(self): """Create a spacer to the menu to separate action groups.""" separator = QAction(self.iface.mainWindow()) separator.setSeparator(True) self.iface.addPluginToMenu(self.tr('InaSAFE'), separator) def clear_modules(self): """Unload inasafe functions and try to return QGIS to before InaSAFE. .. todo:: I think this function can be removed. TS. """ # next lets force remove any inasafe related modules modules = [] for module in sys.modules: if 'inasafe' in module: # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module.split('.') path = '' for myToken in tokens: path += os.path.sep + myToken parent = os.path.abspath(os.path.join( __file__, os.path.pardir, os.path.pardir)) full_path = os.path.join(parent, path + '.py') if os.path.exists(os.path.abspath(full_path)): LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) for module in sys.modules: if 'inasafe' in module: print module # Lets also clean up all the path additions that were made package_path = os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon if self.wizard: self.wizard.deleteLater() for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.mainWindow().removeDockWidget(self.dock_widget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dock_widget.setVisible(False) self.dock_widget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) def toggle_inasafe_action(self, checked): """Check or un-check the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.action_dock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dock_widget.isVisible(): self.dock_widget.setVisible(False) else: self.dock_widget.setVisible(True) self.dock_widget.raise_() def add_test_layers(self): """Add standard test layers.""" from safe.test.utilities import load_standard_layers load_standard_layers() rect = QgsRectangle(106.806, -6.195, 106.837, -6.167) self.iface.mapCanvas().setExtent(rect) def select_test_package(self): """Select the test package.""" settings = QSettings() default_package = 'safe' user_package = unicode(settings.value( 'inasafe/testPackage', default_package, type=str)) test_package, _ = QInputDialog.getText( self.iface.mainWindow(), self.tr('Select the python test package'), self.tr('Select the python test package'), QLineEdit.Normal, user_package) if test_package == '': test_package = default_package settings.setValue('inasafe/testPackage', test_package) msg = self.tr('Run tests in %s' % test_package) self.action_run_tests.setWhatsThis(msg) self.action_run_tests.setText(msg) def run_tests(self): """Run unit tests in the python console.""" from PyQt4.QtGui import QDockWidget main_window = self.iface.mainWindow() action = main_window.findChild(QAction, 'mActionShowPythonDialog') action.trigger() settings = QSettings() package = unicode(settings.value( 'inasafe/testPackage', 'safe', type=str)) for child in main_window.findChildren(QDockWidget, 'PythonConsole'): if child.objectName() == 'PythonConsole': child.show() for widget in child.children(): if 'PythonConsoleWidget' in str(widget.__class__): # print "Console widget found" shell = widget.shell shell.runCommand( 'from inasafe.test_suite import test_package') shell.runCommand('test_package(\'%s\')' % package) break def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, self.iface.mainWindow(), extent=self.dock_widget.extent.user_extent, crs=self.dock_widget.extent.user_extent_crs) widget.clear_extent.connect( self.dock_widget.extent.clear_user_analysis_extent) widget.extent_defined.connect( self.dock_widget.define_user_analysis_extent) # This ensures that run button state is updated on dialog close widget.extent_selector_closed.connect( self.dock_widget.show_next_analysis_extent) # Needs to be non modal to support hide -> interact with map -> show widget.show() # non modal def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.exec_() def show_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog( parent=self.iface.mainWindow(), dock=self.dock_widget) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog dialog = OptionsDialog( self.iface, self.dock_widget, self.iface.mainWindow()) dialog.exec_() # modal def show_keywords_wizard(self): """Show the keywords creation wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog if self.iface.activeLayer() is None: return # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since the IFCW is non modal if not self.wizard: self.wizard = WizardDialog( self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_keywords_creation_mode() self.wizard.exec_() # modal def show_function_centric_wizard(self): """Show the function centric wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since it is non modal if not self.wizard: self.wizard = WizardDialog( self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_function_centric_mode() # non-modal in order to hide for selecting user extent self.wizard.show() def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) dialog = ShakemapConverterDialog(self.iface.mainWindow()) dialog.exec_() # modal def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def add_osm_layer(self): """Add OSM tile layer to the map. This uses a gdal wrapper around the OSM tile service - see the WorldOSM.gdal file for how it is constructed. """ path = resources_path('osm', 'WorldOSM.gdal') layer = QgsRasterLayer(path, self.tr('OpenStreetMap')) registry = QgsMapLayerRegistry.instance() # For older versions we just add directly to the top of legend if QGis.QGIS_VERSION_INT < 20400: # True flag adds layer directly to legend registry.addMapLayer(layer, True) return # Otherwise try to add it as the last layer in the list # False flag prevents layer being added to legend registry.addMapLayer(layer, False) root = QgsProject.instance().layerTreeRoot() index = len(root.findLayers()) + 1 # LOGGER.info('Inserting layer %s at position %s' % ( # layer.source(), index)) root.insertLayer(index, layer) QgsMapLayerRegistry.instance().addMapLayer(layer) def add_petajakarta_layer(self): """Add petajakarta layer to the map. This uses the PetaJakarta API to fetch the latest floods in JK. See https://petajakarta.org/banjir/en/data/api/#aggregates """ from safe.gui.tools.peta_jakarta_dialog import PetaJakartaDialog dialog = PetaJakartaDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def raster_reclassify(self): """Show dialog for Raster Reclassification. This will convert Raster Layer to Vector Layer """ from safe.gui.tools.raster_reclassify_dialog import \ RasterReclassifyDialog dialog = RasterReclassifyDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def show_batch_runner(self): """Show the batch runner dialog.""" from safe.gui.tools.batch.batch_dialog import BatchDialog dialog = BatchDialog( parent=self.iface.mainWindow(), iface=self.iface, dock=self.dock_widget) dialog.exec_() # modal def save_scenario(self): """Save current scenario to text file""" from safe.gui.tools.save_scenario import SaveScenarioDialog dialog = SaveScenarioDialog( iface=self.iface, dock=self.dock_widget) dialog.save_scenario() def _disable_keyword_tools(self): """Internal helper to disable the keyword and wizard actions.""" self.action_keywords_wizard.setEnabled(False) def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if not layer: self._disable_keyword_tools() return if not hasattr(layer, 'providerType'): self._disable_keyword_tools() return if layer.providerType() == 'wms': self._disable_keyword_tools() return if is_raster_layer(layer) and layer.bandCount() > 1: self._disable_keyword_tools() return self.action_keywords_wizard.setEnabled(True) def shortcut_f7(self): """Executed when user press F7 - will show the shakemap importer.""" self.show_shakemap_importer()
def add_action(self, icon_path, text, callback, store_val, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None, dialog=mainPlugDialog()): # type: (object, object, object, object, object, object, object,object, object, object, object) -> object """Add a toolbar icon to the toolbar. :param store_val: This value is the position to store the Dialog within the dialog list, Note that this position can and will interfere with standard operation if it is stored in an incorrect position at this time :type store_val: int :param dialog: The dialog you wish to Display to users :type dialog: function :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 # noinspection PyTypeChecker self.DialogStore[store_val] = dialog 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 addNewAction(self, iconPath, text, callback=None, enabled=True, checkable=False, addToMenu=True, addToToolbar=True, tip=None, whatsThis=None, parent=None): """Add a toolbar icon to the toolbar. :param iconPath: 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 iconPath: 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: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled: bool :param checkable: A flag indicating if the action should be checkable by default. Defaults to False. :type chenckable: bool :param addToMenu: Flag indicating whether the action should also be added to the plugin menu. Defaults to True. :type addToMenu: bool :param addToToolbar: Flag indicating whether the action should also be added to the plugin toolbar. Defaults to True. :type addToToolbar: bool :param tip: Optional text to show in a popup when mouse pointer hovers over the action. :type tip: str :param whatsThis: Optional text to show in the status bar when the mouse pointer hovers over the action. :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :returns: The action that was created. Note that the action is also added to self._actions list. :rtype: QAction """ if parent is None: parent = self.iface.mainWindow() action = QAction(QIcon(iconPath), text, parent) if tip is not None: action.setStatusTip(tip) if whatsThis is not None: action.setWhatsThis(whatsThis) if callback is not None: action.triggered.connect(callback) action.setEnabled(enabled) action.setCheckable(checkable) self.addAction(action, addToMenu, addToToolbar) return action
def addNewAction( self, iconPath, text, callback=None, enabled=True, checkable=False, addToMenu=True, addToToolbar=True, tip=None, whatsThis=None, parent=None): """Add a toolbar icon to the toolbar. :param iconPath: 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 iconPath: 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: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled: bool :param checkable: A flag indicating if the action should be checkable by default. Defaults to False. :type chenckable: bool :param addToMenu: Flag indicating whether the action should also be added to the plugin menu. Defaults to True. :type addToMenu: bool :param addToToolbar: Flag indicating whether the action should also be added to the plugin toolbar. Defaults to True. :type addToToolbar: bool :param tip: Optional text to show in a popup when mouse pointer hovers over the action. :type tip: str :param whatsThis: Optional text to show in the status bar when the mouse pointer hovers over the action. :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :returns: The action that was created. Note that the action is also added to self._actions list. :rtype: QAction """ if parent is None: parent = self.iface.mainWindow() action = QAction(QIcon(iconPath), text, parent) if tip is not None: action.setStatusTip(tip) if whatsThis is not None: action.setWhatsThis(whatsThis) if callback is not None: action.triggered.connect(callback) action.setEnabled(enabled) action.setCheckable(checkable) self.addAction(action, addToMenu, addToToolbar) return action
class Photo2ShapePlugin: def __init__(self, iface): self.iface = iface self.canvas = self.iface.mapCanvas() self.qgsVersion = unicode(QGis.QGIS_VERSION_INT) overrideLocale = QSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QSettings().value('locale/userLocale', '') qmPath = '{}/i18n/photo2shape_{}.qm'.format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(translationPath) QCoreApplication.installTranslator(self.translator) def initGui(self): if int(self.qgsVersion) < 20000: qgisVersion = '{}.{}.{}'.format(self.qgsVersion[0], self.qgsVersion[2], self.qgsVersion[3]) QMessageBox.warning( self.iface.mainWindow(), 'Photo2Shape', self.tr('QGIS {} detected.\nThis version of Photo2Shape ' 'requires at least QGIS 2.0. Plugin will not be ' 'enabled.'.format(qgisVersion))) return None self.actionRun = QAction(self.tr('Photo2Shape'), self.iface.mainWindow()) self.actionRun.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'photo2shape.png'))) self.actionRun.setWhatsThis( self.tr('Create a point shapefile from geotagged images')) self.actionRun.setObjectName('runPhoto2Shape') self.actionAbout = QAction(self.tr('About Photo2Shape...'), self.iface.mainWindow()) self.actionAbout.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'photo2shape.png'))) self.actionAbout.setWhatsThis(self.tr('About Photo2Shape')) self.actionRun.setObjectName('aboutPhoto2Shape') self.iface.addPluginToVectorMenu(self.tr('Photo2Shape'), self.actionRun) self.iface.addPluginToVectorMenu(self.tr('Photo2Shape'), self.actionAbout) self.iface.addVectorToolBarIcon(self.actionRun) self.actionRun.triggered.connect(self.run) self.actionAbout.triggered.connect(self.about) def unload(self): self.iface.removePluginVectorMenu(self.tr('Photo2Shape'), self.actionRun) self.iface.removePluginVectorMenu(self.tr('Photo2Shape'), self.actionAbout) self.iface.removeVectorToolBarIcon(self.actionRun) def run(self): dlg = Photo2ShapeDialog(self.iface) dlg.show() dlg.exec_() def about(self): d = AboutDialog() d.exec_() def tr(self, text): return QCoreApplication.translate('Photo2Shape', text)
def add_action( self, icon_name, 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_name: Name of the icon for this action. Its a normal file ui/resources. :type icon_name: 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 = GeogigPackageReaderDialog() icon = QIcon(os.path.join(os.path.dirname(__file__), "ui", "resources", os.path.basename(icon_name))) 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.addPluginToDatabaseMenu( self.menu, action) self.actions.append(action) return action
class OSMEditorRemoteControlPlugin: def __init__(self, iface): self.iface = iface self.action = None # noinspection PyPep8Naming def initGui(self): self.action = QAction( QIcon(join(dirname(__file__), 'icons', 'josm_icon.svg')), 'OSM Editor Remote Control', self.iface.mainWindow()) self.action.setEnabled(False) help = 'Send remote control command to OSM editor to load data at ' \ 'current map view.' self.action.setWhatsThis(help) self.action.setStatusTip(help) self.action.triggered.connect(self.run) self.iface.mapCanvas().layersChanged.connect(self.change_status) self.iface.mapCanvas().extentsChanged.connect(self.change_status) self.iface.addToolBarIcon(self.action) def unload(self): self.iface.removeToolBarIcon(self.action) def get_lon_lat_extent(self): map_canvas = self.iface.mapCanvas() extent = map_canvas.mapSettings().extent() if map_canvas.hasCrsTransformEnabled(): crs_map = map_canvas.mapSettings().destinationCrs() else: crs_map = map_canvas.currentLayer().crs() if crs_map.authid() != u'EPSG:4326': crs_4326 = QgsCoordinateReferenceSystem() crs_4326.createFromSrid(4326) return QgsCoordinateTransform(crs_map, crs_4326).transform(extent) return extent def change_status(self): if not self.iface.mapCanvas().currentLayer(): self.action.setEnabled(False) else: extent = self.get_lon_lat_extent() self.action.setEnabled( extent.width() * extent.height() < MAX_DOWNLOAD_AREA_DEG) def run(self): extent = self.get_lon_lat_extent() url = 'http://localhost:8111/load_and_zoom?' query_string = 'left=%f&right=%f&top=%f&bottom=%f' % ( extent.xMinimum(), extent.xMaximum(), extent.yMaximum(), extent.yMinimum()) url += query_string try: f = urllib.urlopen(url, proxies={}) result = f.read() f.close() if result.strip().upper() != 'OK': self.report_error('OSM reported: %s' % result) except IOError: self.report_error( 'Could not connect to the OSM editor. Is the OSM editor ' 'running?') def report_error(self, error_message): self.iface.messageBar().pushCritical( 'OSM Editor Remote Control Plugin', error_message)
class WorkspaceWidget(RWidget): class TreeView(QTreeView): def __init__(self, parent): QTreeView.__init__(self, parent) self.setAlternatingRowColors(True) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) self.connect(self, SIGNAL("expanded(QModelIndex)"), self.expanded) def expanded(self, index): self.model().updateEntry(index) def mousePressEvent(self, event): item = self.childAt(event.globalPos()) if not item and event.button() == Qt.LeftButton: self.clearSelection() QTreeView.mousePressEvent(self, event) def selectionChanged(self, new, old): self.emit(SIGNAL("itemSelectionChanged()")) QTreeView.selectionChanged(self, new, old) def __init__(self, parent=None): RWidget.__init__(self, parent) self.workspaceTree = self.TreeView(self) self.workspaceTree.setSortingEnabled(True) self.proxyModel = SortFilterProxyModel() self.proxyModel.setDynamicSortFilter(True) # self.proxyModel.setFilterKeyColumn(1) self.model = TreeModel() self.proxyModel.setSourceModel(self.model) # self.workspaceTree.setModel(self.model) self.workspaceTree.setModel(self.proxyModel) self.actions = [] self.refreshAction = QAction("Re&fresh variables", self) self.refreshAction.setToolTip("Refresh environment browser") self.refreshAction.setWhatsThis("Refresh environment browser") self.refreshAction.setIcon(QIcon(":view-refresh")) self.refreshAction.setEnabled(True) self.actions.append(self.refreshAction) self.loadAction = QAction("&Load data", self) self.loadAction.setToolTip("Load R variable(s) from file") self.loadAction.setWhatsThis("Load R variable(s) from file") self.loadAction.setIcon(QIcon(":custom-open-data")) self.loadAction.setEnabled(True) self.actions.append(self.loadAction) self.exportAction = QAction("&Export to file", self) self.exportAction.setToolTip("Export data to file") self.exportAction.setWhatsThis("Export data to file") self.exportAction.setIcon(QIcon(":custom-document-export")) self.exportAction.setEnabled(False) self.actions.append(self.exportAction) self.saveAction = QAction("&Save variable", self) self.saveAction.setToolTip("Save R variable to file") self.saveAction.setWhatsThis("Save R variable to file") self.saveAction.setIcon(QIcon(":custom-save-data")) self.saveAction.setEnabled(False) self.actions.append(self.saveAction) self.methodAction = QAction("&Print available methods", self) self.methodAction.setToolTip("Print available methods for object class") self.methodAction.setWhatsThis("Print available methods for object class") self.methodAction.setIcon(QIcon(":document-properties")) self.methodAction.setEnabled(False) self.actions.append(self.methodAction) self.attributeAction = QAction("Print object &attributes", self) self.attributeAction.setToolTip("Print available attributes for object class") self.attributeAction.setWhatsThis("Print available attributes for object class") self.attributeAction.setIcon(QIcon(":custom-tag")) self.attributeAction.setEnabled(False) self.actions.append(self.attributeAction) self.summaryAction = QAction("Print object Su&mmary", self) self.summaryAction.setToolTip("Print summary of object") self.summaryAction.setWhatsThis("Print summary of object") self.summaryAction.setIcon(QIcon(":custom-summary")) self.summaryAction.setEnabled(False) self.actions.append(self.summaryAction) self.plotAction = QAction("&Quick plot", self) self.plotAction.setToolTip("Create minimal plot for visualisation") self.plotAction.setWhatsThis("Create minimal plot for visualisation") self.plotAction.setIcon(QIcon(":gnome-fs-bookmark-missing")) self.plotAction.setEnabled(False) self.actions.append(self.plotAction) self.rmAction = QAction("&Remove", self) self.rmAction.setToolTip("Remove selected variable") self.rmAction.setWhatsThis("Removed selected variable") self.rmAction.setIcon(QIcon(":edit-delete")) self.rmAction.setEnabled(False) self.actions.append(self.rmAction) vbox = QVBoxLayout(self) vbox.addWidget(self.workspaceTree) self.variables = dict() self.connect(self.plotAction, SIGNAL("triggered()"), self.plotVariable) self.connect(self.summaryAction, SIGNAL("triggered()"), self.summariseVariable) self.connect(self.rmAction, SIGNAL("triggered()"), self.removeVariable) self.connect(self.exportAction, SIGNAL("triggered()"), self.exportVariable) self.connect(self.saveAction, SIGNAL("triggered()"), self.saveVariable) self.connect(self.loadAction, SIGNAL("triggered()"), self.loadRVariable) self.connect(self.methodAction, SIGNAL("triggered()"), self.printMethods) self.connect(self.refreshAction, SIGNAL("triggered()"), self.updateEnvironment) self.connect(self.attributeAction, SIGNAL("triggered()"), self.printAttributes) self.connect(self.workspaceTree, SIGNAL("itemSelectionChanged()"), self.selectionChanged) self.updateEnvironment() def mousePressEvent(self, event): item = self.workspaceTree.indexAt(event.globalPos()) if not item and event.button() == Qt.LeftButton: self.workspaceTree.clearSelection() RWidget.mousePressEvent(self, event) def contextMenuEvent(self, event): menu = QMenu(self) menu.addAction(self.refreshAction) menu.addSeparator() for action in self.actions[1:-1]: menu.addAction(action) menu.addSeparator() menu.addAction(self.rmAction) menu.exec_(event.globalPos()) def selectionChanged(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: for action in self.actions[2:]: action.setEnabled(False) else: for action in self.actions[2:]: action.setEnabled(True) def printMethods(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False itemType = self.workspaceTree.model().getItem(items[0]).data(1) self.runCommand("methods(class='%s')" % (itemType,)) def printAttributes(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False tree = self.workspaceTree.model().parentTree(items[0]) self.runCommand('names(attributes(%s))' % tree) def summariseVariable(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False tree = self.workspaceTree.model().parentTree(items[0]) self.runCommand('summary(%s)' % tree) def plotVariable(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False index = items[0] tree = self.workspaceTree.model().parentTree(index) self.runCommand('plot(%s)' % tree) def removeVariable(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False item = items[0] tree = self.workspaceTree.model().parentTree(item) command = "rm(%s)" % tree if not item.parent() == QModelIndex(): command = "%s <- NULL" % tree waiter = SignalWaiter(self.parent, SIGNAL("errorOutput()")) self.runCommand(command) if not waiter.wait(50): self.workspaceTree.model().removeRows(item.row(),1, item.parent()) def exportVariable(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False tree = self.workspaceTree.model().parentTree(items[0]) fd = QFileDialog(self.parent, "Save data to file", str(robjects.r.getwd()), "Comma separated (*.csv);;Text file (*.txt);;All files (*.*)") fd.setAcceptMode(QFileDialog.AcceptSave) if not fd.exec_() == QDialog.Accepted: return False files = fd.selectedFiles() selectedFile = files.first() if selectedFile.length() == 0: return False suffix = QString(fd.selectedNameFilter()) index1 = suffix.lastIndexOf("(")+2 index2 = suffix.lastIndexOf(")") suffix = suffix.mid(index1, index2-index1) if not selectedFile.endsWith(suffix): selectedFile.append(suffix) command = QString('write.table(%s, file = "%s",' % (tree, selectedFile)) command.append(QString('append = FALSE, quote = TRUE, sep = ",", eol = "\\n", na = "NA"')) command.append(QString(', dec = ".", row.names = FALSE, col.names = TRUE, qmethod = "escape")')) self.runCommand(command) def saveVariable(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False item = self.workspaceTree.model().getItem(items[0]) name = item.data(0) parent = item.parent() names = [name] while not parent is None: names.append(QString(parent.data(0))) parent = parent.parent() if len(names) > 1: names.pop(-1) name = names[-1] fd = QFileDialog(self.parent, "Save data to file", os.path.join(str(robjects.r.getwd()[0]), unicode(name)+".Rdata"), "R data file (*.Rdata)") fd.setAcceptMode(QFileDialog.AcceptSave) if not fd.exec_() == QDialog.Accepted: return False files = fd.selectedFiles() selectedFile = files.first() if selectedFile.length() == 0: return False suffix = QString(fd.selectedNameFilter()) index1 = suffix.lastIndexOf("(")+2 index2 = suffix.lastIndexOf(")") suffix = suffix.mid(index1, index2-index1) if not selectedFile.endsWith(suffix): selectedFile.append(suffix) commands = QString('save(%s, file="%s")' % (name,selectedFile)) self.runCommand(commands) def loadRVariable(self): fd = QFileDialog(self.parent, "Load R variable(s) from file", str(robjects.r.getwd()[0]), "R data (*.Rdata);;All files (*.*)") fd.setAcceptMode(QFileDialog.AcceptOpen) fd.setFileMode(QFileDialog.ExistingFile) if fd.exec_() == QDialog.Rejected: return False files = fd.selectedFiles() selectedFile = files.first() if selectedFile.length() == 0: return False self.runCommand(QString('load("%s")' % (selectedFile))) self.updateEnvironment() def runCommand(self, command): if not command == "": self.emitCommands(command) def updateEnvironment(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.model = TreeModel() self.proxyModel.setSourceModel(self.model) # self.workspaceTree.setModel(model) QApplication.restoreOverrideCursor() return True
class TemporalSpectralProfilePlugin: POINT_SELECTION = 0 SELECTED_POLYGON = 1 def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.wdg = None self.pointTool = None def initGui(self): # create action self.action = QAction(QIcon(":/plugins/temporalprofiletool/icons/temporalProfileIcon.png"), "Temporal/Spectral Profile", self.iface.mainWindow()) self.action.setWhatsThis("Plots temporal/spectral profiles") QObject.connect(self.action, SIGNAL("triggered()"), self.run) self.aboutAction = QAction("About", self.iface.mainWindow()) QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about) # add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu("&Profile Tool", self.action) self.iface.addPluginToMenu("&Profile Tool", self.aboutAction) #Init class variables self.pointTool = ProfiletoolMapTool(self.iface.mapCanvas(),self.action) #the mouselistener self.dockOpened = False #remember for not reopening dock if there's already one opened self.pointstoDraw = None #Polyline in mapcanvas CRS analysed self.dblclktemp = None #enable disctinction between leftclick and doubleclick self.mdl = None #the model whitch in are saved layers analysed caracteristics self.selectionmethod = 0 #The selection method defined in option self.saveTool = self.canvas.mapTool() #Save the standard mapttool for restoring it at the end self.plotlibrary = None #The plotting library to use self.pointSelectionInstructions = "Click on a raster for temporal/spectral profile (right click to cancel then quit)" self.selectedPolygonInstructions = 'Use "Select Features" tool to select polygon(s) designating AOI for which temporal/spectral profile should be calculated' def unload(self): if not self.wdg is None: self.wdg.close() self.iface.removeToolBarIcon(self.action) self.iface.removePluginMenu("&Profile Tool", self.action) self.iface.removePluginMenu("&Profile Tool", self.aboutAction) def run(self): # first, check posibility if self.checkIfOpening() == False: return #if dock not already opened, open the dock and all the necessary thing (model,doProfile...) if self.dockOpened == False: self.mdl = QStandardItemModel(0, 6) self.wdg = PTDockWidget(self.iface.mainWindow(), self.iface, self.mdl) self.wdg.showIt() self.doprofile = DoProfile(self.iface,self.wdg,self.pointTool, self) self.tableViewTool = TableViewTool() QObject.connect(self.wdg, SIGNAL( "closed(PyQt_PyObject)" ), self.cleaning2) QObject.connect(self.wdg.tableView,SIGNAL("clicked(QModelIndex)"), self._onClick) QObject.connect(self.wdg.pushButton_2, SIGNAL("clicked()"), self.addLayer) QObject.connect(self.wdg.pushButton, SIGNAL("clicked()"), self.removeLayer) QObject.connect(self.wdg.comboBox, SIGNAL("currentIndexChanged(int)"), self.selectionMethod) QObject.connect(self.wdg.cboLibrary, SIGNAL("currentIndexChanged(int)"), self.changePlotLibrary) QObject.connect(self.wdg.cboXAxis, SIGNAL("currentIndexChanged(int)"), self.changeXAxisLabeling) QObject.connect(self.wdg.leXAxisSteps, SIGNAL("editingFinished()"), self.changeXAxisLabeling) QObject.connect(self.wdg.dateTimeEditCurrentTime, SIGNAL("editingFinished()"), self.changeXAxisLabeling) QObject.connect(self.wdg.spinBoxTimeExtent, SIGNAL("editingFinished()"), self.changeXAxisLabeling) QObject.connect(self.wdg.cboTimeExtent, SIGNAL("currentIndexChanged(int)"), self.changeXAxisLabeling) QObject.connect(self.wdg.cbTimeDimension, SIGNAL("stateChanged(int)"), self.changeXAxisLabeling) self.wdg.addOptionComboboxItems() self.addLayer() self.dockOpened = True #Listeners of mouse self.connectPointMapTool() #init the mouse listener comportement and save the classic to restore it on quit self.canvas.setMapTool(self.pointTool) #Help about what doing if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.iface.mainWindow().statusBar().showMessage(self.pointSelectionInstructions ) elif self.selectionmethod == TemporalSpectralProfilePlugin.SELECTED_POLYGON: self.iface.mainWindow().statusBar().showMessage(self.selectedPolygonInstructions) QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL("layersWillBeRemoved (QStringList)"), self.onLayersWillBeRemoved) #************************************* Canvas listener actions ********************************************** # Used when layer is about to be removed from QGIS Map Layer Registry def onLayersWillBeRemoved(self, layersIds): if self.mdl is not None: for layerId in layersIds: for row in range(self.mdl.rowCount()): if layerId == self.mdl.index(row, 3).data().id(): self.removeLayer(row) self.onLayersWillBeRemoved(layersIds) break # Use for selected polygon option def selectionChanged(self, layer): if not layer.geometryType() == QGis.Polygon: return fullGeometry = QgsGeometry() for feature in layer.selectedFeatures(): if fullGeometry.isEmpty(): fullGeometry = QgsGeometry(feature.constGeometry()) else: fullGeometry = fullGeometry.combine(feature.constGeometry()) if not fullGeometry.isEmpty(): crs = osr.SpatialReference() crs.ImportFromProj4(str(layer.crs().toProj4())) self.doprofile.calculatePolygonProfile(fullGeometry, crs, self.mdl, self.plotlibrary) #************************************* Mouse listener actions *********************************************** # Used for point selection option def moved(self, point): if self.wdg and not self.wdg.cbPlotWhenClick.isChecked(): if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.doubleClicked(point) if self.selectionmethod == TemporalSpectralProfilePlugin.SELECTED_POLYGON: pass def rightClicked(self, point): #used to quit the current action self.cleaning() def leftClicked(self, point): self.doubleClicked(point) def doubleClicked(self, point): if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.iface.mainWindow().statusBar().showMessage(str(point.x())+", "+str(point.y())) self.doprofile.calculatePointProfile(point, self.mdl, self.plotlibrary) if self.selectionmethod == TemporalSpectralProfilePlugin.SELECTED_POLYGON: return #***************************** open and quit options ******************************************* def checkIfOpening(self): if self.iface.mapCanvas().layerCount() == 0: #Check a layer is opened QMessageBox.warning(self.iface.mainWindow(), "Profile", "First open a raster layer, please") return False layer = self.iface.activeLayer() if layer == None or not isProfilable(layer) : #Check if a raster layer is opened and selected if self.mdl == None or self.mdl.rowCount() == 0: QMessageBox.warning(self.iface.mainWindow(), "Profile Tool", "Please select a raster layer") return False return True def connectPointMapTool(self): QObject.connect(self.pointTool, SIGNAL("moved"), self.moved) QObject.connect(self.pointTool, SIGNAL("rightClicked"), self.rightClicked) QObject.connect(self.pointTool, SIGNAL("leftClicked"), self.leftClicked) QObject.connect(self.pointTool, SIGNAL("doubleClicked"), self.doubleClicked) QObject.connect(self.pointTool, SIGNAL("deactivate"), self.deactivatePointMapTool) def deactivatePointMapTool(self): #enable clean exit of the plugin QObject.disconnect(self.pointTool, SIGNAL("moved"), self.moved) QObject.disconnect(self.pointTool, SIGNAL("leftClicked"), self.leftClicked) QObject.disconnect(self.pointTool, SIGNAL("rightClicked"), self.rightClicked) QObject.disconnect(self.pointTool, SIGNAL("doubleClicked"), self.doubleClicked) self.iface.mainWindow().statusBar().showMessage("") def connectSelectedPolygonsTool(self): QObject.connect(self.iface.mapCanvas(), SIGNAL("selectionChanged(QgsMapLayer *)"), self.selectionChanged) def deactivateSelectedPolygonsTools(self): QObject.disconnect(self.iface.mapCanvas(), SIGNAL("selectionChanged(QgsMapLayer *)"), self.selectionChanged) def cleaning(self): #used on right click self.canvas.unsetMapTool(self.pointTool) self.canvas.setMapTool(self.saveTool) self.iface.mainWindow().statusBar().showMessage("") def cleaning2(self): #used when Dock dialog is closed QObject.disconnect(self.wdg.tableView,SIGNAL("clicked(QModelIndex)"), self._onClick) if self.selectionmethod == TemporalSpectralProfilePlugin.POINT_SELECTION: self.deactivatePointMapTool() else: self.deactivateSelectedPolygonsTools() self.selectionmethod = TemporalSpectralProfilePlugin.POINT_SELECTION QObject.disconnect(self.wdg.comboBox, SIGNAL("currentIndexChanged(int)"), self.selectionMethod) QObject.disconnect(QgsMapLayerRegistry.instance(), SIGNAL("layersWillBeRemoved (QStringList)"), self.onLayersWillBeRemoved) self.mdl = None self.dockOpened = False self.cleaning() self.wdg = None #***************************** Options ******************************************* def selectionMethod(self,item): if item == TemporalSpectralProfilePlugin.POINT_SELECTION: self.selectionmethod = TemporalSpectralProfilePlugin.POINT_SELECTION self.pointTool.setCursor(Qt.CrossCursor) self.deactivateSelectedPolygonsTools() self.connectPointMapTool() if not self.canvas.mapTool() == self.pointTool: self.canvas.setMapTool(self.pointTool) self.iface.mainWindow().statusBar().showMessage(self.pointSelectionInstructions) self.wdg.changeStatComboBoxItems(self.doprofile.getPointProfileStatNames()) elif item == TemporalSpectralProfilePlugin.SELECTED_POLYGON: self.selectionmethod = TemporalSpectralProfilePlugin.SELECTED_POLYGON self.deactivatePointMapTool() self.connectSelectedPolygonsTool() self.iface.actionSelectRectangle().trigger() self.iface.mainWindow().statusBar().showMessage(self.selectedPolygonInstructions) self.wdg.changeStatComboBoxItems(self.doprofile.getPolygonProfileStatNames(), "mean") def changePlotLibrary(self, item): self.plotlibrary = self.wdg.cboLibrary.itemText(item) self.wdg.addPlotWidget(self.plotlibrary) self.changeXAxisLabeling() def changeXAxisLabeling(self): self.xAxisSteps = {} # default band number labeling if self.wdg.cboXAxis.currentIndex() == 0: self.doprofile.xAxisSteps = None # Labels from string elif self.wdg.cboXAxis.currentIndex() == 1: self.doprofile.xAxisSteps = self.wdg.leXAxisSteps.text().split(';') try: self.doprofile.xAxisSteps = [ float(x) for x in self.doprofile.xAxisSteps ] except ValueError: self.doprofile.xAxisSteps = None text = "Temporal/Spectral Profile Tool: The X-axis steps' string " + \ "is invalid. Using band numbers instead." self.iface.messageBar().pushWidget(self.iface.messageBar().createMessage(text), QgsMessageBar.WARNING, 5) # Labels based on time elif self.wdg.cboXAxis.currentIndex() == 2: self.doprofile.xAxisSteps = ["Timesteps", self.wdg.dateTimeEditCurrentTime.dateTime().toPyDateTime(), int(self.wdg.spinBoxTimeExtent.cleanText()), self.wdg.cboTimeExtent.currentText(), self.wdg.cbTimeDimension.isChecked()] if self.plotlibrary == "Qwt5": text = "Temporal/Spectral Profile Tool: There is currently no support using " + \ "Time steps while using the Qwt plotlibrary" self.iface.messageBar().pushWidget(self.iface.messageBar().createMessage(text), QgsMessageBar.WARNING, 5) self.doprofile.xAxisSteps = None #************************* tableview function ****************************************** def addLayer(self): layer = self.iface.activeLayer() if isProfilable(layer): self.tableViewTool.addLayer(self.iface, self.mdl, layer) def _onClick(self,index1): #action when clicking the tableview self.tableViewTool.onClick(self.iface, self.wdg, self.mdl, self.plotlibrary, index1) def removeLayer(self, index = None): if index is None: index = self.tableViewTool.chooseLayerForRemoval(self.iface, self.mdl) if index is not None: self.tableViewTool.removeLayer(self.mdl, index) PlottingTool().clearData(self.wdg, self.mdl, self.plotlibrary) def about(self): from ui.dlgabout import DlgAbout DlgAbout(self.iface.mainWindow()).exec_()
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 = PdokBagWfsConnectorDialog() # add some slots for the signals self.dlg.button_box.button(QDialogButtonBox.Ok).setEnabled(False) QObject.connect(self.dlg.fileBrowseButton_2, SIGNAL("clicked()"), self.chooseFile) QObject.connect(self.dlg.fileNameBox, SIGNAL("textChanged(QString)"), self.fileNameBoxChanged) QObject.connect(self.dlg.helpButton, SIGNAL("clicked()"), self.showHelp) # populate the layer combo with open(os.path.join(self.plugin_dir,'layers.txt'),'r') as f: layers = [line.strip() for line in f] for layer in layers: self.dlg.layerCombo.addItem(layer) 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.addPluginToWebMenu( self.menu, action) self.actions.append(action) return action
class PrintTemplatesCreator: def __init__(self, iface): self.iface = iface try: from .tests import testerplugin from qgistester.tests import addTestModule addTestModule(testerplugin, "Print Templates Creator") except: pass overrideLocale = QSettings().value("locale/overrideFlag", False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QSettings().value("locale/userLocale", "") qmPath = "{}/i18n/templatescreator_{}.qm".format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator) def initGui(self): self.runAction = QAction(self.tr("Print templates creator"), self.iface.mainWindow()) self.runAction.setIcon( QIcon(os.path.join(pluginPath, "icons", "print.svg"))) self.runAction.setWhatsThis( self.tr("Generate Print JSON from QGIS composer layout")) self.runAction.setObjectName("printTemplatesCreatorRun") self.runAction.triggered.connect(self.run) self.helpAction = QAction(self.tr("Help"), self.iface.mainWindow()) self.helpAction.setIcon( QgsApplication.getThemeIcon('/mActionHelpAPI.png')) self.helpAction.setObjectName("printTemplatesCreatorHelp") self.helpAction.triggered.connect( lambda: webbrowser.open_new("file://{}".format( os.path.join(os.path.dirname(__file__), "docs", "html", "index.html")))) self.iface.addWebToolBarIcon(self.runAction) self.iface.addPluginToWebMenu(self.tr("Print templates creator"), self.runAction) self.iface.addPluginToWebMenu(self.tr("Print templates creator"), self.helpAction) try: from lessons import addLessonsFolder folder = os.path.join(os.path.dirname(__file__), "_lessons") addLessonsFolder(folder) except: pass def unload(self): try: from .tests import testerplugin from qgistester.tests import removeTestModule removeTestModule(testerplugin, "Print Templates Creator") except: pass self.iface.removeWebToolBarIcon(self.runAction) self.iface.removePluginWebMenu(self.tr("Print templates creator"), self.runAction) self.iface.removePluginWebMenu(self.tr("Print templates creator"), self.helpAction) def run(self): dlg = ComposersDialog(self.iface, self.iface.mainWindow()) dlg.show() dlg.exec_() def tr(self, text): return QCoreApplication.translate('Print Templates Creator', text)
class BoundlessConnectPlugin: def __init__(self, iface): self.iface = iface try: from boundlessconnect.tests import testerplugin from qgistester.tests import addTestModule addTestModule(testerplugin, 'Boundless Connect') except Exception as e: pass overrideLocale = QSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QSettings().value('locale/userLocale', '') qmPath = '{}/i18n/boundlessconnect_{}.qm'.format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator) self.iface.initializationCompleted.connect(self.startFirstRunWizard) def initGui(self): self.actionRunWizard = QAction( self.tr('Boundless Connect Login'), self.iface.mainWindow()) self.actionRunWizard.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'connect.svg'))) self.actionRunWizard.setWhatsThis( self.tr('Login to Boundless Connect')) self.actionRunWizard.setObjectName('actionRunWizard') self.actionPluginFromZip = QAction( self.tr('Install plugin from ZIP'), self.iface.mainWindow()) self.actionPluginFromZip.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'plugin.svg'))) self.actionPluginFromZip.setWhatsThis( self.tr('Install plugin from ZIP file stored on disk')) self.actionPluginFromZip.setObjectName('actionPluginFromZip') self.actionRunWizard.triggered.connect(self.runWizardAndProcessResults) self.actionPluginFromZip.triggered.connect(self.installPlugin) # If Boundless repository is a directory, add menu entry # to start modified Plugin Manager which works with local repositories if utils.isRepositoryInDirectory(): self.actionPluginManager = QAction( self.tr('Manage plugins (local folder)'), self.iface.mainWindow()) self.actionPluginManager.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'plugin.svg'))) self.actionPluginManager.setWhatsThis( self.tr('Manage and install plugins from local repository')) self.actionPluginManager.setObjectName('actionPluginManager') self.iface.addPluginToMenu( self.tr('Boundless Connect'), self.actionPluginManager) self.actionPluginManager.triggered.connect(self.pluginManagerLocal) actions = self.iface.mainWindow().menuBar().actions() for action in actions: if action.menu().objectName() == 'mPluginMenu': menuPlugin = action.menu() separator = menuPlugin.actions()[1] menuPlugin.insertAction(separator, self.actionRunWizard) menuPlugin.insertAction(separator, self.actionPluginFromZip) if utils.isRepositoryInDirectory(): menuPlugin.insertAction(separator, self.actionPluginManager) # Add Boundless plugin repository to list of the available # plugin repositories if it is not presented here #utils.addBoundlessRepository() # Enable check for updates if it is not enabled utils.addCheckForUpdates() def unload(self): actions = self.iface.mainWindow().menuBar().actions() for action in actions: if action.menu().objectName() == 'mPluginMenu': menuPlugin = action.menu() menuPlugin.removeAction(self.actionRunWizard) menuPlugin.removeAction(self.actionPluginFromZip) if utils.isRepositoryInDirectory(): menuPlugin.removeAction(self.actionPluginManager) try: from boundlessconnect.tests import testerplugin from qgistester.tests import removeTestModule removeTestModule(testerplugin, 'Boundless Connect') except Exception as e: pass def startFirstRunWizard(self): settings = QSettings('Boundless', 'BoundlessConnect') version = utils.connectVersion() firstRun = settings.value('firstRun' + version, True, bool) settings.setValue('firstRun' + version, False) if firstRun: self.runWizardAndProcessResults() def installPlugin(self): settings = QSettings('Boundless', 'BoundlessConnect') lastDirectory = settings.value('lastPluginDirectory', '.') fileName = QFileDialog.getOpenFileName(self.iface.mainWindow(), self.tr('Open file'), lastDirectory, self.tr('Plugin packages (*.zip *.ZIP)')) if fileName == '': return result = utils.installFromZipFile(fileName) if result is None: self._showMessage(self.tr('Plugin installed successfully'), QgsMessageBar.SUCCESS) else: self._showMessage(result, QgsMessageBar.WARNING) settings.setValue('lastPluginDirectory', QFileInfo(fileName).absoluteDir().absolutePath()) def pluginManagerLocal(self): utils.showPluginManager(False) def runWizardAndProcessResults(self): dlg = ConnectDialog() if dlg.exec_(): utils.showPluginManager(True) utils.installFromStandardPath() self._showMessage( self.tr('Boundless Connect is done configuring your QGIS.'), QgsMessageBar.SUCCESS) def checkingDone(self): updateNeeded, allInstalled = utils.checkPluginsStatus() res = utils.upgradeConnect() if res != '': self._showMessage(res) return if allInstalled and not updateNeeded: self._showMessage(self.tr('You are up to date with Boundless plugins')) elif updateNeeded: self.btnUpdate = QPushButton(self.tr('Update')) self.btnUpdate.clicked.connect(utils.upgradeInstalledPlugins) self.btnUpdate.clicked.connect(self.iface.messageBar().popWidget) updateMsg = QgsMessageBarItem(self.tr('Update plugins'), self.tr('Some Boundless plugins need ' 'to be updated. Update them now?'), self.btnUpdate, QgsMessageBar.INFO, 0, self.iface.messageBar() ) self.iface.messageBar().pushItem(updateMsg) def _showMessage(self, message, level=QgsMessageBar.INFO): self.iface.messageBar().pushMessage( message, level, self.iface.messageTimeout()) def tr(self, text): return QCoreApplication.translate('Boundless Connect', text)
class EjdexplInt: def __init__(self, iface): self.iface = iface self.plugin_dir = os.path.dirname(__file__) self.searchobj = None self.readconfig() self.updateconfig() self.srsitem = CanvasItems(self.iface.mapCanvas(),self.config['search_color'],self.config['search_style'],self.config['search_width'],self.config['search_icon'],self.config['search_size']) self.db = QSqlDatabase.addDatabase('QODBC') self.db.setDatabaseName(self.config['connection']) locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir,'i18n','EjdexplInt_{}.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) def tr(self, message): return QCoreApplication.translate('EjdexplInt', message) def initGui(self): self.action = QAction(QIcon(":/plugins/EjdexplInt/icons/icon.png"),self.tr(u'Activate EjdExplorer tool'),self.iface.mainWindow()) self.action.setWhatsThis(u"Activate EjdExplorer tool") self.action.triggered.connect(self.run) self.tbmenu = QMenu() self.ag1 = QActionGroup(self.tbmenu,exclusive=True) self.acPol = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Polygon.ico'),self.tr(u'Draw polygon'),self.tbmenu,checkable=True)) self.acLin = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Polyline.ico'),self.tr(u'Draw line'),self.tbmenu,checkable=True)) self.acPnt = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Geo-Fence.ico'),self.tr(u'Draw point'),self.tbmenu,checkable=True)) self.acAlay = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Layers.ico'),self.tr(u'Active selection'),self.tbmenu,checkable=True)) self.acPobj = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Quest.ico'),self.tr(u'Previous object'),self.tbmenu,checkable=True)) self.tbmenu.addActions(self.ag1.actions()); self.acPol.setChecked(self.config['searchtool']==u'polygon') self.acLin.setChecked(self.config['searchtool']==u'line') self.acPnt.setChecked(self.config['searchtool']==u'point') self.acAlay.setChecked(self.config['searchtool']==u'selection') self.acPobj.setChecked(self.config['searchtool']==u'search') self.tbmenu.addSeparator() self.ag2 = QActionGroup(self.tbmenu,exclusive=True) self.acSingle = self.ag2.addAction(QAction(self.tr(u'Use single mode'),self.tbmenu,checkable=True)) self.acBulk = self.ag2.addAction(QAction(self.tr(u'Use bulk mode'),self.tbmenu,checkable=True)) self.acMerge = self.ag2.addAction(QAction(self.tr(u'Use merge mode'),self.tbmenu,checkable=True)) self.tbmenu.addActions(self.ag2.actions()); self.acSingle.setChecked(self.config['tabchoice']==u'single') self.acBulk.setChecked(self.config['tabchoice']==u'bulk') self.acMerge.setChecked(self.config['tabchoice']==u'merge') if self.config['old_behavior'] == 0: self.tbmenu.addSeparator() self.acClear = QAction(self.tr(u'Clear'),self.tbmenu,checkable=False) self.acClear.triggered.connect(self.clearSearch) self.tbmenu.addAction(self.acClear) self.toolButton = QToolButton() self.toolButton.addAction(self.action) self.toolButton.setDefaultAction(self.action) self.toolButton.setMenu(self.tbmenu) self.toolButton.setPopupMode(QToolButton.MenuButtonPopup) self.iface.addToolBarWidget(self.toolButton) self.iface.addPluginToMenu(self.tr(u'Activate EjdExplorer tool'), self.action) self.ag1.triggered.connect(self.drawChanged) def drawChanged(self, action): if action.isChecked(): self.run() def clearSearch(self): if self.config['old_behavior'] == 0: self.srsitem.clearMarkerGeom() def unload(self): self.iface.removePluginMenu(self.tr(u'Activate EjdExplorer tool'), self.action) self.iface.removeToolBarIcon(self.action) del self.tbmenu # No parent del self.toolButton # No parent def run(self): geoms = None canvas = self.iface.mapCanvas() if self.config['old_behavior'] == 0: self.srsitem.clearMarkerGeom() if self.acPol.isChecked(): # polygon tool = CaptureTool(canvas, self.geometryAdded, CaptureTool.CAPTURE_POLYGON) canvas.setMapTool(tool) elif self.acLin.isChecked(): # line tool = CaptureTool(canvas, self.geometryAdded, CaptureTool.CAPTURE_LINE) canvas.setMapTool(tool) elif self.acPnt.isChecked(): # point tool = AddPointTool(canvas, self.geometryAdded) canvas.setMapTool(tool) elif self.acAlay.isChecked(): # active layer selection layer = self.iface.activeLayer() if (layer) and (layer.type() == QgsMapLayer.VectorLayer): selection = layer.selectedFeatures() if (selection): for f in selection: if geoms == None: geoms = f.geometry() else: geoms = geoms.combine( f.geometry() ) if (geoms != None): self.geometryAdded(geoms) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'No object found'), QgsMessageBar.CRITICAL, 6) elif self.acPobj.isChecked(): # existing object geoms = self.searchobj if (geoms != None): self.geometryAdded(geoms) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'No existing object found'), QgsMessageBar.CRITICAL, 6) self.acPol.setChecked(True) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'Uknown search tool'), QgsMessageBar.CRITICAL, 6) def cnvobj2wkt (self,gobj,epsg_in,epsg_out, buffer_pol, buffer_lin): # Buffer around search object; negative for polygon or positive for points and lines if gobj.type() == 2: # Polygon gobj = gobj.buffer(buffer_pol,8) else: # Line or Point gobj = gobj.buffer(buffer_lin,8) crsSrc = QgsCoordinateReferenceSystem(int(epsg_in)) crsDest = QgsCoordinateReferenceSystem(int(epsg_out)) xform = QgsCoordinateTransform(crsSrc, crsDest) i = gobj.transform(xform) return gobj.exportToWkt() def geometryAdded(self, geom): self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Start EjdExplorer'), self.tr(u'Starting EjdExplorer program, takes a few seconds..'), QgsMessageBar.INFO, 6) self.searchobj = geom if self.config['old_behavior'] == 0: self.srsitem.setMarkerGeom(geom) epsg_in = self.iface.mapCanvas().mapRenderer().destinationCrs().authid().replace('EPSG:','') geom_txt = self.cnvobj2wkt (geom,epsg_in,self.config['epsg'],self.config['buffer_pol'],self.config['buffer_lin']) txt1, txt2 = self.getlists (geom_txt) mode = u'single' if self.acBulk.isChecked(): mode = u'bulk' if self.acMerge.isChecked(): mode = u'merge' # NB! parameters dosn't work as expected, LIFA contacted (and admit to an error in their program) txt = u'start ' + self.config['command'] + u' "' + self.config['parameter'].format(mode, txt1,txt2) + u'"' txt = txt.encode('latin-1') if len(txt) <= 8190: # max length of command-line parameter os.system ( txt) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Start EjdExplorer'), self.tr(u'To many entities selected; try with a smaller search object'), QgsMessageBar.CRITICAL, 6) self.iface.actionPan().trigger() def msgbox (self,txt1): cb = QApplication.clipboard() cb.setText(txt1) msgBox = QMessageBox() msgBox.setText(txt1) msgBox.exec_() def getlists(self, wkt): ejrlrv = [] matrnr = [] if (self.db.open()==True): query = QSqlQuery (self.config['sqlquery'].format(wkt,self.config['epsg'])) while (query.next()): ejrlrv.append(query.value(0)) matrnr.append(query.value(1)) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Database Error'), db.lastError().text(), QgsMessageBar.INFO, 6) return u','.join(ejrlrv), u','.join(matrnr) def readconfig(self): s = QSettings() k = __package__ self.config = { 'epsg': unicode(s.value(k + "/epsg" , "25832", type=str)), 'buffer_pol': s.value(k + "/buffer_pol" , -0.1, type=float), 'buffer_lin': s.value(k + "/buffer_lin" , 0.1, type=float), 'searchtool': unicode(s.value(k + "/searchtool" , "point", type=str)).lower(), 'tabchoice': unicode(s.value(k + "/tabchoice" , "single", type=str)).lower(), 'sqlquery': unicode(s.value(k + "/sqlquery" , "select LTRIM(RTRIM(CONVERT(varchar(10), [landsejerlavskode]))) as ejrlvnr, LTRIM(RTRIM([matrikelnummer])) as matrnr from [dbo].[Jordstykke] where geometry::STGeomFromText('{0}',{1}).STIntersects([geometri])=1", type=str)), 'connection': unicode(s.value(k + "/connection" , "Driver={SQL Server};Server=f-sql12;Database=LOIS;Trusted_Connection=Yes;", type=str)), 'command': unicode(s.value(k + "/command" , 'C:/"Program Files (x86)"/LIFA/EjdExplorer/LIFA.EjdExplorer.GUI.exe', type=str)), 'parameter': unicode(s.value(k + "/parameter" , 'ejdexpl://?mode={0}&CadastralDistrictIdentifier={1}&RealPropertyKey={2}', type=str)), 'search_color': str(s.value(k + "/search_color", "#FF0000", type=str)), 'search_width': s.value(k + "/search_width", 4, type=int), 'search_style': s.value(k + "/search_style", 1, type=int), 'search_icon': s.value(k + "/search_icon", QgsVertexMarker.ICON_CROSS, type=int), 'search_size': s.value(k + "/search_size", 30, type=int), 'old_behavior': s.value(k + "/old_behavior", 0, type=int) } self.srsitem = CanvasItems(self.iface.mapCanvas(),self.config['search_color'],self.config['search_style'],self.config['search_width'],self.config['search_icon'],self.config['search_size']) def updateconfig(self): s = QSettings() k = __package__ s.setValue(k + "/epsg", self.config['epsg']) s.setValue(k + "/buffer_pol", self.config['buffer_pol']) s.setValue(k + "/buffer_lin", self.config['buffer_lin']) s.setValue(k + "/searchtool", self.config['searchtool']) s.setValue(k + "/tabchoice", self.config['tabchoice']) s.setValue(k + "/sqlquery", self.config['sqlquery']) s.setValue(k + "/connection", self.config['connection']) s.setValue(k + "/command", self.config['command']) s.setValue(k + "/parameter", self.config['parameter']) s.setValue(k + "/search_color", self.config['search_color']) s.setValue(k + "/search_style", self.config['search_style']) s.setValue(k + "/search_width", self.config['search_width']) s.setValue(k + "/search_icon", self.config['search_icon']) s.setValue(k + "/search_size", self.config['search_size']) s.setValue(k + "/old_behavior", self.config['old_behavior']) s.sync
class Plugin(object): """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menu bar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Register all the impact functions register_impact_functions() # Save reference to the QGIS interface self.iface = iface self.dock_widget = None self.action_import_dialog = None self.action_save_scenario = None self.action_batch_runner = None self.action_shake_converter = None self.action_minimum_needs = None self.action_minimum_needs_config = None self.action_impact_merge_dlg = None self.key_action = None self.action_options = None self.action_keywords_wizard = None self.action_function_centric_wizard = None self.action_extent_selector = None self.translator = None self.toolbar = None self.wizard = None self.actions = [] # list of all QActions we create for InaSAFE self.action_dock = None self.action_toggle_rubberbands = None self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) # noinspection PyArgumentList def change_i18n(self, new_locale): """Change internationalisation for the plugin. Override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param new_locale: The new locale i.e. 'id', 'af', etc. :type new_locale: str :raises: TranslationLoadException """ os.environ['INASAFE_LANG'] = str(new_locale) LOGGER.debug('%s %s %s' % ( new_locale, QLocale.system().name(), os.environ['INASAFE_LANG'])) root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) translation_path = os.path.join( root, 'safe_qgis', 'i18n', 'inasafe_' + str(new_locale) + '.qm') if os.path.exists(translation_path): self.translator = QTranslator() result = self.translator.load(translation_path) if not result: message = 'Failed to load translation for %s' % new_locale raise TranslationLoadError(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( translation_path, os.path.exists(translation_path))) # 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('Plugin', message) def add_action(self, action, add_to_toolbar=True): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) def _create_dock_toggle_action(self): """Create action for plugin dockable window (show/hide).""" # pylint: disable=W0201 icon = resources_path('img', 'icons', 'icon.svg') self.action_dock = QAction( QIcon(icon), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.action_dock.setObjectName('InaSAFEDockToggle') self.action_dock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setCheckable(True) self.action_dock.setChecked(True) self.action_dock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.action_dock) # -------------------------------------- # Create action for keywords creation wizard # ------------------------------------- def _create_keywords_wizard_action(self): """Create action for keywords creation wizard.""" icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('Keywords Creation Wizard'), self.iface.mainWindow()) self.action_keywords_wizard.setStatusTip(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setWhatsThis(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setEnabled(False) self.action_keywords_wizard.triggered.connect( self.show_keywords_wizard) self.add_action(self.action_keywords_wizard) def _create_analysis_wizard_action(self): """Create action for IF-centric wizard.""" icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('Impact Function Centric Wizard'), self.iface.mainWindow()) self.action_function_centric_wizard.setStatusTip(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setWhatsThis(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setEnabled(True) self.action_function_centric_wizard.triggered.connect( self.show_function_centric_wizard) self.add_action(self.action_function_centric_wizard) def _create_options_dialog_action(self): """Create action for options dialog.""" icon = resources_path('img', 'icons', 'configure-inasafe.svg') self.action_options = QAction( QIcon(icon), self.tr('Options'), self.iface.mainWindow()) self.action_options.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.action_options.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) self.action_options.triggered.connect(self.show_options) self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_action(self): """Create action for minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.action_minimum_needs = QAction( QIcon(icon), self.tr('Minimum Needs Calculator'), self.iface.mainWindow()) self.action_minimum_needs.setStatusTip(self.tr( 'Open InaSAFE minimum needs calculator')) self.action_minimum_needs.setWhatsThis(self.tr( 'Open InaSAFE minimum needs calculator')) self.action_minimum_needs.triggered.connect(self.show_minimum_needs) self.add_action( self.action_minimum_needs, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_options_action(self): """Create action for global minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg') self.action_minimum_needs_config = QAction( QIcon(icon), self.tr('Minimum Needs Configuration'), self.iface.mainWindow()) self.action_minimum_needs_config.setStatusTip(self.tr( 'Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.setWhatsThis(self.tr( 'Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.triggered.connect( self.show_minimum_needs_configuration) self.add_action( self.action_minimum_needs_config, add_to_toolbar=self.full_toolbar) def _create_shakemap_converter_action(self): """Create action for converter dialog.""" icon = resources_path('img', 'icons', 'show-converter-tool.svg') self.action_shake_converter = QAction( QIcon(icon), self.tr('Shakemap Converter'), self.iface.mainWindow()) self.action_shake_converter.setStatusTip(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.setWhatsThis(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.triggered.connect( self.show_shakemap_importer) self.add_action( self.action_shake_converter, add_to_toolbar=self.full_toolbar) def _create_batch_runner_action(self): """Create action for batch runner dialog.""" icon = resources_path('img', 'icons', 'show-batch-runner.svg') self.action_batch_runner = QAction( QIcon(icon), self.tr('Batch Runner'), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr( 'Open Batch Runner')) self.action_batch_runner.setWhatsThis(self.tr( 'Open Batch Runner')) self.action_batch_runner.triggered.connect(self.show_batch_runner) self.add_action( self.action_batch_runner, add_to_toolbar=self.full_toolbar) def _create_save_scenario_action(self): """Create action for save scenario dialog.""" icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction( QIcon(icon), self.tr('Save Current Scenario'), self.iface.mainWindow()) message = self.tr('Save current scenario to text file') self.action_save_scenario.setStatusTip(message) self.action_save_scenario.setWhatsThis(message) # noinspection PyUnresolvedReferences self.action_save_scenario.triggered.connect(self.save_scenario) self.add_action( self.action_save_scenario, add_to_toolbar=self.full_toolbar) def _create_osm_downloader_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'show-osm-download.svg') self.action_import_dialog = QAction( QIcon(icon), self.tr('OpenStreetMap Downloader'), self.iface.mainWindow()) self.action_import_dialog.setStatusTip(self.tr( 'OpenStreetMap Downloader')) self.action_import_dialog.setWhatsThis(self.tr( 'OpenStreetMap Downloader')) self.action_import_dialog.triggered.connect(self.show_osm_downloader) self.add_action(self.action_import_dialog) def _create_add_osm_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-osm-tiles-layer.svg') self.action_add_osm_layer = QAction( QIcon(icon), self.tr('Add OpenStreetMap Tile Layer'), self.iface.mainWindow()) self.action_add_osm_layer.setStatusTip(self.tr( 'Add OpenStreetMap Tile Layer')) self.action_add_osm_layer.setWhatsThis(self.tr( 'Use this to add an OSM layer to your map. ' 'It needs internet access to function.')) self.action_add_osm_layer.triggered.connect(self.add_osm_layer) self.add_action(self.action_add_osm_layer) def _create_add_petajakarta_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-petajakarta-layer.svg') self.action_add_petajakarta_layer = QAction( QIcon(icon), self.tr('Add PetaJakarta Flood Layer'), self.iface.mainWindow()) self.action_add_petajakarta_layer.setStatusTip(self.tr( 'Add PetaJakarta Flood Layer')) self.action_add_petajakarta_layer.setWhatsThis(self.tr( 'Use this to add a PetaJakarta layer to your map. ' 'It needs internet access to function.')) self.action_add_petajakarta_layer.triggered.connect( self.add_petajakarta_layer) self.add_action( self.action_add_petajakarta_layer, add_to_toolbar=False) def _create_impact_merge_action(self): """Create action for impact layer merge Dialog.""" icon = resources_path('img', 'icons', 'show-impact-merge.svg') self.action_impact_merge_dlg = QAction( QIcon(icon), self.tr('Impact Layer Merger'), self.iface.mainWindow()) self.action_impact_merge_dlg.setStatusTip(self.tr( 'Impact Layer Merger')) self.action_impact_merge_dlg.setWhatsThis(self.tr( 'Impact Layer Merger')) self.action_impact_merge_dlg.triggered.connect(self.show_impact_merge) self.add_action( self.action_impact_merge_dlg, add_to_toolbar=self.full_toolbar) def _create_rubber_bands_action(self): """Create action for toggling rubber bands.""" icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg') self.action_toggle_rubberbands = QAction( QIcon(icon), self.tr('Toggle Scenario Outlines'), self.iface.mainWindow()) message = self.tr('Toggle rubber bands showing scenario extents.') self.action_toggle_rubberbands.setStatusTip(message) self.action_toggle_rubberbands.setWhatsThis(message) # Set initial state self.action_toggle_rubberbands.setCheckable(True) settings = QSettings() flag = bool(settings.value( 'inasafe/showRubberBands', False, type=bool)) self.action_toggle_rubberbands.setChecked(flag) # noinspection PyUnresolvedReferences self.action_toggle_rubberbands.triggered.connect( self.dock_widget.toggle_rubber_bands) self.add_action(self.action_toggle_rubberbands) def _create_analysis_extent_action(self): """Create action for analysis extent dialog.""" icon = resources_path('img', 'icons', 'set-extents-tool.svg') self.action_extent_selector = QAction( QIcon(icon), self.tr('Set Analysis Area'), self.iface.mainWindow()) self.action_extent_selector.setStatusTip(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.setWhatsThis(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.triggered.connect( self.show_extent_selector) self.add_action(self.action_extent_selector) def _create_test_layers_action(self): """Create action for adding layers (developer mode, non final only).""" final_release = release_status() == 'final' settings = QSettings() self.developer_mode = settings.value( 'inasafe/developer_mode', False, type=bool) if not final_release and self.developer_mode: icon = resources_path('img', 'icons', 'add-test-layers.svg') self.action_add_layers = QAction( QIcon(icon), self.tr('Add Test Layers'), self.iface.mainWindow()) self.action_add_layers.setStatusTip(self.tr( 'Add test layers')) self.action_add_layers.setWhatsThis(self.tr( 'Add test layers')) self.action_add_layers.triggered.connect( self.add_test_layers) self.add_action(self.action_add_layers) def _create_dock(self): """Create dockwidget and tabify it with the legend.""" # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = Dock(self.iface) self.dock_widget.setObjectName('InaSAFE-Dock') self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend') if legend_tab: self.iface.mainWindow().tabifyDockWidget( legend_tab, self.dock_widget) self.dock_widget.raise_() def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') self.dock_widget = None # Now create the actual dock self._create_dock() # And all the menu actions # Configuration Group self._create_dock_toggle_action() self._create_options_dialog_action() self._create_minimum_needs_options_action() self._create_analysis_extent_action() self._create_rubber_bands_action() self._add_spacer_to_menu() self._create_keywords_wizard_action() self._create_analysis_wizard_action() self._add_spacer_to_menu() self._create_osm_downloader_action() self._create_add_osm_layer_action() self._create_add_petajakarta_layer_action() self._create_shakemap_converter_action() self._create_minimum_needs_action() self._create_test_layers_action() self._add_spacer_to_menu() self._create_batch_runner_action() self._create_impact_merge_action() self._create_save_scenario_action() # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action) # Also deal with the fact that on start of QGIS dock may already be # hidden. self.action_dock.setChecked(self.dock_widget.isVisible()) def _add_spacer_to_menu(self): """Create a spacer to the menu to separate action groups.""" separator = QAction(self.iface.mainWindow()) separator.setSeparator(True) self.iface.addPluginToMenu(self.tr('InaSAFE'), separator) def clear_modules(self): """Unload inasafe functions and try to return QGIS to before InaSAFE. .. todo:: I think this function can be removed. TS. """ # next lets force remove any inasafe related modules modules = [] for module in sys.modules: if 'inasafe' in module: # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module.split('.') path = '' for myToken in tokens: path += os.path.sep + myToken parent = os.path.abspath(os.path.join( __file__, os.path.pardir, os.path.pardir)) full_path = os.path.join(parent, path + '.py') if os.path.exists(os.path.abspath(full_path)): LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) for module in sys.modules: if 'inasafe' in module: print module # Lets also clean up all the path additions that were made package_path = os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon if self.wizard: self.wizard.deleteLater() for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.mainWindow().removeDockWidget(self.dock_widget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dock_widget.setVisible(False) self.dock_widget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) def toggle_inasafe_action(self, checked): """Check or un-check the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.action_dock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dock_widget.isVisible(): self.dock_widget.setVisible(False) else: self.dock_widget.setVisible(True) self.dock_widget.raise_() def add_test_layers(self): """Add standard test layers.""" from safe.test.utilities import load_standard_layers load_standard_layers() rect = QgsRectangle(106.806, -6.195, 106.837, -6.167) self.iface.mapCanvas().setExtent(rect) def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, self.iface.mainWindow(), extent=self.dock_widget.extent.user_extent, crs=self.dock_widget.extent.user_extent_crs) widget.clear_extent.connect( self.dock_widget.extent.clear_user_analysis_extent) widget.extent_defined.connect( self.dock_widget.define_user_analysis_extent) # This ensures that run button state is updated on dialog close widget.extent_selector_closed.connect( self.dock_widget.show_next_analysis_extent) # Needs to be non modal to support hide -> interact with map -> show widget.show() # non modal def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.exec_() def show_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog( parent=self.iface.mainWindow(), dock=self.dock_widget) dialog.exec_() # modal def show_impact_merge(self): """Show the impact layer merge dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.impact_merge_dialog import ImpactMergeDialog dialog = ImpactMergeDialog(self.iface.mainWindow()) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog dialog = OptionsDialog( self.iface, self.dock_widget, self.iface.mainWindow()) dialog.exec_() # modal def show_keywords_wizard(self): """Show the keywords creation wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog if self.iface.activeLayer() is None: return # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since the IFCW is non modal if not self.wizard: self.wizard = WizardDialog( self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_keywords_creation_mode() self.wizard.exec_() # modal def show_function_centric_wizard(self): """Show the function centric wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since it is non modal if not self.wizard: self.wizard = WizardDialog( self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_function_centric_mode() # non-modal in order to hide for selecting user extent self.wizard.show() def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) dialog = ShakemapConverterDialog(self.iface.mainWindow()) dialog.exec_() # modal def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def add_osm_layer(self): """Add OSM tile layer to the map. This uses a gdal wrapper around the OSM tile service - see the WorldOSM.gdal file for how it is constructed. """ path = resources_path('osm', 'WorldOSM.gdal') layer = QgsRasterLayer(path, self.tr('OpenStreetMap')) registry = QgsMapLayerRegistry.instance() # For older versions we just add directly to the top of legend if QGis.QGIS_VERSION_INT < 20400: # True flag adds layer directly to legend registry.addMapLayer(layer, True) return # Otherwise try to add it as the last layer in the list # False flag prevents layer being added to legend registry.addMapLayer(layer, False) root = QgsProject.instance().layerTreeRoot() index = len(root.findLayers()) + 1 # LOGGER.info('Inserting layer %s at position %s' % ( # layer.source(), index)) root.insertLayer(index, layer) QgsMapLayerRegistry.instance().addMapLayer(layer) def add_petajakarta_layer(self): """Add petajakarta layer to the map. This uses the PetaJakarta API to fetch the latest floods in JK. See https://petajakarta.org/banjir/en/data/api/#aggregates """ from safe.gui.tools.peta_jakarta_dialog import PetaJakartaDialog dialog = PetaJakartaDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def show_batch_runner(self): """Show the batch runner dialog.""" from safe.gui.tools.batch.batch_dialog import BatchDialog dialog = BatchDialog( parent=self.iface.mainWindow(), iface=self.iface, dock=self.dock_widget) dialog.exec_() # modal def save_scenario(self): """Save current scenario to text file""" from safe.gui.tools.save_scenario import SaveScenarioDialog dialog = SaveScenarioDialog( iface=self.iface, dock=self.dock_widget) dialog.save_scenario() def _disable_keyword_tools(self): """Internal helper to disable the keyword and wizard actions.""" self.action_keywords_wizard.setEnabled(False) def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if not layer: self._disable_keyword_tools() return if not hasattr(layer, 'providerType'): self._disable_keyword_tools() return if layer.providerType() == 'wms': self._disable_keyword_tools() return if is_raster_layer(layer) and layer.bandCount() > 1: self._disable_keyword_tools() return self.action_keywords_wizard.setEnabled(True) def shortcut_f7(self): """Executed when user press F7 - will show the shakemap importer.""" self.show_shakemap_importer()
class Plugin: """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menubar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Save reference to the QGIS interface self.iface = iface self.translator = None self.toolbar = None self.actions = [] # list of all QActions we create for InaSAFE self.setup_i18n() #print self.tr('InaSAFE') custom_logging.setup_logger() # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) #noinspection PyArgumentList def setup_i18n(self, preferred_locale=None): """Setup internationalisation for the plugin. See if QGIS wants to override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param preferred_locale: If set will override any other way of determining locale. :type preferred_locale: str, None :raises: TranslationLoadException """ myOverrideFlag = QSettings().value('locale/overrideFlag', QVariant(False)).toBool() if preferred_locale is not None: myLocaleName = preferred_locale elif myOverrideFlag: myLocaleName = QSettings().value('locale/userLocale', QVariant('')).toString() else: myLocaleName = QLocale.system().name() # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc myLocaleName = str(myLocaleName).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(myLocaleName) LOGGER.debug('%s %s %s %s' % (preferred_locale, myOverrideFlag, QLocale.system().name(), os.environ['LANG'])) myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) myTranslationPath = os.path.join( myRoot, 'safe_qgis', 'i18n', 'inasafe_' + str(myLocaleName) + '.qm') if os.path.exists(myTranslationPath): self.translator = QTranslator() myResult = self.translator.load(myTranslationPath) if not myResult: myMessage = 'Failed to load translation for %s' % myLocaleName raise TranslationLoadError(myMessage) QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % (myTranslationPath, os.path.exists(myTranslationPath))) 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 """ return QCoreApplication.translate('Plugin', message) def add_action(self, action, add_to_toolbar=True): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) #noinspection PyCallByClass def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') # Import dock here as it needs to be imported AFTER i18n is set up from safe_qgis.widgets.dock import Dock self.dockWidget = None #-------------------------------------- # Create action for plugin dockable window (show/hide) #-------------------------------------- # pylint: disable=W0201 self.actionDock = QAction(QIcon(':/plugins/inasafe/icon.svg'), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.actionDock.setObjectName('InaSAFEDockToggle') self.actionDock.setStatusTip(self.tr('Show/hide InaSAFE dock widget')) self.actionDock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget')) self.actionDock.setCheckable(True) self.actionDock.setChecked(True) QObject.connect(self.actionDock, SIGNAL('triggered()'), self.toggle_dock_visibility) self.add_action(self.actionDock) #-------------------------------------- # Create action for keywords editor #-------------------------------------- self.actionKeywordsDialog = QAction( QIcon(':/plugins/inasafe/show-keyword-editor.svg'), self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow()) self.actionKeywordsDialog.setStatusTip( self.tr('Open InaSAFE keywords editor')) self.actionKeywordsDialog.setWhatsThis( self.tr('Open InaSAFE keywords editor')) self.actionKeywordsDialog.setEnabled(False) QObject.connect(self.actionKeywordsDialog, SIGNAL('triggered()'), self.show_keywords_editor) self.add_action(self.actionKeywordsDialog) #-------------------------------------- # Create action for reset icon #-------------------------------------- self.actionResetDock = QAction( QIcon(':/plugins/inasafe/reset-dock.svg'), self.tr('Reset Dock'), self.iface.mainWindow()) self.actionResetDock.setStatusTip(self.tr('Reset the InaSAFE Dock')) self.actionResetDock.setWhatsThis(self.tr('Reset the InaSAFE Dock')) QObject.connect(self.actionResetDock, SIGNAL('triggered()'), self.reset_dock) self.add_action(self.actionResetDock) #-------------------------------------- # Create action for options dialog #-------------------------------------- self.actionOptions = QAction( QIcon(':/plugins/inasafe/configure-inasafe.svg'), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.actionOptions.setStatusTip(self.tr('Open InaSAFE options dialog')) self.actionOptions.setWhatsThis(self.tr('Open InaSAFE options dialog')) QObject.connect(self.actionOptions, SIGNAL('triggered()'), self.show_options) self.add_action(self.actionOptions) #-------------------------------------- # Create action for impact functions doc dialog #-------------------------------------- self.actionImpactFunctionsDoc = QAction( QIcon(':/plugins/inasafe/show-impact-functions.svg'), self.tr('InaSAFE Impact Functions Browser'), self.iface.mainWindow()) self.actionImpactFunctionsDoc.setStatusTip( self.tr('Open InaSAFE Impact Functions Browser')) self.actionImpactFunctionsDoc.setWhatsThis( self.tr('Open InaSAFE Impact Functions Browser')) QObject.connect(self.actionImpactFunctionsDoc, SIGNAL('triggered()'), self.show_function_browser) self.add_action(self.actionImpactFunctionsDoc) # Short cut for Open Impact Functions Doc self.keyAction = QAction("Test Plugin", self.iface.mainWindow()) self.iface.registerMainWindowAction(self.keyAction, "F7") QObject.connect(self.keyAction, SIGNAL("triggered()"), self.shortcut_f7) #--------------------------------------- # Create action for minimum needs dialog #--------------------------------------- self.actionMinimumNeeds = QAction( QIcon(':/plugins/inasafe/show-minimum-needs.svg'), self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow()) self.actionMinimumNeeds.setStatusTip( self.tr('Open InaSAFE minimum needs tool')) self.actionMinimumNeeds.setWhatsThis( self.tr('Open InaSAFE minimum needs tool')) QObject.connect(self.actionMinimumNeeds, SIGNAL('triggered()'), self.show_minimum_needs) self.add_action(self.actionMinimumNeeds) #--------------------------------------- # Create action for converter dialog #--------------------------------------- self.actionConverter = QAction( QIcon(':/plugins/inasafe/show-converter-tool.svg'), self.tr('InaSAFE Converter'), self.iface.mainWindow()) self.actionConverter.setStatusTip(self.tr('Open InaSAFE Converter')) self.actionConverter.setWhatsThis(self.tr('Open InaSAFE Converter')) QObject.connect(self.actionConverter, SIGNAL('triggered()'), self.show_shakemap_importer) self.add_action(self.actionConverter) #--------------------------------------- # Create action for batch runner dialog #--------------------------------------- self.actionBatchRunner = QAction( QIcon(':/plugins/inasafe/show-batch-runner.svg'), self.tr('InaSAFE Batch Runner'), self.iface.mainWindow()) self.actionBatchRunner.setStatusTip( self.tr('Open InaSAFE Batch Runner')) self.actionBatchRunner.setWhatsThis( self.tr('Open InaSAFE Batch Runner')) QObject.connect(self.actionBatchRunner, SIGNAL('triggered()'), self.show_batch_runner) self.add_action(self.actionBatchRunner) #--------------------------------------- # Create action for batch runner dialog #--------------------------------------- self.actionSaveScenario = QAction( QIcon(':/plugins/inasafe/save-as-scenario.svg'), self.tr('Save current scenario'), self.iface.mainWindow()) myMessage = self.tr('Save current scenario to text file') self.actionSaveScenario.setStatusTip(myMessage) self.actionSaveScenario.setWhatsThis(myMessage) self.actionSaveScenario.triggered.connect(self.save_scenario) self.add_action(self.actionSaveScenario) #-------------------------------------- # Create action for import OSM Dialog #-------------------------------------- self.actionImportDlg = QAction( QIcon(':/plugins/inasafe/show-osm-download.svg'), self.tr('InaSAFE OpenStreetMap Downloader'), self.iface.mainWindow()) self.actionImportDlg.setStatusTip( self.tr('InaSAFE OpenStreetMap Downloader')) self.actionImportDlg.setWhatsThis( self.tr('InaSAFE OpenStreetMap Downloader')) QObject.connect(self.actionImportDlg, SIGNAL('triggered()'), self.show_osm_downloader) self.add_action(self.actionImportDlg) #-------------------------------------- # create dockwidget and tabify it with the legend #-------------------------------------- self.dockWidget = Dock(self.iface) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget) myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend') if myLegendTab: self.iface.mainWindow().tabifyDockWidget(myLegendTab, self.dockWidget) self.dockWidget.raise_() # # Hook up a slot for when the dock is hidden using its close button # or view-panels # QObject.connect(self.dockWidget, SIGNAL("visibilityChanged (bool)"), self.toggle_inasafe_action) # pylint: disable=W0201 def clear_modules(self): """Unload inasafe functions and try to return QIGS to before InaSAFE. """ from safe.impact_functions import core core.unload_plugins() # next lets force remove any inasafe related modules myModules = [] for myModule in sys.modules: if 'inasafe' in myModule: # Check if it is really one of our modules i.e. exists in the # plugin directory myTokens = myModule.split('.') myPath = '' for myToken in myTokens: myPath += os.path.sep + myToken myParent = os.path.abspath( os.path.join(__file__, os.path.pardir, os.path.pardir)) myFullPath = os.path.join(myParent, myPath + '.py') if os.path.exists(os.path.abspath(myFullPath)): LOGGER.debug('Removing: %s' % myModule) myModules.append(myModule) for myModule in myModules: del (sys.modules[myModule]) for myModule in sys.modules: if 'inasafe' in myModule: print myModule # Lets also clean up all the path additions that were made myPackagePath = os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % myPackagePath) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if myPackagePath not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.mainWindow().removeDockWidget(self.dockWidget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dockWidget.setVisible(False) self.dockWidget.destroy() QObject.disconnect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layer_changed) self.clear_modules() def toggle_inasafe_action(self, checked): """Check or uncheck the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.actionDock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dockWidget.isVisible(): self.dockWidget.setVisible(False) else: self.dockWidget.setVisible(True) self.dockWidget.raise_() def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.minimum_needs import MinimumNeeds myDialog = MinimumNeeds(self.iface.mainWindow()) myDialog.show() def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.options_dialog import OptionsDialog myDialog = OptionsDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.show() def show_keywords_editor(self): """Show the keywords editor.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.keywords_dialog import KeywordsDialog if self.iface.activeLayer() is None: return myDialog = KeywordsDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.setModal(True) myDialog.show() def show_function_browser(self): """Show the impact function browser tool.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.function_browser import FunctionBrowser myDialog = FunctionBrowser(self.iface.mainWindow()) myDialog.setModal(True) myDialog.show() def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.shakemap_importer import ShakemapImporter myDialog = ShakemapImporter(self.iface.mainWindow()) myDialog.show() def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe_qgis.tools.osm_downloader import OsmDownloader dialog = OsmDownloader(self.iface.mainWindow(), self.iface) dialog.setModal(True) dialog.show() def show_batch_runner(self): """Show the batch runner dialog.""" from safe_qgis.batch.batch_dialog import BatchDialog myDialog = BatchDialog(self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.setModal(True) myDialog.show() def save_scenario(self): """Save current scenario to text file,""" self.dockWidget.save_current_scenario() def reset_dock(self): """Reset the dock to its default state.""" self.dockWidget.get_layers() def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if layer is None: self.actionKeywordsDialog.setEnabled(False) else: self.actionKeywordsDialog.setEnabled(True) self.dockWidget.layer_changed(layer) def shortcut_f7(self): '''Executed when user press F7 - will show the shakemap importer.''' self.show_shakemap_importer()
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 = SkaneTrafikenDialog() 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
class StartNotSimple: def __init__(self, iface): self.iface = iface self.tableSchema = 'edgv' self.geometryColumn = 'geom' self.keyColumn = 'id' def initGui(self): # cria uma ação que iniciará a configuração do plugin pai = self.iface.mainWindow() icon_path = ':/plugins/StartNotSimple/icon.png' self.action = QAction (QIcon (icon_path),u"Acessa banco de dados para revisão de Geometria Simples", pai) self.action.setObjectName ("Stard database") self.action.setStatusTip(None) self.action.setWhatsThis(None) self.action.triggered.connect(self.run) # Adicionar o botão icone self.iface.addToolBarIcon (self.action) #Cria uma nova toolbar #self.toolbar = self.iface.addToolBar(u'Validation Tool') #self.toolbar.addAction(self.action) def unload(self): # remove o item de ícone do QGIS GUI. self.iface.removeToolBarIcon (self.action) def run(self): ################################## ###### PEGA A LAYER ATIVA ######## ################################## layer = self.iface.activeLayer() if not layer: self.iface.messageBar().pushMessage("Erro", u"Esperando uma Active Layer!", level=QgsMessageBar.CRITICAL, duration=4) return if layer.featureCount() == 0: self.iface.messageBar().pushMessage("Erro", u"a camada não possui feições!", level=QgsMessageBar.CRITICAL, duration=4) return parametros = layer.source().split(" ") # recebe todos os parametros em uma lista ( senha, porta, password etc..) #################################### ###### INICIANDO CONEXÃO DB ######## #################################### # Outra opção para isso, seria usar ex: self.dbname.. self.host.. etc.. direto dentro do laço for. dbname = "" host = "" port = 0 user = "" password = "" for i in parametros: part = i.split("=") # Recebe os parametros guardados na própria Layer if "dbname" in part[0]: dbname = part[1].replace("'", "") elif "host" in part[0]: host = part[1].replace("'", "") elif "port" in part[0]: port = int(part[1].replace("'", "")) elif "user" in part[0]: user = part[1].replace("'", "") elif "password" in part[0]: password = part[1].split("|")[0].replace("'", "") print dbname, host, port, user, password # Testa se os parametros receberam os valores pretendidos, caso não, apresenta a mensagem informando.. if len(dbname) == 0 or len(host) == 0 or port == 0 or len(user) == 0 or len(password) == 0: self.iface.messageBar().pushMessage("Erro", u'Um dos parametros não foram devidamente recebidos!', level=QgsMessageBar.CRITICAL, duration=4) return #################################### #### SETA VALORES DE CONEXÃO DB #### #################################### connection = QSqlDatabase.addDatabase('QPSQL') connection.setHostName(host) connection.setPort(port) connection.setUserName(user) connection.setPassword(password) connection.setDatabaseName(dbname) if not connection.isOpen(): # Testa se a conexão esta recebendo os parametros adequadamente. if not connection.open(): print 'Error connecting to database!' self.iface.messageBar().pushMessage("Erro", u'Error connecting to database!', level=QgsMessageBar.CRITICAL, duration=4) print connection.lastError().text() return #################################### ###### CRIAÇÃO DE MEMORY LAYER ##### #################################### layerCrs = layer.crs().authid() # Passa o formato (epsg: numeros) flagsLayerName = layer.name() + "_flags" flagsLayerExists = False for l in QgsMapLayerRegistry.instance().mapLayers().values(): # Recebe todas as camadas que estão abertas if l.name() == flagsLayerName: # ao encontrar o nome pretendido.. self.flagsLayer = l # flagslayer vai receber o nome.. self.flagsLayerProvider = l.dataProvider() flagsLayerExists = True # se encontrado os parametros buscados, recebe True. break if flagsLayerExists == False: # se não encontrado os parametros buscados, recebe False. tempString = "Point?crs=" tempString += str(layerCrs) self.flagsLayer = QgsVectorLayer(tempString, flagsLayerName, "memory") self.flagsLayerProvider = self.flagsLayer.dataProvider() self.flagsLayerProvider.addAttributes([QgsField("id", QVariant.Int), QgsField("geomId", QVariant.String), QgsField("motivo", QVariant.String)]) self.flagsLayer.updateFields() self.flagsLayer.startEditing() ids = [feat.id() for feat in self.flagsLayer.getFeatures()] self.flagsLayer.deleteFeatures(ids) self.flagsLayer.commitChanges() lista_fid = [] # Iniciando lista for f in layer.getFeatures(): lista_fid.append(str(f.id())) # Guarda na lista. A lista de Feature ids passa tipo "int", foi convertido e guardado como "str". source = layer.source().split(" ") self.tableName = " " # Inicia vazio layerExistsInDB = False for i in source: if "table=" in i or "layername=" in i: # Se encontrar os atributos pretendidos dentre todos do for self.tableName = source[source.index(i)].split(".")[1] # Faz split em ponto e pega a segunda parte. self.tableName = self.tableName.replace('"', '') layerExistsInDB = True break if layerExistsInDB == False: self.iface.messageBar().pushMessage("Erro", u"Provedor da camada corrente não provem do banco de dados!", level=QgsMessageBar.CRITICAL, duration=4) return ############################## #### Busca através do SQL #### ############################## sql = """select foo."{3}" as "{3}", ST_AsText(ST_MULTI(st_startpoint(foo."{2}"))) as "{2}" from ( select "{3}" as "{3}", (ST_Dump(ST_Node(ST_SetSRID(ST_MakeValid("{2}"),ST_SRID("{2}"))))).geom as "{2}" from "{0}"."{1}" where ST_IsSimple("{2}") = 'f' and {3} in ({4})) as foo where st_equals(st_startpoint(foo."{2}"),st_endpoint(foo."{2}"))""".format(self.tableSchema, self.tableName, self.geometryColumn, self.keyColumn, ",".join(lista_fid)) query = QSqlQuery(sql) self.flagsLayer.startEditing() flagCount = 0 # iniciando contador que será referência para os IDs da camada de memória. listaFeatures = [] while query.next(): id = query.value(0) # recebendo valores buscados no sql local = query.value(1) # recebendo valores buscados no sql motivo = query.value(2) print local, id, motivo flagId = flagCount flagFeat = QgsFeature() flagFeat.setFields(self.flagsLayer.fields()) # passa quais atributos serão usados. flagGeom = QgsGeometry.fromWkt(local) # passa o local onde foi localizado o erro. flagFeat.setGeometry(flagGeom) flagFeat.setAttribute(0, flagId) # insere o id definido para a coluna 0 da layer de memória. flagFeat.setAttribute(1, id) # insere o id da geometria para a coluna 1 da layer de memória. flagFeat.setAttribute(2, u"A geometria não é simples.") listaFeatures.append(flagFeat) flagCount += 1 # incrementando o contador a cada iteração self.flagsLayerProvider.addFeatures(listaFeatures) self.flagsLayer.commitChanges() # Aplica as alterações à camada. QgsMapLayerRegistry.instance().addMapLayer(self.flagsLayer) # Adicione a camada no mapa if flagCount == 0: QgsMapLayerRegistry.instance().removeMapLayer(self.flagsLayer.id()) self.iface.messageBar().pushMessage("Aviso", u"Não foi encontrado Flags em \"" + layer.name() + "\" !", level=QgsMessageBar.CRITICAL, duration=4) return if len(query.lastError().text()) == 1: self.iface.messageBar().pushMessage("Aviso", "foram geradas " + str(flagCount) + " flags para a camada \"" + layer.name() + "\" !", level=QgsMessageBar.INFO, duration=4) else: self.iface.messageBar().pushMessage("Erro", u"a geração de flags falhou!", level=QgsMessageBar.CRITICAL, duration=4) print query.lastError().text()
class MetaSearchPlugin(object): """base plugin""" def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.dialog = None self.web_menu = '&MetaSearch' LOGGER.debug('Setting up i18n') # TODO: does this work for locales like: pt_BR ? locale_name = QSettings().value("locale/userLocale")[0:2] # this one below does not pick up when you load QGIS with --lang param # locale_name = str(QLocale.system().name()).split('_')[0] LOGGER.debug('Locale name: %s', locale_name) # load if exists tr_file = os.path.join(self.context.ppath, 'locale', locale_name, 'LC_MESSAGES', 'ui.qm') if os.path.exists(tr_file): self.translator = QTranslator() result = self.translator.load(tr_file) if not result: msg = 'Failed to load translation: %s' % tr_file LOGGER.error(msg) raise RuntimeError(msg) QCoreApplication.installTranslator(self.translator) LOGGER.debug(QCoreApplication.translate('MetaSearch', 'Translation loaded: %s' % tr_file)) def initGui(self): """startup""" # run run_icon = QIcon('%s/%s' % (self.context.ppath, 'images/MetaSearch.png')) self.action_run = QAction(run_icon, 'MetaSearch', self.iface.mainWindow()) self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch', 'MetaSearch plugin')) self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch', 'Search Metadata Catalogues')) self.action_run.triggered.connect(self.run) self.iface.addToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png')) self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow()) self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help')) self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch')) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface) def unload(self): """teardown""" # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_run) self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.iface.removeToolBarIcon(self.action_run) self.iface.removeToolBarIcon(self.action_help) def run(self): """open MetaSearch""" self.dialog.exec_() def help(self): """open help in user's default web browser""" open_url(self.context.metadata.get('general', 'homepage'))
class QGISEducation: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.constants = TerreImageConstant() self.constants.iface = self.iface self.constants.canvas = self.iface.mapCanvas() self.constants.legendInterface = self.iface.legendInterface() def initGui(self): """ Initialisation on the widget interface """ # Create action that will start plugin configuration self.action = QAction( QIcon(":/plugins/qgiseducation/img/icon.png"), u"Terre Image", self.iface.mainWindow()) self.action.setWhatsThis("Terre Image") # connect the action to the run method self.action.triggered.connect(self.run) self.aboutAction = QAction(QIcon(":/plugins/DockableMirrorMap/icons/about.png"), "About", self.iface.mainWindow()) QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u"&TerreImage", self.action) self.iface.addPluginToMenu("TerreImage", self.aboutAction) self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None QObject.connect(self.iface, SIGNAL("projectRead()"), self.onProjectLoaded) QObject.connect(QgsProject.instance(), SIGNAL("writeProject(QDomDocument &)"), self.onWriteProject) QObject.connect(self.iface, SIGNAL("newProjectCreated()"), self.newProject) def do_display_one_band(self, who, qgis_layer, working_directory, mirror_tool): logger.debug("who" + str(who)) # manage_QGIS.display_one_band(self.qgis_education_manager.layer, who, self.iface) if qgis_layer: my_process = TerreImageDisplay(self.iface, working_directory, ProcessingManager().working_layer, mirror_tool, who, None, qgis_layer) else: my_process = TerreImageDisplay(self.iface, working_directory, ProcessingManager().working_layer, mirror_tool, who) # ProcessingManager().add_processing(my_process) self.educationWidget.set_combobox_histograms() def unload(self): """ Defines the unload of the plugin """ self.unload_interface() # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&TerreImage", self.action) self.iface.removeToolBarIcon(self.action) def unload_interface(self): if self.qgisedudockwidget is not None and self.educationWidget is not None: self.qgisedudockwidget.close() self.educationWidget.disconnectP() # run method that performs all the real work def run(self): """ Defines the behavior of the plugin """ timeBegin = time.time() # self.educationWidget.set_working_message(True) self.iface.newProject(True) # self.qgis_education_manager = TerreImageManager(self.iface) # _, bands = self.qgis_education_manager.set_current_layer( ) _, bands, working_dir = terre_image_utils.set_current_layer(self.iface) timeEnd = time.time() timeExec = timeEnd - timeBegin logger.info("temps de chargement: " + str(timeExec)) self.show_education_widget(bands, working_dir) # self.educationWidget.set_working_message(False) def show_education_widget(self, bands, working_dir): if ProcessingManager().working_layer and bands: if not self.dockOpened: # create the widget to display information self.educationWidget = QGISEducationWidget(self.iface) QObject.connect(self.educationWidget, SIGNAL("terminated()"), self.unload_interface) # self.educationWidget.qgis_education_manager = self.qgis_education_manager self.educationWidget.qgis_education_manager = TerreImageManager(self.iface) self.educationWidget.qgis_education_manager.working_directory = working_dir self.educationWidget.lineEdit_working_dir.setText(working_dir) self.educationWidget.qgis_education_manager.classif_tool.set_layers(ProcessingManager().get_qgis_working_layers(), ProcessingManager().working_layer.get_qgis_layer(), ProcessingManager().working_layer.band_invert) self.educationWidget.qgis_education_manager.classif_tool.set_directory(working_dir) self.educationWidget.qgis_education_manager.classif_tool.setupUi() # create the dockwidget with the correct parent and add the valuewidget self.qgisedudockwidget = Terre_Image_Main_Dock_widget("Terre Image", self.iface.mainWindow(), self.iface) self.qgisedudockwidget.setObjectName("Terre Image") self.qgisedudockwidget.setWidget(self.educationWidget) QObject.connect(self.qgisedudockwidget, SIGNAL("closed(PyQt_PyObject)"), self.close_dock) # add the dockwidget to iface self.iface.addDockWidget(Qt.RightDockWidgetArea, self.qgisedudockwidget) self.educationWidget.set_comboBox_sprectral_band_display() text = "Plan R <- BS_PIR \nPlan V <- BS_R \nPlan B <- BS_V" self.qgisedudockwidget.show() self.dockOpened = True def about(self): from terre_image_about import DlgAbout DlgAbout(self.iface.mainWindow()).exec_() def close_dock(self, object): self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None if self.iface.legendInterface().layers() != []: self.iface.newProject() def newProject(self): for item in self.iface.mapCanvas().scene().items(): if isinstance(item, QgsRubberBand): item.reset(QGis.Point) if self.educationWidget is not None: self.educationWidget.disconnect_interface() if self.qgisedudockwidget is not None: self.qgisedudockwidget.close() self.educationWidget.disconnectP() self.dockOpened = False self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None def onWriteProject(self, domproject): if ProcessingManager().working_layer is None: return # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer", self.qgis_education_manager.layer.source_file ) # # write band orders # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_bands", str(self.qgis_education_manager.layer.bands) ) # logger.debug( str(self.qgis_education_manager.layer.bands) ) # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_type", self.qgis_education_manager.layer.type ) # QgsProject.instance().writeEntry( "QGISEducation", "/working_directory", self.qgis_education_manager.working_directory ) QgsProject.instance().writeEntry("QGISEducation", "/working_layer", ProcessingManager().working_layer.source_file) # write band orders QgsProject.instance().writeEntry("QGISEducation", "/working_layer_bands", str(ProcessingManager().working_layer.bands)) logger.debug(str(ProcessingManager().working_layer.bands)) QgsProject.instance().writeEntry("QGISEducation", "/working_layer_type", ProcessingManager().working_layer.type) QgsProject.instance().writeEntry("QGISEducation", "/working_directory", self.educationWidget.qgis_education_manager.working_directory) p = [] for process in ProcessingManager().get_processings(): p.append((process.processing_name, process.output_working_layer.get_source())) # print "process", p QgsProject.instance().writeEntry("QGISEducation", "/process", str(p)) QgsProject.instance().writeEntry("QGISEducation", "/index_group", self.constants.index_group) if "Angle Spectral" in ProcessingManager().get_processings_name(): # delete rubberband for item in self.iface.mapCanvas().scene().items(): # item is a rubberband if isinstance(item, QgsRubberBand): # get point if item.size() > 0: point = item.getPoint(0) # print point QgsProject.instance().writeEntryDouble("QGISEducation", "/angle_spectral_point_x", point.x()) QgsProject.instance().writeEntryDouble("QGISEducation", "/angle_spectral_point_y", point.y()) p = TerreImageParamaters() if p.is_complete(): QgsProject.instance().writeEntryDouble("QGISEducation", "/red_x_min", p.red_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/red_x_max", p.red_max) QgsProject.instance().writeEntryDouble("QGISEducation", "/green_x_min", p.green_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/green_x_max", p.green_max) QgsProject.instance().writeEntryDouble("QGISEducation", "/blue_x_min", p.blue_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/blue_x_max", p.blue_max) def onProjectLoaded(self): # does not work stops the project reading. # should desactivate all interface and read the project again # self.newProject( True ) # restore mirrors? wl, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer") if not ok or wl == "": pass if not wl == "": bands, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer_bands") logger.debug("is ok" + str(ok)) logger.debug(bands) # working_layer = WorkingLayer(wl, None, bands) # TODO interpreter bands type, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer_type") working_dir, ok = QgsProject.instance().readEntry("QGISEducation", "/working_directory") layer, bands = terre_image_utils.restore_working_layer(wl, eval(bands), type) ProcessingManager().working_layer = layer self.show_education_widget(bands, working_dir) # self.qgis_education_manager = TerreImageManager( self.iface ) # self.qgis_education_manager.restore_processing_manager(wl, eval(bands), type, working_dir) # if self.qgis_education_manager: process, ok = QgsProject.instance().readEntry("QGISEducation", "/process") logger.debug(eval(process)) index_group, ok = QgsProject.instance().readDoubleEntry("QGISEducation", "/index_group") self.constants.index_group = int(float(index_group)) process = eval(process) for qgis_layer in self.iface.legendInterface().layers(): # print "layer loading ", qgis_layer.name() if qgis_layer.name() in [ "NDVI", "NDTI", "Indice de brillance", "KMEANS" ]: process = TerreImageProcessing(self.iface, working_dir, ProcessingManager().working_layer, self.educationWidget.qgis_education_manager.mirror_map_tool, qgis_layer.name(), None, qgis_layer) elif "Angle Spectral" in qgis_layer.name(): process = TerreImageProcessing(self.iface, working_dir, ProcessingManager().working_layer, self.educationWidget.qgis_education_manager.mirror_map_tool, qgis_layer.name(), qgis_layer.source(), qgis_layer) # ProcessingManager().add_processing(process) elif "couleur_naturelles" in qgis_layer.name(): try: self.do_display_one_band('nat', qgis_layer, working_dir, self.educationWidget.qgis_education_manager.mirror_map_tool) except AttributeError: QMessageBox.warning(None , "Erreur", u'Le projet ne peut être lu. Essayez de créer un projet vierge, puis de réouvrir le projet souhaité.', QMessageBox.Ok) # self.newProject( ) return None # ProcessingManager().add_display( process ) else: corres = { 'red':"_bande_rouge", 'green':"_bande_verte", 'blue':"_bande_bleue", 'pir':"_bande_pir", 'mir':"_bande_mir", "nat":"_couleurs_naturelles" } result = [x for x in corres if qgis_layer.name().endswith(corres[x])] # print result if result: # print "the couleur", result[0] try: self.do_display_one_band(result[0], qgis_layer, working_dir, self.educationWidget.qgis_education_manager.mirror_map_tool) except AttributeError: QMessageBox.warning(None , "Erreur", u'Le projet ne peut être lu. Essayez de créer un projet vierge, puis de réouvrir le projet souhaité.', QMessageBox.Ok) # self.newProject( ) return None # ProcessingManager().add_display( process ) angle_spectral_point_x, ok_x = QgsProject.instance().readDoubleEntry("QGISEducation", "/angle_spectral_point_x") angle_spectral_point_y, ok_y = QgsProject.instance().readDoubleEntry("QGISEducation", "/angle_spectral_point_y") # print "angle_spectral_point_x, angle_spectral_point_y", angle_spectral_point_x, angle_spectral_point_y if ok_x and ok_y: # print "angle_spectral_point_x, angle_spectral_point_y", angle_spectral_point_x, angle_spectral_point_y p = ProcessingManager().processing_from_name("Angle Spectral") if p: rubberband = p[0].rubberband rubberband.setWidth(10) rubberband.setColor(QColor(Qt.yellow)) rubberband.addPoint(QgsPoint(float(angle_spectral_point_x), float(angle_spectral_point_y))) p = TerreImageParamaters() p.red_min = QgsProject.instance().readDoubleEntry("QGISEducation", "/red_x_min")[0] p.red_max = QgsProject.instance().readDoubleEntry("QGISEducation", "/red_x_max")[0] p.green_min = QgsProject.instance().readDoubleEntry("QGISEducation", "/green_x_min")[0] p.green_max = QgsProject.instance().readDoubleEntry("QGISEducation", "/green_x_max")[0] p.blue_min = QgsProject.instance().readDoubleEntry("QGISEducation", "/blue_x_min")[0] p.blue_max = QgsProject.instance().readDoubleEntry("QGISEducation", "/blue_x_max")[0] self.educationWidget.set_combobox_histograms() self.iface.mapCanvas().refresh() self.iface.mapCanvas().repaint()
class Plugin: """The QGIS interface implementation for the Risk in a box plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menubar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. Args: iface - a Quantum GIS QGisAppInterface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. Returns: None. Raises: no exceptions explicitly raised. """ # Save reference to the QGIS interface self.iface = iface self.translator = None self.setupI18n() #print self.tr('InaSAFE') utilities.setupLogger() #noinspection PyArgumentList def setupI18n(self, thePreferredLocale=None): """Setup internationalisation for the plugin. See if QGIS wants to override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. Args: thePreferredLocale - optional parameter which if set will override any other way of determining locale.. Returns: None. Raises: TranslationLoadException """ myOverrideFlag = QSettings().value( 'locale/overrideFlag', QVariant(False)).toBool() if thePreferredLocale is not None: myLocaleName = thePreferredLocale elif myOverrideFlag: myLocaleName = QSettings().value('locale/userLocale', QVariant('')).toString() else: myLocaleName = QLocale.system().name() # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc myLocaleName = str(myLocaleName).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(myLocaleName) LOGGER.debug('%s %s %s %s' % ( thePreferredLocale, myOverrideFlag, QLocale.system().name(), os.environ['LANG'])) myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) myTranslationPath = os.path.join( myRoot, 'safe_qgis', 'i18n', 'inasafe_' + str(myLocaleName) + '.qm') if os.path.exists(myTranslationPath): self.translator = QTranslator() myResult = self.translator.load(myTranslationPath) if not myResult: myMessage = 'Failed to load translation for %s' % myLocaleName raise TranslationLoadError(myMessage) QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( myTranslationPath, os.path.exists(myTranslationPath))) def tr(self, theString): """We implement this ourself since we do not inherit QObject. Args: theString - string for translation. Returns: Translated version of theString. Raises: no exceptions explicitly raised. """ return QCoreApplication.translate('Plugin', theString) #noinspection PyCallByClass def initGui(self): """Gui initialisation procedure (for QGIS plugin api). This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Import dock here as it needs to be imported AFTER i18n is set up from safe_qgis.dock import Dock self.dockWidget = None #-------------------------------------- # Create action for plugin dockable window (show/hide) #-------------------------------------- # pylint: disable=W0201 self.actionDock = QAction( QIcon(':/plugins/inasafe/icon.svg'), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.actionDock.setObjectName('InaSAFEDockToggle') self.actionDock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.actionDock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.actionDock.setCheckable(True) self.actionDock.setChecked(True) QObject.connect( self.actionDock, SIGNAL('triggered()'), self.showHideDockWidget) # add to plugin toolbar self.iface.addToolBarIcon(self.actionDock) # add to plugin menu self.iface.addPluginToMenu( self.tr('InaSAFE'), self.actionDock) #-------------------------------------- # Create action for keywords editor #-------------------------------------- self.actionKeywordsDialog = QAction( QIcon(':/plugins/inasafe/show-keyword-editor.svg'), self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow()) self.actionKeywordsDialog.setStatusTip(self.tr( 'Open InaSAFE keywords editor')) self.actionKeywordsDialog.setWhatsThis(self.tr( 'Open InaSAFE keywords editor')) self.actionKeywordsDialog.setEnabled(False) QObject.connect( self.actionKeywordsDialog, SIGNAL('triggered()'), self.showKeywordsEditor) self.iface.addToolBarIcon(self.actionKeywordsDialog) self.iface.addPluginToMenu( self.tr('InaSAFE'), self.actionKeywordsDialog) #-------------------------------------- # Create action for reset icon #-------------------------------------- self.actionResetDock = QAction( QIcon(':/plugins/inasafe/reset-dock.svg'), self.tr('Reset Dock'), self.iface.mainWindow()) self.actionResetDock.setStatusTip(self.tr( 'Reset the InaSAFE Dock')) self.actionResetDock.setWhatsThis(self.tr( 'Reset the InaSAFE Dock')) QObject.connect( self.actionResetDock, SIGNAL('triggered()'), self.resetDock) self.iface.addToolBarIcon(self.actionResetDock) self.iface.addPluginToMenu( self.tr('InaSAFE'), self.actionResetDock) #-------------------------------------- # Create action for options dialog #-------------------------------------- self.actionOptions = QAction( QIcon(':/plugins/inasafe/configure-inasafe.svg'), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.actionOptions.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.actionOptions.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) QObject.connect( self.actionOptions, SIGNAL('triggered()'), self.showOptions) self.iface.addToolBarIcon(self.actionOptions) self.iface.addPluginToMenu( self.tr('InaSAFE'), self.actionOptions) #-------------------------------------- # Create action for impact functions doc dialog #-------------------------------------- self.actionImpactFunctionsDoc = QAction( QIcon(':/plugins/inasafe/show-impact-functions.svg'), self.tr('InaSAFE Impact Functions Browser'), self.iface.mainWindow()) self.actionImpactFunctionsDoc.setStatusTip(self.tr( 'Open InaSAFE Impact Functions Browser')) self.actionImpactFunctionsDoc.setWhatsThis(self.tr( 'Open InaSAFE Impact Functions Browser')) QObject.connect( self.actionImpactFunctionsDoc, SIGNAL('triggered()'), self.showImpactFunctionsDoc) self.iface.addToolBarIcon(self.actionImpactFunctionsDoc) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionImpactFunctionsDoc) # Short cut for Open Impact Functions Doc self.keyAction = QAction("Test Plugin", self.iface.mainWindow()) self.iface.registerMainWindowAction(self.keyAction, "F7") QObject.connect(self.keyAction, SIGNAL("triggered()"), self.keyActionF7) #--------------------------------------- # Create action for minimum needs dialog #--------------------------------------- self.actionMinimumNeeds = QAction( QIcon(':/plugins/inasafe/show-minimum-needs.svg'), self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow()) self.actionMinimumNeeds.setStatusTip(self.tr( 'Open InaSAFE minimum needs tool')) self.actionMinimumNeeds.setWhatsThis(self.tr( 'Open InaSAFE minimum needs tool')) QObject.connect(self.actionMinimumNeeds, SIGNAL('triggered()'), self.showMinimumNeeds) self.iface.addToolBarIcon(self.actionMinimumNeeds) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionMinimumNeeds) #--------------------------------------- # Create action for converter dialog #--------------------------------------- self.actionConverter = QAction( QIcon(':/plugins/inasafe/show-minimum-needs.svg'), self.tr('InaSAFE Converter'), self.iface.mainWindow()) self.actionConverter.setStatusTip(self.tr( 'Open InaSAFE Converter')) self.actionConverter.setWhatsThis(self.tr( 'Open InaSAFE Converter')) QObject.connect(self.actionConverter, SIGNAL('triggered()'), self.showConverter) self.iface.addToolBarIcon(self.actionConverter) self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionConverter) #-------------------------------------- # Create action for import OSM Dialog #-------------------------------------- self.actionImportDlg = QAction( QIcon(':/plugins/inasafe/osm-download.png'), self.tr('InaSAFE OpenStreetMap Downloader'), self.iface.mainWindow()) self.actionImportDlg.setStatusTip(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.actionImportDlg.setWhatsThis(self.tr( 'InaSAFE OpenStreetMap Downloader')) QObject.connect( self.actionImportDlg, SIGNAL('triggered()'), self.showImportDlg) self.iface.addToolBarIcon(self.actionImportDlg) self.iface.addPluginToMenu( self.tr('InaSAFE'), self.actionImportDlg) #-------------------------------------- # create dockwidget and tabify it with the legend #-------------------------------------- self.dockWidget = Dock(self.iface) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget) myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend') if myLegendTab: self.iface.mainWindow().tabifyDockWidget( myLegendTab, self.dockWidget) self.dockWidget.raise_() # # Hook up a slot for when the current layer is changed # QObject.connect( self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged) # # Hook up a slot for when the dock is hidden using its close button # or view-panels # QObject.connect( self.dockWidget, SIGNAL("visibilityChanged (bool)"), self.toggleActionDock) # pylint: disable=W0201 def unload(self): """Gui breakdown procedure (for QGIS plugin api). This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Remove the plugin menu item and icon self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionDock) self.iface.removeToolBarIcon(self.actionDock) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionKeywordsDialog) self.iface.removeToolBarIcon(self.actionKeywordsDialog) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionResetDock) self.iface.removeToolBarIcon(self.actionResetDock) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionOptions) self.iface.removeToolBarIcon(self.actionOptions) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionMinimumNeeds) self.iface.removeToolBarIcon(self.actionMinimumNeeds) self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionImpactFunctionsDoc) self.iface.removeToolBarIcon(self.actionImpactFunctionsDoc) self.iface.mainWindow().removeDockWidget(self.dockWidget) self.dockWidget.setVisible(False) self.dockWidget.destroy() QObject.disconnect( self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged) def toggleActionDock(self, checked): """check or uncheck the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels .. see also:: :func:`Plugin.initGui`. Args: checked - if actionDock has to be checked or not Returns: None. Raises: no exceptions explicitly raised. """ self.actionDock.setChecked(checked) # Run method that performs all the real work def showHideDockWidget(self): """Show or hide the dock widget. This slot is called when the user clicks the toolbar icon or menu item associated with this plugin. It will hide or show the dock depending on its current state. .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ if self.dockWidget.isVisible(): self.dockWidget.setVisible(False) else: self.dockWidget.setVisible(True) self.dockWidget.raise_() def showMinimumNeeds(self): """Show the minimum needs dialog. This slot is called when the user clicks the minimum needs toolbar icon or menu item associated with this plugin. .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.minimum_needs import MinimumNeeds myDialog = MinimumNeeds(self.iface.mainWindow()) myDialog.show() def showOptions(self): """Show the options dialog. This slot is called when the user clicks the options toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.options_dialog import OptionsDialog myDialog = OptionsDialog( self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.show() def showKeywordsEditor(self): """Show the keywords editor. This slot is called when the user clicks the keyword editor toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.keywords_dialog import KeywordsDialog if self.iface.activeLayer() is None: return myDialog = KeywordsDialog( self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.setModal(True) myDialog.show() def showImpactFunctionsDoc(self): """Show the impact function doc This slot is called when the user clicks the impact functions toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.impact_functions_doc import ImpactFunctionsDoc myDialog = ImpactFunctionsDoc(self.iface.mainWindow()) myDialog.show() def showConverter(self): """Show the converter dialog. This slot is called when the user clicks the impact functions toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # import here only so that it is AFTER i18n set up from safe_qgis.converter_dialog import ConverterDialog myDialog = ConverterDialog(self.iface.mainWindow()) myDialog.show() def showImportDlg(self): from safe_qgis.import_dialog import ImportDialog dlg = ImportDialog(self.iface.mainWindow(), self.iface) dlg.setModal(True) dlg.show() def resetDock(self): """Reset the dock to its default state. This slot is called when the user clicks the reset icon in the toolbar or the reset menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ self.dockWidget.getLayers() def layerChanged(self, theLayer): """Enable or disable the keywords editor icon. This slot is called when the user clicks the keyword editor toolbar icon or menu item associated with this plugin .. see also:: :func:`Plugin.initGui`. Args: None. Returns: None. Raises: no exceptions explicitly raised. """ if theLayer is None: self.actionKeywordsDialog.setEnabled(False) else: self.actionKeywordsDialog.setEnabled(True) self.dockWidget.layerChanged(theLayer) def keyActionF7(self): '''Executed when user press F7''' self.showConverter()
class MetaSearchPlugin(object): """base plugin""" def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.dialog = None self.web_menu = '&MetaSearch' LOGGER.debug('Setting up i18n') # TODO: does this work for locales like: pt_BR ? locale_name = QSettings().value("locale/userLocale")[0:2] # this one below does not pick up when you load QGIS with --lang param # locale_name = str(QLocale.system().name()).split('_')[0] LOGGER.debug('Locale name: %s', locale_name) # load if exists tr_file = os.path.join(self.context.ppath, 'locale', locale_name, 'LC_MESSAGES', 'ui.qm') if os.path.exists(tr_file): self.translator = QTranslator() result = self.translator.load(tr_file) if not result: msg = 'Failed to load translation: %s' % tr_file LOGGER.error(msg) raise RuntimeError(msg) QCoreApplication.installTranslator(self.translator) LOGGER.debug( QCoreApplication.translate('MetaSearch', 'Translation loaded: %s' % tr_file)) def initGui(self): """startup""" # run run_icon = QIcon('%s/%s' % (self.context.ppath, 'images/MetaSearch.png')) self.action_run = QAction(run_icon, 'MetaSearch', self.iface.mainWindow()) self.action_run.setWhatsThis( QCoreApplication.translate('MetaSearch', 'MetaSearch plugin')) self.action_run.setStatusTip( QCoreApplication.translate('MetaSearch', 'Search Metadata Catalogues')) self.action_run.triggered.connect(self.run) self.iface.addToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png')) self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow()) self.action_help.setWhatsThis( QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help')) self.action_help.setStatusTip( QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch')) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface) def unload(self): """teardown""" # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_run) self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.iface.removeToolBarIcon(self.action_run) self.iface.removeToolBarIcon(self.action_help) def run(self): """open MetaSearch""" self.dialog.exec_() def help(self): """open help in user's default web browser""" open_url(self.context.metadata.get('general', 'homepage'))
class Plugin: """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menubar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Save reference to the QGIS interface self.iface = iface self.translator = None self.toolbar = None self.actions = [] # list of all QActions we create for InaSAFE self.setup_i18n() #print self.tr('InaSAFE') custom_logging.setup_logger() # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) #noinspection PyArgumentList def setup_i18n(self, preferred_locale=None): """Setup internationalisation for the plugin. See if QGIS wants to override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param preferred_locale: If set will override any other way of determining locale. :type preferred_locale: str, None :raises: TranslationLoadException """ myOverrideFlag = QSettings().value('locale/overrideFlag', False) if preferred_locale is not None: myLocaleName = preferred_locale elif myOverrideFlag: myLocaleName = QSettings().value('locale/userLocale', '') else: myLocaleName = QLocale.system().name() # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc myLocaleName = str(myLocaleName).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(myLocaleName) LOGGER.debug('%s %s %s %s' % ( preferred_locale, myOverrideFlag, QLocale.system().name(), os.environ['LANG'])) myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) myTranslationPath = os.path.join( myRoot, 'safe_qgis', 'i18n', 'inasafe_' + str(myLocaleName) + '.qm') if os.path.exists(myTranslationPath): self.translator = QTranslator() myResult = self.translator.load(myTranslationPath) if not myResult: myMessage = 'Failed to load translation for %s' % myLocaleName raise TranslationLoadError(myMessage) # noinspection PyTypeChecker QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( myTranslationPath, os.path.exists(myTranslationPath))) 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 return QCoreApplication.translate('Plugin', message) def add_action(self, action, add_to_toolbar=True): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) #noinspection PyCallByClass def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') # Import dock here as it needs to be imported AFTER i18n is set up from safe_qgis.widgets.dock import Dock self.dockWidget = None #-------------------------------------- # Create action for plugin dockable window (show/hide) #-------------------------------------- # pylint: disable=W0201 self.actionDock = QAction( QIcon(':/plugins/inasafe/icon.svg'), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.actionDock.setObjectName('InaSAFEDockToggle') self.actionDock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.actionDock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.actionDock.setCheckable(True) self.actionDock.setChecked(True) self.actionDock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.actionDock) #-------------------------------------- # Create action for keywords editor #-------------------------------------- self.actionKeywordsDialog = QAction( QIcon(':/plugins/inasafe/show-keyword-editor.svg'), self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow()) self.actionKeywordsDialog.setStatusTip(self.tr( 'Open InaSAFE keywords editor')) self.actionKeywordsDialog.setWhatsThis(self.tr( 'Open InaSAFE keywords editor')) self.actionKeywordsDialog.setEnabled(False) self.actionKeywordsDialog.triggered.connect(self.show_keywords_editor) self.add_action(self.actionKeywordsDialog) #-------------------------------------- # Create action for reset icon #-------------------------------------- self.actionResetDock = QAction( QIcon(':/plugins/inasafe/reset-dock.svg'), self.tr('Reset Dock'), self.iface.mainWindow()) self.actionResetDock.setStatusTip(self.tr( 'Reset the InaSAFE Dock')) self.actionResetDock.setWhatsThis(self.tr( 'Reset the InaSAFE Dock')) self.actionResetDock.triggered.connect(self.reset_dock) self.add_action(self.actionResetDock) #-------------------------------------- # Create action for options dialog #-------------------------------------- self.actionOptions = QAction( QIcon(':/plugins/inasafe/configure-inasafe.svg'), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.actionOptions.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.actionOptions.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) self.actionOptions.triggered.connect(self.show_options) self.add_action(self.actionOptions) #-------------------------------------- # Create action for impact functions doc dialog #-------------------------------------- self.actionFunctionBrowser = QAction( QIcon(':/plugins/inasafe/show-impact-functions.svg'), self.tr('InaSAFE Impact Functions Browser'), self.iface.mainWindow()) self.actionFunctionBrowser.setStatusTip(self.tr( 'Open InaSAFE Impact Functions Browser')) self.actionFunctionBrowser.setWhatsThis(self.tr( 'Open InaSAFE Impact Functions Browser')) self.actionFunctionBrowser.triggered.connect( self.show_function_browser) self.add_action(self.actionFunctionBrowser) # Short cut for Open Impact Functions Doc self.keyAction = QAction("Test Plugin", self.iface.mainWindow()) self.iface.registerMainWindowAction(self.keyAction, "F7") self.keyAction.triggered.connect(self.shortcut_f7) #--------------------------------------- # Create action for minimum needs dialog #--------------------------------------- self.actionMinimumNeeds = QAction( QIcon(':/plugins/inasafe/show-minimum-needs.svg'), self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow()) self.actionMinimumNeeds.setStatusTip(self.tr( 'Open InaSAFE minimum needs tool')) self.actionMinimumNeeds.setWhatsThis(self.tr( 'Open InaSAFE minimum needs tool')) self.actionMinimumNeeds.triggered.connect(self.show_minimum_needs) self.add_action(self.actionMinimumNeeds) #--------------------------------------- # Create action for converter dialog #--------------------------------------- self.actionConverter = QAction( QIcon(':/plugins/inasafe/show-converter-tool.svg'), self.tr('InaSAFE Converter'), self.iface.mainWindow()) self.actionConverter.setStatusTip(self.tr( 'Open InaSAFE Converter')) self.actionConverter.setWhatsThis(self.tr( 'Open InaSAFE Converter')) self.actionConverter.triggered.connect(self.show_shakemap_importer) self.add_action(self.actionConverter) #--------------------------------------- # Create action for batch runner dialog #--------------------------------------- self.actionBatchRunner = QAction( QIcon(':/plugins/inasafe/show-batch-runner.svg'), self.tr('InaSAFE Batch Runner'), self.iface.mainWindow()) self.actionBatchRunner.setStatusTip(self.tr( 'Open InaSAFE Batch Runner')) self.actionBatchRunner.setWhatsThis(self.tr( 'Open InaSAFE Batch Runner')) self.actionBatchRunner.triggered.connect(self.show_batch_runner) self.add_action(self.actionBatchRunner) #--------------------------------------- # Create action for batch runner dialog #--------------------------------------- self.actionSaveScenario = QAction( QIcon(':/plugins/inasafe/save-as-scenario.svg'), self.tr('Save current scenario'), self.iface.mainWindow()) myMessage = self.tr('Save current scenario to text file') self.actionSaveScenario.setStatusTip(myMessage) self.actionSaveScenario.setWhatsThis(myMessage) # noinspection PyUnresolvedReferences self.actionSaveScenario.triggered.connect(self.save_scenario) self.add_action(self.actionSaveScenario) #-------------------------------------- # Create action for import OSM Dialog #-------------------------------------- self.actionImportDlg = QAction( QIcon(':/plugins/inasafe/show-osm-download.svg'), self.tr('InaSAFE OpenStreetMap Downloader'), self.iface.mainWindow()) self.actionImportDlg.setStatusTip(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.actionImportDlg.setWhatsThis(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.actionImportDlg.triggered.connect(self.show_osm_downloader) self.add_action(self.actionImportDlg) #-------------------------------------- # create dockwidget and tabify it with the legend #-------------------------------------- self.dockWidget = Dock(self.iface) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget) myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend') if myLegendTab: self.iface.mainWindow().tabifyDockWidget( myLegendTab, self.dockWidget) self.dockWidget.raise_() # # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dockWidget.visibilityChanged.connect(self.toggle_inasafe_action) # pylint: disable=W0201 def clear_modules(self): """Unload inasafe functions and try to return QGIS to before InaSAFE. """ from safe.impact_functions import core core.unload_plugins() # next lets force remove any inasafe related modules myModules = [] for myModule in sys.modules: if 'inasafe' in myModule: # Check if it is really one of our modules i.e. exists in the # plugin directory myTokens = myModule.split('.') myPath = '' for myToken in myTokens: myPath += os.path.sep + myToken myParent = os.path.abspath(os.path.join( __file__, os.path.pardir, os.path.pardir)) myFullPath = os.path.join(myParent, myPath + '.py') if os.path.exists(os.path.abspath(myFullPath)): LOGGER.debug('Removing: %s' % myModule) myModules.append(myModule) for myModule in myModules: del (sys.modules[myModule]) for myModule in sys.modules: if 'inasafe' in myModule: print myModule # Lets also clean up all the path additions that were made myPackagePath = os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % myPackagePath) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if myPackagePath not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.mainWindow().removeDockWidget(self.dockWidget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dockWidget.setVisible(False) self.dockWidget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) self.clear_modules() def toggle_inasafe_action(self, checked): """Check or uncheck the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.actionDock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dockWidget.isVisible(): self.dockWidget.setVisible(False) else: self.dockWidget.setVisible(True) self.dockWidget.raise_() def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.minimum_needs import MinimumNeeds myDialog = MinimumNeeds(self.iface.mainWindow()) myDialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.options_dialog import OptionsDialog myDialog = OptionsDialog( self.iface, self.dockWidget, self.iface.mainWindow()) myDialog.exec_() # modal def show_keywords_editor(self): """Show the keywords editor.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.keywords_dialog import KeywordsDialog if self.iface.activeLayer() is None: return myDialog = KeywordsDialog( self.iface.mainWindow(), self.iface, self.dockWidget) myDialog.exec_() # modal def show_function_browser(self): """Show the impact function browser tool.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.function_browser import FunctionBrowser myDialog = FunctionBrowser(self.iface.mainWindow()) myDialog.exec_() # modal def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe_qgis.tools.shakemap_importer import ShakemapImporter myDialog = ShakemapImporter(self.iface.mainWindow()) myDialog.exec_() # modal def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe_qgis.tools.osm_downloader import OsmDownloader dialog = OsmDownloader(self.iface.mainWindow(), self.iface) dialog.exec_() # modal def show_batch_runner(self): """Show the batch runner dialog.""" from safe_qgis.batch.batch_dialog import BatchDialog myDialog = BatchDialog( parent=self.iface.mainWindow(), iface=self.iface, dock=self.dockWidget) myDialog.exec_() # modal def save_scenario(self): """Save current scenario to text file,""" self.dockWidget.save_current_scenario() def reset_dock(self): """Reset the dock to its default state.""" self.dockWidget.get_layers() def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if layer is None: self.actionKeywordsDialog.setEnabled(False) else: self.actionKeywordsDialog.setEnabled(True) def shortcut_f7(self): """Executed when user press F7 - will show the shakemap importer.""" self.show_shakemap_importer()
class Plugin(object): """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menu bar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QGisAppInterface """ # Save reference to the QGIS interface self.iface = iface self.dock_widget = None self.action_import_dialog = None self.action_save_scenario = None self.action_batch_runner = None self.action_shake_converter = None self.action_minimum_needs = None self.action_global_minimum_needs = None self.action_impact_merge_dlg = None self.key_action = None self.action_options = None self.action_keywords_dialog = None self.action_keywords_wizard = None self.action_function_centric_wizard = None self.action_extent_selector = None self.translator = None self.toolbar = None self.actions = [] # list of all QActions we create for InaSAFE self.action_dock = None self.action_toggle_rubberbands = None self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) # noinspection PyArgumentList def change_i18n(self, new_locale): """Change internationalisation for the plugin. Override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param new_locale: the new locale i.e. 'id', 'af', etc. :type new_locale: str :raises: TranslationLoadException """ os.environ['INASAFE_LANG'] = str(new_locale) LOGGER.debug('%s %s %s' % ( new_locale, QLocale.system().name(), os.environ['INASAFE_LANG'])) root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) translation_path = os.path.join( root, 'safe_qgis', 'i18n', 'inasafe_' + str(new_locale) + '.qm') if os.path.exists(translation_path): self.translator = QTranslator() result = self.translator.load(translation_path) if not result: message = 'Failed to load translation for %s' % new_locale raise TranslationLoadError(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( translation_path, os.path.exists(translation_path))) # 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('Plugin', message) def add_action(self, action, add_to_toolbar=True): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) # noinspection PyPep8Naming def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = None # -------------------------------------- # Create action for plugin dockable window (show/hide) # -------------------------------------- # pylint: disable=W0201 icon = resources_path('img', 'icons', 'icon.svg') self.action_dock = QAction( QIcon(icon), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.action_dock.setObjectName('InaSAFEDockToggle') self.action_dock.setStatusTip(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setWhatsThis(self.tr( 'Show/hide InaSAFE dock widget')) self.action_dock.setCheckable(True) self.action_dock.setChecked(True) self.action_dock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.action_dock) # -------------------------------------- # Create action for keywords editor # -------------------------------------- icon = resources_path('img', 'icons', 'show-keyword-editor.svg') self.action_keywords_dialog = QAction( QIcon(icon), self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow()) self.action_keywords_dialog.setStatusTip(self.tr( 'Open InaSAFE keywords editor')) self.action_keywords_dialog.setWhatsThis(self.tr( 'Open InaSAFE keywords editor')) self.action_keywords_dialog.setEnabled(False) self.action_keywords_dialog.triggered.connect( self.show_keywords_editor) self.add_action( self.action_keywords_dialog, add_to_toolbar=self.full_toolbar) # -------------------------------------- # Create action for keywords creation wizard # ------------------------------------- icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('InaSAFE Keywords Creation Wizard'), self.iface.mainWindow()) self.action_keywords_wizard.setStatusTip(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setWhatsThis(self.tr( 'Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setEnabled(False) self.action_keywords_wizard.triggered.connect( self.show_keywords_wizard) self.add_action(self.action_keywords_wizard) # -------------------------------------- # Create action for IF-centric wizard # -------------------------------------- icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('InaSAFE Impact Function Centric Wizard'), self.iface.mainWindow()) self.action_function_centric_wizard.setStatusTip(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setWhatsThis(self.tr( 'Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setEnabled(True) self.action_function_centric_wizard.triggered.connect( self.show_function_centric_wizard) self.add_action(self.action_function_centric_wizard) # -------------------------------------- # Create action for options dialog # -------------------------------------- icon = resources_path('img', 'icons', 'configure-inasafe.svg') self.action_options = QAction( QIcon(icon), self.tr('InaSAFE Options'), self.iface.mainWindow()) self.action_options.setStatusTip(self.tr( 'Open InaSAFE options dialog')) self.action_options.setWhatsThis(self.tr( 'Open InaSAFE options dialog')) self.action_options.triggered.connect(self.show_options) self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) # --------------------------------------- # Create action for minimum needs dialog # --------------------------------------- icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.action_minimum_needs = QAction( QIcon(icon), self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow()) self.action_minimum_needs.setStatusTip(self.tr( 'Open InaSAFE minimum needs tool')) self.action_minimum_needs.setWhatsThis(self.tr( 'Open InaSAFE minimum needs tool')) self.action_minimum_needs.triggered.connect(self.show_minimum_needs) self.add_action( self.action_minimum_needs, add_to_toolbar=self.full_toolbar) # ---------------------------------------------- # Create action for global minimum needs dialog # ---------------------------------------------- icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg') self.action_global_minimum_needs = QAction( QIcon(icon), self.tr('InaSAFE Global Minimum Needs Configuration'), self.iface.mainWindow()) self.action_global_minimum_needs.setStatusTip(self.tr( 'Open InaSAFE global minimum needs configuration')) self.action_global_minimum_needs.setWhatsThis(self.tr( 'Open InaSAFE global minimum needs configuration')) self.action_global_minimum_needs.triggered.connect( self.show_global_minimum_needs_configuration) self.add_action( self.action_global_minimum_needs, add_to_toolbar=self.full_toolbar) # --------------------------------------- # Create action for converter dialog # --------------------------------------- icon = resources_path('img', 'icons', 'show-converter-tool.svg') self.action_shake_converter = QAction( QIcon(icon), self.tr('InaSAFE Converter'), self.iface.mainWindow()) self.action_shake_converter.setStatusTip(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.setWhatsThis(self.tr( 'Open InaSAFE Converter')) self.action_shake_converter.triggered.connect( self.show_shakemap_importer) self.add_action( self.action_shake_converter, add_to_toolbar=self.full_toolbar) # --------------------------------------- # Create action for batch runner dialog # --------------------------------------- icon = resources_path('img', 'icons', 'show-batch-runner.svg') self.action_batch_runner = QAction( QIcon(icon), self.tr('InaSAFE Batch Runner'), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr( 'Open InaSAFE Batch Runner')) self.action_batch_runner.setWhatsThis(self.tr( 'Open InaSAFE Batch Runner')) self.action_batch_runner.triggered.connect(self.show_batch_runner) self.add_action( self.action_batch_runner, add_to_toolbar=self.full_toolbar) # --------------------------------------- # Create action for save scenario dialog # --------------------------------------- icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction( QIcon(icon), self.tr('Save current scenario'), self.iface.mainWindow()) message = self.tr('Save current scenario to text file') self.action_save_scenario.setStatusTip(message) self.action_save_scenario.setWhatsThis(message) # noinspection PyUnresolvedReferences self.action_save_scenario.triggered.connect(self.save_scenario) self.add_action( self.action_save_scenario, add_to_toolbar=self.full_toolbar) # -------------------------------------- # Create action for import OSM Dialog # -------------------------------------- icon = resources_path('img', 'icons', 'show-osm-download.svg') self.action_import_dialog = QAction( QIcon(icon), self.tr('InaSAFE OpenStreetMap Downloader'), self.iface.mainWindow()) self.action_import_dialog.setStatusTip(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.action_import_dialog.setWhatsThis(self.tr( 'InaSAFE OpenStreetMap Downloader')) self.action_import_dialog.triggered.connect(self.show_osm_downloader) self.add_action(self.action_import_dialog) # -------------------------------------- # Create action for impact layer merge Dialog # -------------------------------------- icon = resources_path('img', 'icons', 'show-impact-merge.svg') self.action_impact_merge_dlg = QAction( QIcon(icon), self.tr('InaSAFE Impact Layer Merge'), self.iface.mainWindow()) self.action_impact_merge_dlg.setStatusTip(self.tr( 'InaSAFE Impact Layer Merge')) self.action_impact_merge_dlg.setWhatsThis(self.tr( 'InaSAFE Impact Layer Merge')) self.action_impact_merge_dlg.triggered.connect(self.show_impact_merge) self.add_action( self.action_impact_merge_dlg, add_to_toolbar=self.full_toolbar) # -------------------------------------- # create dockwidget and tabify it with the legend # -------------------------------------- self.dock_widget = Dock(self.iface) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend') if myLegendTab: self.iface.mainWindow().tabifyDockWidget( myLegendTab, self.dock_widget) self.dock_widget.raise_() # # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action) # Also deal with the fact that on start of QGIS dock may already be # hidden. self.action_dock.setChecked(self.dock_widget.isVisible()) # pylint: disable=W0201 # --------------------------------------- # Create action for toggling rubber bands # --------------------------------------- icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg') self.action_toggle_rubberbands = QAction( QIcon(icon), self.tr('Toggle scenario outlines'), self.iface.mainWindow()) message = self.tr('Toggle rubber bands showing scenarion extents.') self.action_toggle_rubberbands.setStatusTip(message) self.action_toggle_rubberbands.setWhatsThis(message) # Set initial state self.action_toggle_rubberbands.setCheckable(True) settings = QSettings() flag = bool(settings.value( 'inasafe/showRubberBands', False, type=bool)) self.action_toggle_rubberbands.setChecked(flag) # noinspection PyUnresolvedReferences self.action_toggle_rubberbands.triggered.connect( self.dock_widget.toggle_rubber_bands) self.add_action(self.action_toggle_rubberbands) # --------------------------------------- # Create action for analysis extent dialog # --------------------------------------- icon = resources_path('img', 'icons', 'set-extents-tool.svg') self.action_extent_selector = QAction( QIcon(icon), self.tr('Set the analysis area for InaSAFE'), self.iface.mainWindow()) self.action_extent_selector.setStatusTip(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.setWhatsThis(self.tr( 'Set the analysis area for InaSAFE')) self.action_extent_selector.triggered.connect( self.show_extent_selector) self.add_action(self.action_extent_selector) # noinspection PyMethodMayBeStatic def clear_modules(self): """Unload inasafe functions and try to return QGIS to before InaSAFE. """ from safe.impact_functions import core core.unload_plugins() # next lets force remove any inasafe related modules modules = [] for module in sys.modules: if 'inasafe' in module: # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module.split('.') path = '' for myToken in tokens: path += os.path.sep + myToken parent = os.path.abspath(os.path.join( __file__, os.path.pardir, os.path.pardir)) full_path = os.path.join(parent, path + '.py') if os.path.exists(os.path.abspath(full_path)): LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) for module in sys.modules: if 'inasafe' in module: print module # Lets also clean up all the path additions that were made package_path = os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.mainWindow().removeDockWidget(self.dock_widget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dock_widget.setVisible(False) self.dock_widget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) def toggle_inasafe_action(self, checked): """Check or un-check the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.action_dock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dock_widget.isVisible(): self.dock_widget.setVisible(False) else: self.dock_widget.setVisible(True) self.dock_widget.raise_() def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, self.iface.mainWindow(), extent=self.dock_widget.extent.user_extent, crs=self.dock_widget.extent.user_extent_crs) widget.clear_extent.connect( self.dock_widget.extent.clear_user_analysis_extent) widget.extent_defined.connect( self.dock_widget.define_user_analysis_extent) # Needs to be non modal to support hide -> interact with map -> show widget.show() # non modal def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.show() # non modal def show_global_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog(self.iface.mainWindow()) dialog.exec_() # modal def show_impact_merge(self): """Show the impact layer merge dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.impact_merge_dialog import ImpactMergeDialog dialog = ImpactMergeDialog(self.iface.mainWindow()) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog dialog = OptionsDialog( self.iface, self.dock_widget, self.iface.mainWindow()) dialog.exec_() # modal def show_keywords_editor(self): """Show the keywords editor.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.keywords_dialog import KeywordsDialog # Next block is a fix for #776 if self.iface.activeLayer() is None: return try: keyword_io = KeywordIO() keyword_io.read_keywords(self.iface.activeLayer()) except UnsupportedProviderError: # noinspection PyUnresolvedReferences,PyCallByClass # noinspection PyTypeChecker,PyArgumentList QMessageBox.warning( None, self.tr('Unsupported layer type'), self.tr( 'The layer you have selected cannot be used for ' 'analysis because its data type is unsupported.')) return # End of fix for #776 # Fix for #793 except NoKeywordsFoundError: # we will create them from scratch in the dialog pass # End of fix for #793 # Fix for filtered-layer except InvalidParameterError, e: # noinspection PyTypeChecker,PyTypeChecker,PyArgumentList QMessageBox.warning( None, self.tr('Invalid Layer'), e.message ) return dialog = KeywordsDialog( self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_() # modal
class RECS: """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', 'RECS_HOME_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.initdlg=InitTaskDialog() self.selectdlg = SelectTaskDialog() self.loginDlg=LogInDialog() self.taskMgrDlg=TaskManagerDialog() self.taskInfoDlg=taskInfo() self.taskFeaturesDlg=taskFeatures() #self.loadmapDlg=LoadMapDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Task') self.logIn() self.selectTask() self.actions = [] self.toolbar = self.iface.addToolBar(u'Recs') self.toolbar.setObjectName(u'Recs') # layer.editingStarted.connect(editLayer() ) # TODO: We are going to let the user set this up in a future iteration #self.toolbar = self.iface.addToolBar(u'SelectTask') #self.toolbar.setObjectName(u'SelectTask') # 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('Tasks', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: # self.menu = QMenu( "&Task", self.iface.mainWindow().menuBar() ) action = self.iface.mainWindow().menuBar().actions() lastAction = action[-1] self.iface.addPluginToMenu( self.menu, lastAction) self.actions.append(lastAction) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" """Create the menu entries and toolbar icons inside the QGIS GUI.""" """ Task menu setting """ self.menu = QMenu(self.iface.mainWindow()) self.menu.setObjectName("task_menu_object") self.menu.setTitle("Task") """ Task """ self.action_tasks = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Tasks", self.iface.mainWindow()) self.action_tasks.setObjectName("Task_action_object") self.action_tasks.setWhatsThis("Task Initialized") #QtCore.QObject.connect(self.action_tasks, SIGNAL("triggered()"), self.tasks) """ Initializing Task """ self.action_init_task = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Initialize ", self.iface.mainWindow()) self.action_init_task.setObjectName("Task_action_object") self.action_init_task.setWhatsThis("Task Initialize") QtCore.QObject.connect(self.action_init_task, SIGNAL("triggered()"), self.initTask) """ Select Task """ self.action_select_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Select Task", self.iface.mainWindow()) self.action_select_task.setObjectName("Task_Select_object") self.action_select_task.setWhatsThis("Select Task") QtCore.QObject.connect(self.action_select_task, SIGNAL("triggered()"), self.selectTask) """ Reload Task """ self.action_reload_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Reload Task", self.iface.mainWindow()) self.action_reload_task.setObjectName("Task_Reload_object") self.action_reload_task.setWhatsThis("Reload Task") QtCore.QObject.connect(self.action_reload_task, SIGNAL("triggered()"), self.taskManager) """ Edit Task """ self.action_edit_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Edit Task", self.iface.mainWindow()) self.action_edit_task.setObjectName("Task_Edit_object") self.action_edit_task.setWhatsThis("Edit Task") QtCore.QObject.connect(self.action_edit_task, SIGNAL("triggered()"), self.editLayer) """ Finish Task """ self.action_finish_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Finish Task", self.iface.mainWindow()) self.action_finish_task.setObjectName("Task_Finish_object") self.action_finish_task.setWhatsThis("Edit Task") QtCore.QObject.connect(self.action_finish_task, SIGNAL("triggered()"), self.finishEditngLayer) """ Add action to the menu list """ #self.menuTask.addAction(self.action_tasks) self.menu.addAction(self.action_init_task) self.menu.addAction(self.action_select_task) self.menu.addAction(self.action_reload_task) self.menu.addAction(self.action_edit_task) self.menu.addAction(self.action_finish_task) """ Add menu to the menubar """ menubar=self.iface.mainWindow().menuBar() menubar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),self.menu) """ Add icon to the toolbar """ #self.iface.addPluginToMenu(u"&load Map", self.action_loadmap) #self.iface.addToolBarIcon(self.action_init_task) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&Task_Manager'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def initTask(self): layers = self.iface.legendInterface().layers() #layer_list = [] for layer in layers: #layer_list.append(layer.name()) if layer.name() == 'PARCEL': self.iface.setActiveLayer(layer) self.initdlg.show() #layer_list=list(set(layer_list)) #self.initdlg.comboBox.addItems(layer_list) self.initdlg.setFixedSize(self.initdlg.size()) result = self.initdlg.exec_() if result: pass def selectTask(self): self.selectdlg.show() self.selectdlg.setFixedSize(self.selectdlg.size()) self.selectdlg.loadLayer() self.selectdlg.populate() result = self.selectdlg.exec_() if result: # self.selectdlg.close() pass def showTaskInfo(self): self.taskInfoDlg.show() t_id = self.taskMgrDlg.retTaskID() self.taskInfoDlg.getAttribData(t_id) #self.taskInfoDlg.populate() def taskManager(self): if self.taskMgrDlg.isVisible(): self.taskMgrDlg.loadTaskClicked() # self.taskMgrDlg.close() # self.apdockwidget.close() else: self.taskMgrDlg.show() self.apdockwidget = QDockWidget("Task Manager", self.iface.mainWindow()) self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint) self.apdockwidget.setWidget(self.taskMgrDlg) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget) self.taskMgrDlg.populate() self.taskFeatures() # rows = self.taskMgrDlg.taskListTable.rowCount() # createdByList=[] # # # for row in range(0,rows): # createdByItems=self.taskMgrDlg.taskListTable.item(row,1) # createdByList.append(createdByItems.text()) # # # createdByList=list(set(createdByList)) # self.taskMgrDlg.createByComboBox.addItems(createdByList) # self.taskMgrDlg.createByComboBox.setCurrentIndex(createdByList.index()) self.menu = QtGui.QMenu() #newTask=self.menu.addAction("New Task",self.newTask,"") newTask = self.menu.addAction("New Task", self.newTaskEvent) loadTask = self.menu.addAction("Load Task", self.loadTaskEvent) cancelTask = self.menu.addAction("Cancel Task", self.cancelTaskEvent) showTaskArea = self.menu.addAction("Show Task Area", self.showTaskAreaEvent) noTask=self.menu.addAction("No Task",self.noTaskEvent) showTaskInfo=self.menu.addAction("Show Task Info",self.showTaskInfoEvent) updateFeature=self.menu.addAction("Update Features",self.updateFeatureEvent) self.taskMgrDlg.taskListTable.addAction(newTask) self.taskMgrDlg.taskListTable.addAction(loadTask) self.taskMgrDlg.taskListTable.addAction(cancelTask) self.taskMgrDlg.taskListTable.addAction(showTaskArea) self.taskMgrDlg.taskListTable.addAction(noTask) self.taskMgrDlg.taskListTable.addAction(showTaskInfo) self.taskMgrDlg.taskListTable.addAction(updateFeature) self.taskMgrDlg.taskListTable.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.taskMgrDlg.taskListTable.customContextMenuRequested.connect(self.contextMenuEvent) result = self.taskMgrDlg.exec_() if result: self.taskMgrDlg.populate() #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange def contextMenuEvent(self, point): self.menu.exec_(self.taskMgrDlg.taskListTable.mapToGlobal(point)) def newTaskEvent(self): self.initTask() def loadTaskEvent(self): self.taskMgrDlg.loadTaskClicked() t_id = self.taskMgrDlg.retTaskID() self.taskFeaturesDlg.populate(t_id) def cancelTaskEvent(self): self.taskMgrDlg.cancelTask() def showTaskAreaEvent(self): self.taskMgrDlg.showTaskAreaClicked() def noTaskEvent(self): print "noTask Called" def showTaskInfoEvent(self): self.showTaskInfo() def updateFeatureEvent(self): print "updateFeature" def logIn(self): self.loginDlg.show() self.loginDlg.setWindowFlags(Qt.FramelessWindowHint) result = self.loginDlg.exec_() if result: pass def loadLayer(self): self.mlr = None # QgsMapLayerRegistry.instance().removeAllMapLayers() self.mlr = QgsMapLayerRegistry.instance() uri = QgsDataSourceURI() uri.setConnection("172.20.0.71", "5432", "ncrprs_db", "postgres", "123456") uri.setDataSource("recs", "t_parcel", "parcelgeometry", "") vlayer = QgsVectorLayer(uri.uri(), "Parcel", "postgres") if vlayer.isValid(): self.mlr.addMapLayer(vlayer) else: QMessageBox.information(None, "Unable to Laod Data", "Unable to Load Layers from the Database!") return None def editLayer(self): global taskLayer global featCount layers = self.iface.legendInterface().layers() for layer in layers: if layer.name() == 'TaskLayer': taskLayer = layer taskLayerID=layer.id() self.iface.setActiveLayer(taskLayer) featCount = taskLayer.featureCount() print featCount taskLayer.startEditing() QgsProject.instance().setSnapSettingsForLayer(taskLayerID,True,2,1,20,True) def finishEditngLayer(self): """ change the edits to GML again to detect the changes """ print featCount taskLayer_shape = iface.activeLayer() QgsVectorFileWriter.writeAsVectorFormat(taskLayer_shape,"Z:\\GMLEdited\\temp.gml","utf-8",None,"GML") #QgsMapLayerRegistry.instance().removeAllMapLayers() iface.addVectorLayer("Z:\\GMLEdited\\temp.gml","EditedTaskLayer","ogr") """ Compare the two gml geometries """ doc_edited = xml.dom.minidom.parse("Z:\\GMLEdited\\temp.gml") doc_origion = xml.dom.minidom.parse("Z:\\GMLFile\\ogrGML.gml") editedParcel = doc_edited.getElementsByTagName("gml:featureMember") epLength = editedParcel.length print epLength obj = GeometryEdit() if epLength > featCount: obj.split(doc_edited,doc_origion) print "split" elif epLength < featCount: obj.merge(doc_edited,doc_origion) print "merge" else: obj.updateGeom() print "update" def taskFeatures(self): self.taskFeaturesDlg.show() self.apdockwidget = QDockWidget("Features Of Current Task", self.iface.mainWindow()) self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint) self.apdockwidget.setWidget(self.taskFeaturesDlg) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget) self.menu_feature = QtGui.QMenu() #newTask=self.menu.addAction("New Task",self.newTask,"") editAttr = self.menu_feature.addAction("Edit", self.editEvent) self.taskFeaturesDlg.currentTaskTable.addAction(editAttr) self.taskFeaturesDlg.currentTaskTable.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.taskFeaturesDlg.currentTaskTable.customContextMenuRequested.connect(self.contextMenuEvent2) #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange def contextMenuEvent2(self, point): self.menu_feature.exec_(self.taskFeaturesDlg.currentTaskTable.mapToGlobal(point)) def editEvent(self): self.showTaskInfo()
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 = BeyondTheBorderDialog() 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) if ProcessingConfig.getSetting('ACTIVATE_R'): # RscriptFolder = processing.algs.r.RUtils.RUtils.RScriptsFolder() RscriptFolder = ProcessingConfig.getSetting('R_SCRIPTS_FOLDER') shutil.copyfile(self.plugin_dir+"/rscript/btb_LissageGrille.rsx", RscriptFolder+"/btb_LissageGrille.rsx") shutil.copyfile(self.plugin_dir+"/rscript/btb_Schematisation_de_carreaux.rsx", RscriptFolder+"/btb_Schematisation_de_carreaux.rsx") shutil.copyfile(self.plugin_dir+"/rscript/btb_Schematisation_de_carreaux.rsx.help", RscriptFolder+"/btb_Schematisation_de_carreaux.rsx.help") self.actions.append(action) return action