def do_init_baselayer_menu(self):
        """Initialize baselayer menu:

        Adds the menu and reads all baselayers from the yaml file
        and adds them into the menu.

        Language support is working!
        """
        menubar = QMenuBar(self.toolbar)
        menubar.setObjectName("VeriSOModule.LoadBaselayerMenuBar")
        menubar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        menu = QMenu(menubar)
        menu.setTitle(_translate(self.module, "Baselayer", None))

        locale = QSettings().value('locale/userLocale')[0:2]

        baselayers = get_baselayers(self.module)
        if not baselayers:
            message = "Could not load baselayer definitions file."
            self.message_bar.pushMessage("Error",
                                         _translate(self.module, message,
                                                    None),
                                         level=Qgis.Critical,
                                         duration=0)
            return

        for baselayer in baselayers["baselayer"]:
            baselayer_title = baselayer["title"]
            try:
                keys = list(baselayer_title.keys())
                try:
                    baselayer_title = str(baselayer_title[locale])
                    # language found
                except:
                    # language *not* found
                    baselayer_title = str(list(baselayer_title.values())[0])
            except:
                baselayer_title = str(baselayer_title)

            baselayer["title"] = baselayer_title

            action = QAction(baselayer_title, self.iface.mainWindow())
            menu.addAction(action)
            action.triggered.connect(
                lambda checked, layer=baselayer: self.do_show_baselayer(layer))

        menubar.addMenu(menu)
        self.toolbar.insertWidget(self.beforeAction, menubar)
        if (sys.platform == 'darwin'):
            menubar.setNativeMenuBar(False)
Beispiel #2
0
    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            # print "** STARTING WBNMViewer"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = WBNMViewerDockWidget()
                self.dockwidget.plotButton.clicked.connect(
                    self.plot_hydrograph)
                self.dockwidget.filterEdit.textChanged.connect(
                    self.filter_storms)
                self.dockwidget.boxButton.clicked.connect(
                    self.plot_box_whisker)
                self.dockwidget.ensembleButton.clicked.connect(
                    self.plot_ensembles)

                # set up menubar
                self.window = QWidget()
                self.vbox = QVBoxLayout()
                self.window.setLayout(self.vbox)
                self.menuBar = QMenuBar()
                self.vbox.addWidget(self.menuBar)
                self.dockwidget.dockWidgetContents.layout().setSpacing(0)
                self.dockwidget.dockWidgetContents.layout().setMargin(0)
                self.dockwidget.dockWidgetContents.layout().setContentsMargins(
                    0, 0, 0, 0)
                self.dockwidget.dockWidgetContents.layout().insertWidget(
                    0, self.window)

                fileMenu = self.menuBar.addMenu("&File")
                self.loadWBNMMetaFile = QAction("Load WBNM *_Meta.out file",
                                                self.window)
                fileMenu.addAction(self.loadWBNMMetaFile)
                self.loadWBNMMetaFile.triggered.connect(self.process_meta_file)

                # set up data tab

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
Beispiel #3
0
    def doShowProjectId(self):
        menuBar = QMenuBar(self.toolbar)
        menuBar.setObjectName("VeriSOModule.ShowProjectIdMenuBar")
        menuBar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        menu = QMenu(menuBar)
        self.project_id = self.settings.value("project/id")
        menu.setTitle(
            QCoreApplication.translate(self.module,
                                       "Aktives Projekt: " + self.project_id))

        menuBar.addMenu(menu)
        menuBar.setEnabled(False)
        self.toolbar.addWidget(menuBar)
Beispiel #4
0
    def do_init_defects_menu(self):
        """Inititializes the defects menu:
        - load defects
        - export defects
        
        Export defects uses some external python excel library.
        """
        menubar = QMenuBar(self.toolbar)
        menubar.setObjectName("VeriSOModule.LoadDefectsMenuBar")
        menubar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        menu = QMenu(menubar)
        menu.setTitle(_translate(self.module, "Bemerkungen", None))

        action = QAction(_translate(self.module, "Bemerkungen laden", None),
                         self.iface.mainWindow())
        action.triggered.connect(self.do_load_defects)
        menu.addAction(action)

        action = QAction(
            _translate(self.module, "Bemerkungen exportieren", None),
            self.iface.mainWindow())
        action.triggered.connect(self.do_export_defects)
        menu.addAction(action)

        menubar.addMenu(menu)
        self.toolbar.insertWidget(self.beforeAction, menubar)
    def do_init_topics_tables_menu(self):
        """Creates the topics and tables loader menu.
        Topics and tables are sorted alphanumerically. I'm not sure if ili2pg
        saves enough
        information in the database to find out the interlis model order.

        At the moment there is no locale support here.
        Seems to be not very handy without mapping tables anyway...
        """
        menubar = QMenuBar(self.toolbar)
        menubar.setObjectName("VeriSOModule.LoadTopicsTablesMenuBar")
        menubar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        menu = QMenu(menubar)
        menu.setTitle(_translate(self.module, "Tables", None))

        topics = get_topics_tables(self.module_name)
        if not topics:
            message = "Something went wrong catching the topics/tables list " \
                      "from the database."
            self.message_bar.pushMessage(self.module_name,
                                         _translate(self.module, message,
                                                    None),
                                         Qgis.Critical,
                                         duration=0)
            return

        for topic in topics:
            topic_menu = menu.addMenu(str(topic["topic"]))

            action = QAction(_translate(self.module, "Load Topic", None),
                             self.iface.mainWindow())
            topic_menu.addAction(action)
            topic_menu.addSeparator()
            action.triggered.connect(
                lambda checked, topic=topic: self.do_show_topic(topic))

            layers = get_layers_from_topic(topic)
            for my_layer in layers:
                action = QAction(my_layer["title"], self.iface.mainWindow())
                topic_menu.addAction(action)
                action.triggered.connect(lambda checked, layer=my_layer: self.
                                         do_show_single_topic_layer(layer))

        menubar.addMenu(menu)
        self.toolbar.insertWidget(self.beforeAction, menubar)
        if (sys.platform == 'darwin'):
            menubar.setNativeMenuBar(False)
Beispiel #6
0
    def get_checks_menubar(self, check_topics):
        menubar = QMenuBar(self.toolbar)
        menubar.setObjectName("VeriSOModule.LoadChecksMenuBar")
        menubar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        menu = QMenu(menubar)
        menu.setTitle(_translate(self.module, "Checks", None))

        locale = QSettings().value('locale/userLocale')[0:2]
        for check_topic in check_topics:
            checks = check_topics[check_topic]["checks"]
            if not checks:
                message = "The topic %s has no valid checks: skiping." % (
                    check_topic)
                self.message_bar.pushWarning(
                    "Warning", _translate(self.module, message, None))

                # this topic has no valid checks
                continue

            single_check_menu = menu.addMenu(str(check_topic))

            for check in checks:
                check_name = check["name"]

                # Same multilingual strategy as in get_check_topics().
                try:
                    keys = list(check_name.keys())
                    try:
                        check_name = str(check_name[locale])
                        # language found
                    except:
                        # language *not* found
                        check_name = str(list(check_name.values())[0])
                except:
                    check_name = str(check_name)

                if check_name == "separator":
                    single_check_menu.addSeparator()
                else:
                    action = QAction(check_name, self.iface.mainWindow())

                    try:
                        shortcut = check["shortcut"]
                        action.setShortcut(shortcut)
                    except:
                        pass

                    single_check_menu.addAction(action)
                    topic_dir = check_topics[check_topic]['topic_dir']
                    action.triggered.connect(
                        lambda checked, complex_check=check, folder=topic_dir:
                        self.do_show_complex_check(folder, complex_check))

        menubar.addMenu(menu)
        return menubar
Beispiel #7
0
    def initTopMenu(self):
        #adding
        #topMenu=self.titleBarWidget()
        #topMenu=self.layout().menuBar()
        topMenu = QMenuBar()
        #self.layout().setMenuBar(self.topMenu)
        #topMenu=QMenuBar(self)#works but need to click '>>' button

        addMenu = topMenu.addMenu("add")
        loadSecAct = addMenu.addAction('load .sec...')
        loadSecAct.triggered.connect(self.loadSec)
        loadRteAct = addMenu.addAction('load .rte...')
        loadRteAct.triggered.connect(self.loadRTE)
        loadSrAct = addMenu.addAction('load .sr...')
        loadSrAct.triggered.connect(self.loadSr)

        #save
        saveMenu = topMenu.addMenu("save")

        saveSrAct = saveMenu.addAction('save as .sr...')
        saveSrAct.triggered.connect(self.saveAsSr)

        saveSecAct = saveMenu.addAction('save as .sec...')
        saveSecAct.triggered.connect(self.saveAsSec)

        saveSecAct = saveMenu.addAction('save as .rte...')
        saveSecAct.triggered.connect(self.saveAsRte)

        setingsMenu = topMenu.addMenu("settings")
        setDatabaseAct = setingsMenu.addAction('set database...')
        setDatabaseAct.triggered.connect(self.dd.show)

        #self.toolBar=QToolBar(self)
        #toolbar=self.addToolBar()
        #topMenu = QMenuBar(self)
        #topMenu.setDefaultUp(False)
        #addMenu=topMenu.addMenu("add")
        #saveMenu=topMenu.addMenu("save")
        #self.layout().addWidget(topMenu)
        self.main_widget.layout().setMenuBar(topMenu)
Beispiel #8
0
class DBManager(QMainWindow):

    def __init__(self, iface, parent=None):
        QMainWindow.__init__(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi()
        self.iface = iface

        # restore the window state
        settings = QgsSettings()
        self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray))
        self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray))

        self.tabs.currentChanged.connect(self.tabChanged)
        self.tree.selectedItemChanged.connect(self.itemChanged)
        self.tree.model().dataChanged.connect(self.iface.reloadConnections)
        self.itemChanged(None)

    def closeEvent(self, e):
        self.unregisterAllActions()
        # clear preview, this will delete the layer in preview tab
        self.preview.loadPreview(None)

        # save the window state
        settings = QgsSettings()
        settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState())
        settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry())

        QMainWindow.closeEvent(self, e)

    def refreshItem(self, item=None):
        with OverrideCursor(Qt.WaitCursor):
            try:
                if item is None:
                    item = self.tree.currentItem()
                self.tree.refreshItem(item)  # refresh item children in the db tree
            except BaseError as e:
                DlgDbError.showError(e, self)

    def itemChanged(self, item):
        with OverrideCursor(Qt.WaitCursor):
            try:
                self.reloadButtons()
                # clear preview, this will delete the layer in preview tab
                self.preview.loadPreview(None)
                self.refreshTabs()
            except BaseError as e:
                DlgDbError.showError(e, self)

    def reloadButtons(self):
        db = self.tree.currentDatabase()
        if not hasattr(self, '_lastDb'):
            self._lastDb = db

        elif db == self._lastDb:
            return

        # remove old actions
        if self._lastDb is not None:
            self.unregisterAllActions()

        # add actions of the selected database
        self._lastDb = db
        if self._lastDb is not None:
            self._lastDb.registerAllActions(self)

    def tabChanged(self, index):
        with OverrideCursor(Qt.WaitCursor):
            try:
                self.refreshTabs()
            except BaseError as e:
                DlgDbError.showError(e, self)

    def refreshTabs(self):
        index = self.tabs.currentIndex()
        item = self.tree.currentItem()
        table = self.tree.currentTable()

        # enable/disable tabs
        self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table is not None)
        self.tabs.setTabEnabled(self.tabs.indexOf(self.preview), table is not None and table.type in [table.VectorType,
                                                                                                      table.RasterType] and table.geomColumn is not None)
        # show the info tab if the current tab is disabled
        if not self.tabs.isTabEnabled(index):
            self.tabs.setCurrentWidget(self.info)

        current_tab = self.tabs.currentWidget()
        if current_tab == self.info:
            self.info.showInfo(item)
        elif current_tab == self.table:
            self.table.loadData(item)
        elif current_tab == self.preview:
            self.preview.loadPreview(item)

    def refreshActionSlot(self):
        self.info.setDirty()
        self.table.setDirty()
        self.preview.setDirty()
        self.refreshItem()

    def importActionSlot(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                     Qgis.Info, self.iface.messageTimeout())
            return

        outUri = db.uri()
        schema = self.tree.currentSchema()
        if schema:
            outUri.setDataSource(schema.name, "", "", "")

        from .dlg_import_vector import DlgImportVector

        dlg = DlgImportVector(None, db, outUri, self)
        dlg.exec_()

    def exportActionSlot(self):
        table = self.tree.currentTable()
        if table is None:
            self.infoBar.pushMessage(self.tr("Select the table you want export to file."), Qgis.Info,
                                     self.iface.messageTimeout())
            return

        inLayer = table.toMapLayer()
        if inLayer.type() != QgsMapLayer.VectorLayer:
            self.infoBar.pushMessage(
                self.tr("Select a vector or a tabular layer you want export."),
                Qgis.Warning, self.iface.messageTimeout())
            return

        from .dlg_export_vector import DlgExportVector

        dlg = DlgExportVector(inLayer, table.database(), self)
        dlg.exec_()

        inLayer.deleteLater()

    def runSqlWindow(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                     Qgis.Info, self.iface.messageTimeout())
            # force displaying of the message, it appears on the first tab (i.e. Info)
            self.tabs.setCurrentIndex(0)
            return

        from .dlg_sql_window import DlgSqlWindow

        query = DlgSqlWindow(self.iface, db, self)
        dbname = db.connection().connectionName()
        tabname = self.tr("Query ({0})").format(dbname)
        index = self.tabs.addTab(query, tabname)
        self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)
        query.nameChanged.connect(functools.partial(self.update_query_tab_name, index, dbname))

    def runSqlLayerWindow(self, layer):
        from .dlg_sql_layer_window import DlgSqlLayerWindow
        query = DlgSqlLayerWindow(self.iface, layer, self)
        lname = layer.name()
        tabname = self.tr("Layer ({0})").format(lname)
        index = self.tabs.addTab(query, tabname)
        # self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)

    def update_query_tab_name(self, index, dbname, queryname):
        if not queryname:
            queryname = self.tr("Query")
        tabname = u"%s (%s)" % (queryname, dbname)
        self.tabs.setTabText(index, tabname)

    def showSystemTables(self):
        self.tree.showSystemTables(self.actionShowSystemTables.isChecked())

    def registerAction(self, action, menuName, callback=None):
        """ register an action to the manager's main menu """
        if not hasattr(self, '_registeredDbActions'):
            self._registeredDbActions = {}

        if callback is not None:
            def invoke_callback(x):
                return self.invokeCallback(callback)

        if menuName is None or menuName == "":
            self.addAction(action)

            if menuName not in self._registeredDbActions:
                self._registeredDbActions[menuName] = list()
            self._registeredDbActions[menuName].append(action)

            if callback is not None:
                action.triggered.connect(invoke_callback)
            return True

        # search for the menu
        actionMenu = None
        helpMenuAction = None
        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue
            if a.menu() != self.menuHelp:
                helpMenuAction = a

            actionMenu = a
            break

        # not found, add a new menu before the help menu
        if actionMenu is None:
            menu = QMenu(menuName, self)
            if helpMenuAction is not None:
                actionMenu = self.menuBar.insertMenu(helpMenuAction, menu)
            else:
                actionMenu = self.menuBar.addMenu(menu)

        menu = actionMenu.menu()
        menuActions = menu.actions()

        # get the placeholder's position to insert before it
        pos = 0
        for pos in range(len(menuActions)):
            if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
                menuActions[pos].setVisible(True)
                break

        if pos < len(menuActions):
            before = menuActions[pos]
            menu.insertAction(before, action)
        else:
            menu.addAction(action)

        actionMenu.setVisible(True)  # show the menu

        if menuName not in self._registeredDbActions:
            self._registeredDbActions[menuName] = list()
        self._registeredDbActions[menuName].append(action)

        if callback is not None:
            action.triggered.connect(invoke_callback)

        return True

    def invokeCallback(self, callback, *params):
        """ Call a method passing the selected item in the database tree,
                the sender (usually a QAction), the plugin mainWindow and
                optionally additional parameters.

                This method takes care to override and restore the cursor,
                but also catches exceptions and displays the error dialog.
        """
        with OverrideCursor(Qt.WaitCursor):
            try:
                callback(self.tree.currentItem(), self.sender(), self, *params)
            except BaseError as e:
                # catch database errors and display the error dialog
                DlgDbError.showError(e, self)

    def unregisterAction(self, action, menuName):
        if not hasattr(self, '_registeredDbActions'):
            return

        if menuName is None or menuName == "":
            self.removeAction(action)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

            action.deleteLater()
            return True

        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue

            menu = a.menu()
            menuActions = menu.actions()

            menu.removeAction(action)
            if menu.isEmpty():  # hide the menu
                a.setVisible(False)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

                # hide the placeholder if there're no other registered actions
                if len(self._registeredDbActions[menuName]) <= 0:
                    for i in range(len(menuActions)):
                        if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"):
                            menuActions[i].setVisible(False)
                            break

            action.deleteLater()
            return True

        return False

    def unregisterAllActions(self):
        if not hasattr(self, '_registeredDbActions'):
            return

        for menuName in self._registeredDbActions:
            for action in list(self._registeredDbActions[menuName]):
                self.unregisterAction(action, menuName)
        del self._registeredDbActions

    def close_tab(self, index):
        widget = self.tabs.widget(index)
        if widget not in [self.info, self.table, self.preview]:
            self.tabs.removeTab(index)
            widget.deleteLater()

    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
                                                   self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
                                                     self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
                                                     self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
                                                     self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
Beispiel #9
0
    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
                                                   self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
                                                     self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
                                                     self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
                                                     self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
def qgis_app(request):
    """
    Creates a QGIS application, a QGIS Interface, a QGIS Settings and a set of loaded plugins. The fixture can be
    parametrized with the following options:
    - plugin_names: Plugin names to load
    - plugin_paths: Directories where the plugins are located
    - locale: Language code with the translation that the plugin has to be loaded

    :param request: Fixture request. It contains the indirect parameters for fixture setup
    :type request: FixtureRequest
    :return: The QGIS application objects
    :rtype: (QgsApplication, QgisInterface, QgsSettings, (list of object) or None)
    """
    # Collect parameters
    plugin_names = request.param[
        'plugin_names'] if 'plugin_names' in request.param else None
    plugin_paths = request.param['plugin_paths'] if 'plugin_paths' in request.param \
        else [str(Path(__file__).parent.parent.parent) + '/src']
    locale = request.param['locale'] if 'locale' in request.param else 'EN'
    # Create a QGIS Application
    # noinspection PyTypeChecker
    QgsApplication.setPrefixPath('/usr', True)
    qgs = QgsApplication([], True)
    qgs.initQgis()
    # Mock the QGIS Interface
    iface = unittest.mock.Mock(spec=QgisInterface)
    main_window = QMainWindow()
    iface.mainWindow.return_value = main_window
    canvas = QgsMapCanvas(main_window)
    canvas.resize(QSize(400, 400))
    iface.mapCanvas.return_value = canvas
    # Create the settings
    global_settings = QSettings()
    global_settings.setValue('locale/userLocale', locale)
    qgs_settings = QgsSettings()
    qgs_settings_file = qgs_settings.fileName()
    menu = QMenuBar()
    main_window.setMenuBar(menu)
    qgis.utils.iface = iface
    for plugin_path in plugin_paths:
        sys.path.insert(0, plugin_path)
        qgis.utils.plugin_paths.append(plugin_path)
    qgis.utils.updateAvailablePlugins()
    if plugin_names is not None:
        plugins = list()
        if isinstance(plugin_names, str):
            plugin_names = [plugin_names]
        for plugin_name in plugin_names:
            assert qgis.utils.loadPlugin(plugin_name)
            assert qgis.utils.startPlugin(plugin_name)
            plugins.append(qgis.utils.plugins[plugin_name])
        yield qgs, iface, qgs_settings, plugins
        for plugin_name in plugin_names:
            qgis.utils.unloadPlugin(plugin_name)
            del qgis.utils.plugin_times[plugin_name]
        if plugin_paths is not None:
            for plugin_path in plugin_paths:
                sys.path.remove(plugin_path)
                qgis.utils.plugin_paths.remove(plugin_path)
        qgis.utils.updateAvailablePlugins()
    else:
        yield qgs, iface, qgs_settings, None

    os.remove(qgs_settings_file)
    del qgs
Beispiel #11
0
    def initGui(self):
        icon_path = ':/plugins/veriso/icon.png'

        # Qt offers some themes which you also can change in QGIS settings.
        # Since the background color of the menu toolbar can be different than
        # the background color of the button toolbars, the veriso toolbar
        # doesn't suit well. So we change it manually by finding out the
        # background color of one (e.g. file) toolbar and applying it
        # to the veriso toolbar.
        # This approach works (well?) for xfce 4.12 and standard (gtk+) theme.
        # We need to do this also in other methods when we add new menus :-(

        # 20150406: Only change QToolBar background color.
        # Otherweise the later added menus will have white hover color and
        # other quirks.
        # Strange: QToolBar stylesheet seems to need an border.
        background_color = self.iface.mainWindow().menuBar().palette().color(
            QPalette.Window).name()

        # main toolbar
        self.toolbar = self.iface.addToolBar("VeriSO")
        self.toolbar.setStyleSheet("QToolBar {background-color: " +
                                   background_color + "; border: 0px solid " +
                                   background_color + ";}")

        self.toolbar.setObjectName("VeriSO.Main.ToolBar")
        self.toolbar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        # projects
        self.menubar_projects = QMenuBar()
        self.menubar_projects.setObjectName("VeriSO.Main.ProjectsMenuBar")
        self.menubar_projects.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred))
        self.menu_projects = QMenu()
        self.menu_projects.setTitle(tr("Projects"))
        self.menubar_projects.addMenu(self.menu_projects)

        # files
        self.menubar_file = QMenuBar()
        self.menubar_file.setObjectName("VeriSO.Main.FileMenuBar")
        self.menubar_file.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_file = QMenu()
        self.menu_file.setTitle(tr("File"))
        self.import_project = QAction(tr("Import project"),
                                      self.iface.mainWindow())
        self.import_project.triggered.connect(self.do_import_project)
        self.delete_project = QAction(tr("Delete project"),
                                      self.iface.mainWindow())
        self.delete_project.triggered.connect(self.do_delete_project)
        self.menu_file.addActions([self.import_project, self.delete_project])
        self.menubar_file.addMenu(self.menu_file)

        # settings
        self.menubar_settings = QMenuBar()
        self.menubar_settings.setObjectName("VeriSO.Main.SettingsMenuBar")
        self.menubar_settings.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_settings = QMenu()
        self.menu_settings.setTitle(tr("Settings"))

        self.options = QAction(tr("Options"), self.iface.mainWindow())
        self.options.triggered.connect(self.do_options)
        self.menu_settings.addActions([self.options])
        self.menubar_settings.addMenu(self.menu_settings)

        # Add menus to toolbar.
        self.toolbar.addWidget(self.menubar_projects)
        self.toolbar.addWidget(self.menubar_file)
        self.toolbar.addWidget(self.menubar_settings)

        # Initial load of project menu entries.
        self.do_load_projects_database()
Beispiel #12
0
    def initGui(self):

        # Prepare defects list dock
        self._create_defects_list_dock()

        # Prepare check results dock
        self._create_check_results_dock()

        # Qt offers some themes which you also can change in QGIS settings.
        # Since the background color of the menu toolbar can be different than
        # the background color of the button toolbars, the veriso toolbar
        # doesn't suit well. So we change it manually by finding out the
        # background color of one (e.g. file) toolbar and applying it
        # to the veriso toolbar.
        # This approach works (well?) for xfce 4.12 and standard (gtk+) theme.
        # We need to do this also in other methods when we add new menus :-(

        # 20150406: Only change QToolBar background color.
        # Otherweise the later added menus will have white hover color and
        # other quirks.
        # Strange: QToolBar stylesheet seems to need an border.
        background_color = self.iface.mainWindow().menuBar().palette().color(
            QPalette.Window).name()

        # main toolbar
        self.toolbar = self.iface.addToolBar("VeriSO")
        self.toolbar.setStyleSheet(
            "QToolBar {background-color: " + background_color +
            "; border: 0px solid " + background_color + ";}")

        self.toolbar.setObjectName("VeriSO.Main.ToolBar")
        self.toolbar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        # trick for OSX compatibility
        if(sys.platform == 'darwin'):
            foobar = QMenuBar()

        # projects
        self.menubar_projects = QMenuBar()
        self.menubar_projects.setObjectName("VeriSO.Main.ProjectsMenuBar")
        self.menubar_projects.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred))
        self.menu_projects = QMenu()
        self.menu_projects.setTitle(tr("Projects"))
        self.menubar_projects.addMenu(self.menu_projects)

        # files
        self.menubar_file = QMenuBar()
        self.menubar_file.setObjectName("VeriSO.Main.FileMenuBar")
        self.menubar_file.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_file = QMenu()
        self.menu_file.setTitle(tr("File"))
        self.import_project = QAction(tr("Import project"),
                                      self.iface.mainWindow())
        self.import_project.triggered.connect(self.do_import_project)
        self.export_project = QAction(tr("Export project"),
                                      self.iface.mainWindow())
        self.export_project.triggered.connect(self.do_export_project)
        self.delete_project = QAction(tr("Delete project"),
                                      self.iface.mainWindow())
        self.delete_project.triggered.connect(self.do_delete_project)
        self.menu_file.addActions([self.import_project, self.export_project,
                                   self.delete_project])
        self.menubar_file.addMenu(self.menu_file)

        # defects
        self.menubar_defects = QMenuBar(self.toolbar)
        self.menubar_defects.setObjectName("VeriSO.Main.LoadDefectsMenuBar")

        self.menubar_defects.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_defects = QMenu(self.menubar_defects)
        self.menu_defects.setObjectName("VeriSO.Main.LoadDefectsMenu")
        self.menu_defects.setTitle(tr("Defects"))

        self.defects_list_action = QAction(tr("Show defects list dock"),
                                           self.iface.mainWindow())
        self.defects_list_action.setCheckable(True)
        self.defects_list_action.setChecked(True)
        self.defects_list_action.triggered.connect(
            self.toggle_defects_list_dock_visibility)
        self.menu_defects.addAction(self.defects_list_action)
        self.menubar_defects.addMenu(self.menu_defects)

        # settings
        self.menubar_settings = QMenuBar()
        self.menubar_settings.setObjectName("VeriSO.Main.SettingsMenuBar")
        self.menubar_settings.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_settings = QMenu()
        self.menu_settings.setTitle(tr("Settings"))

        self.options = QAction(tr("Options"), self.iface.mainWindow())
        self.options.triggered.connect(self.do_options)
        self.menu_settings.addActions([self.options])
        self.menubar_settings.addMenu(self.menu_settings)

        # Add menus to toolbar.
        if(sys.platform == 'darwin'):
            self.toolbar.addWidget(foobar)
        self.toolbar.addWidget(self.menubar_projects)
        self.toolbar.addWidget(self.menubar_file)
        self.toolbar.addWidget(self.menubar_defects)
        self.toolbar.addWidget(self.menubar_settings)

        # for OSX compatibility. Without setNativeMenuBar(False) the veriso
        # menu will not appear
        if(sys.platform == 'darwin'):
            self.menubar_projects.setNativeMenuBar(False)
            self.menubar_file.setNativeMenuBar(False)
            self.menubar_defects.setNativeMenuBar(False)
            self.menubar_settings.setNativeMenuBar(False)

        # Initial load of project menu entries.
        self.do_load_projects_database()

        if(sys.platform == 'darwin'):
            self.iface.mainWindow().menuBar().setNativeMenuBar(False)
            self.iface.mainWindow().menuBar().setNativeMenuBar(True)
Beispiel #13
0
class VeriSO(object):
    def __init__(self, iface):
        self.iface = iface
        self.message_bar = self.iface.messageBar()
        self.plugin_dir = os.path.dirname(__file__)

        self.settings = QSettings("CatAIS", "VeriSO")

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

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

        # members
        self.toolbar = None
        self.menubar_projects = None
        self.menubar_file = None
        self.menu_file = None
        self.import_project = None
        self.export_project = None
        self.delete_project = None
        self.menubar_settings = None
        self.menu_projects = None
        self.menu_settings = None
        self.menubar_defects = None
        self.menu_defects = None
        self.defects_list_action = None
        self.options = None
        self.import_dlg = None
        self.export_dlg = None
        self.delete_dlg = None
        self.options_dlg = None
        self.max_scale = None

    # noinspection PyPep8Naming
    def initGui(self):

        # Prepare defects list dock
        self._create_defects_list_dock()

        # Prepare check results dock
        self._create_check_results_dock()

        # Qt offers some themes which you also can change in QGIS settings.
        # Since the background color of the menu toolbar can be different than
        # the background color of the button toolbars, the veriso toolbar
        # doesn't suit well. So we change it manually by finding out the
        # background color of one (e.g. file) toolbar and applying it
        # to the veriso toolbar.
        # This approach works (well?) for xfce 4.12 and standard (gtk+) theme.
        # We need to do this also in other methods when we add new menus :-(

        # 20150406: Only change QToolBar background color.
        # Otherweise the later added menus will have white hover color and
        # other quirks.
        # Strange: QToolBar stylesheet seems to need an border.
        background_color = self.iface.mainWindow().menuBar().palette().color(
            QPalette.Window).name()

        # main toolbar
        self.toolbar = self.iface.addToolBar("VeriSO")
        self.toolbar.setStyleSheet(
            "QToolBar {background-color: " + background_color +
            "; border: 0px solid " + background_color + ";}")

        self.toolbar.setObjectName("VeriSO.Main.ToolBar")
        self.toolbar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        # trick for OSX compatibility
        if(sys.platform == 'darwin'):
            foobar = QMenuBar()

        # projects
        self.menubar_projects = QMenuBar()
        self.menubar_projects.setObjectName("VeriSO.Main.ProjectsMenuBar")
        self.menubar_projects.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred))
        self.menu_projects = QMenu()
        self.menu_projects.setTitle(tr("Projects"))
        self.menubar_projects.addMenu(self.menu_projects)

        # files
        self.menubar_file = QMenuBar()
        self.menubar_file.setObjectName("VeriSO.Main.FileMenuBar")
        self.menubar_file.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_file = QMenu()
        self.menu_file.setTitle(tr("File"))
        self.import_project = QAction(tr("Import project"),
                                      self.iface.mainWindow())
        self.import_project.triggered.connect(self.do_import_project)
        self.export_project = QAction(tr("Export project"),
                                      self.iface.mainWindow())
        self.export_project.triggered.connect(self.do_export_project)
        self.delete_project = QAction(tr("Delete project"),
                                      self.iface.mainWindow())
        self.delete_project.triggered.connect(self.do_delete_project)
        self.menu_file.addActions([self.import_project, self.export_project,
                                   self.delete_project])
        self.menubar_file.addMenu(self.menu_file)

        # defects
        self.menubar_defects = QMenuBar(self.toolbar)
        self.menubar_defects.setObjectName("VeriSO.Main.LoadDefectsMenuBar")

        self.menubar_defects.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_defects = QMenu(self.menubar_defects)
        self.menu_defects.setObjectName("VeriSO.Main.LoadDefectsMenu")
        self.menu_defects.setTitle(tr("Defects"))

        self.defects_list_action = QAction(tr("Show defects list dock"),
                                           self.iface.mainWindow())
        self.defects_list_action.setCheckable(True)
        self.defects_list_action.setChecked(True)
        self.defects_list_action.triggered.connect(
            self.toggle_defects_list_dock_visibility)
        self.menu_defects.addAction(self.defects_list_action)
        self.menubar_defects.addMenu(self.menu_defects)

        # settings
        self.menubar_settings = QMenuBar()
        self.menubar_settings.setObjectName("VeriSO.Main.SettingsMenuBar")
        self.menubar_settings.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_settings = QMenu()
        self.menu_settings.setTitle(tr("Settings"))

        self.options = QAction(tr("Options"), self.iface.mainWindow())
        self.options.triggered.connect(self.do_options)
        self.menu_settings.addActions([self.options])
        self.menubar_settings.addMenu(self.menu_settings)

        # Add menus to toolbar.
        if(sys.platform == 'darwin'):
            self.toolbar.addWidget(foobar)
        self.toolbar.addWidget(self.menubar_projects)
        self.toolbar.addWidget(self.menubar_file)
        self.toolbar.addWidget(self.menubar_defects)
        self.toolbar.addWidget(self.menubar_settings)

        # for OSX compatibility. Without setNativeMenuBar(False) the veriso
        # menu will not appear
        if(sys.platform == 'darwin'):
            self.menubar_projects.setNativeMenuBar(False)
            self.menubar_file.setNativeMenuBar(False)
            self.menubar_defects.setNativeMenuBar(False)
            self.menubar_settings.setNativeMenuBar(False)

        # Initial load of project menu entries.
        self.do_load_projects_database()

        if(sys.platform == 'darwin'):
            self.iface.mainWindow().menuBar().setNativeMenuBar(False)
            self.iface.mainWindow().menuBar().setNativeMenuBar(True)

    def do_import_project(self):
        from .base.file.importproject import ImportProjectDialog
        self.import_dlg = ImportProjectDialog(self.iface)
        if self.import_dlg.init_gui():
            self.import_dlg.show()
            self.import_dlg.projectsDatabaseHasChanged.connect(
                self.do_load_projects_database)

    def do_export_project(self):
        from .base.file.exportproject import ExportProjectDialog
        self.export_dlg = ExportProjectDialog(self.iface)
        if self.export_dlg.init_gui():
            self.export_dlg.show()
            self.export_dlg.projectsDatabaseHasChanged.connect(
                self.do_load_projects_database)

    def do_delete_project(self):
        from .base.file.deleteproject import DeleteProjectDialog
        self.delete_dlg = DeleteProjectDialog(self.iface)
        if self.delete_dlg.init_gui():
            self.delete_dlg.show()
            self.delete_dlg.projectsDatabaseHasChanged.connect(
                self.do_load_projects_database)

    def do_options(self):
        from .base.settings.options import OptionsDialog
        self.options_dlg = OptionsDialog(self.iface)
        self.options_dlg.init_gui()
        self.options_dlg.show()
        self.options_dlg.projectsDatabaseHasChanged.connect(
            self.do_load_projects_database)

    def do_load_projects_database(self):
        projects = get_projects()

        if projects is not None:
            grouped_projects = {}
            for project in projects:
                module_name = project["appmodulename"]
                try:
                    module_list = grouped_projects[module_name]
                except KeyError:
                    module_list = []

                module_list.append(project)
                grouped_projects[module_name] = module_list

            self.menu_projects.clear()
            for key in sorted(grouped_projects):
                modules = grouped_projects[key]
                group_menu = self.menu_projects.addMenu(str(key))
                sorted_projects_list = sorted(modules,
                                              key=lambda k: k['displayname'])
                for project in sorted_projects_list:
                    action = QAction(str(project["displayname"]),
                                     self.iface.mainWindow())
                    group_menu.addAction(action)
                    action.triggered.connect(
                        lambda checked, active_project=project:
                            self.do_load_project(active_project))

    def do_load_project(self, project):
        # verified on osx, str(project[...]) return future.newstring, that
        # QSettings doesn't use it correctly. With native, use of standard
        # python string is forced.

        self.settings.setValue("project/id", str(project["id"]))
        self.settings.setValue("project/displayname",
                               str(project["displayname"]))
        self.settings.setValue("project/appmodule", str(project["appmodule"]))
        self.settings.setValue("project/appmodulename",
                               str(project["appmodulename"]))
        self.settings.setValue("project/ilimodelname",
                               str(project["ilimodelname"]))
        self.settings.setValue("project/epsg", str(project["epsg"]))
        self.settings.setValue("project/provider", str(project["provider"]))
        if 'dbhost' in project:
            self.settings.setValue("project/dbhost", str(project["dbhost"]))
        if 'dbport' in project:
            self.settings.setValue("project/dbport", str(project["dbport"]))
        if 'dbname' in project:
            self.settings.setValue("project/dbname", str(project["dbname"]))
        self.settings.setValue("project/dbschema", str(project["dbschema"]))
        if 'dbuser' in project:
            self.settings.setValue("project/dbuser", str(project["dbuser"]))
        if 'dbpwd' in project:
            self.settings.setValue("project/dbpwd", str(project["dbpwd"]))
        if 'dbadmin' in project:
            self.settings.setValue("project/dbadmin", str(project["dbadmin"]))
        if 'dbadminpwd' in project:
            self.settings.setValue("project/dbadminpwd",
                                   str(project["dbadminpwd"]))
        if 'projectdir' in project:
            self.settings.setValue("project/projectdir",
                                   str(project["projectdir"]))
        self.settings.setValue("project/max_scale", str(project["max_scale"]))

        module_name = project["appmodule"].lower()
        try:
            module_name = "veriso.modules." + module_name + ".applicationmodule"
            module = dynamic_import(module_name)
            application_module = module.ApplicationModule(self)
            application_module.init_gui()

            if project["max_scale"]:
                self.set_max_scale(project["max_scale"])
            else:
                self.unset_max_scale()

        except Exception as e:
            self.message_bar.pushMessage("VeriSO", str(e),
                                         level=Qgis.Critical, duration=0)

    def set_max_scale(self, scale):
        self.max_scale = scale
        self.iface.mapCanvas().scaleChanged.connect(
            self.zoom_to_max_scale)

    def unset_max_scale(self):
        self.max_scale = 0.0
        try:
            self.iface.mapCanvas().scaleChanged.disconnect(
                self.zoom_to_max_scale)
        except TypeError:
            pass

    def zoom_to_max_scale(self):
        canvas = self.iface.mapCanvas()
        if int(canvas.scale()) < int(self.max_scale):
            canvas.scaleChanged.disconnect(self.zoom_to_max_scale)
            canvas.zoomScale(self.max_scale)
            canvas.scaleChanged.connect(self.zoom_to_max_scale)

    def unload(self):
        self.iface.mainWindow().removeToolBar(self.toolbar)

    def toggle_defects_list_dock_visibility(self):
        """Show or hide the dock widget."""
        if self.defects_list_dock.isVisible():
            self.defects_list_dock.setVisible(False)
        else:
            self.defects_list_dock.setVisible(True)
            self.defects_list_dock.raise_()

    def _create_defects_list_dock(self):
        """Create dockwidget and tabify it with the legend."""

        self.defects_list_dock = DefectsListDock(self.iface)
        self.defects_list_dock.setObjectName('DefectsListDock')
        self.iface.addDockWidget(Qt.RightDockWidgetArea,
                                 self.defects_list_dock)
        legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend')
        if legend_tab:
            self.iface.mainWindow().tabifyDockWidget(
                legend_tab, self.defects_list_dock)
        self.defects_list_dock.setVisible(True)
        self.defects_list_dock.raise_()

    def _create_check_results_dock(self):
        """Create check results dockwidget"""

        self.CheckResultsDock = CheckResultsDock(self.iface)
        self.CheckResultsDock.setObjectName('CheckResultsDock')
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.CheckResultsDock)
        self.CheckResultsDock.clear_results()
        self.CheckResultsDock.setVisible(True)
        self.CheckResultsDock.raise_()
Beispiel #14
0
class WBNMViewer:
    """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",
                                   "WBNMViewer_{}.qm".format(locale))

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

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

        # print "** INITIALIZING WBNMViewer"
        self.pluginIsActive = False
        self.dockwidget = None

        # store processed data
        self.peaks = []
        self.hydrographs = []
        self.subareas = []
        self.storms = []

    # 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("WBNMViewer", message)

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

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

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

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

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

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

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

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

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

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

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

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

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

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

        self.actions.append(action)

        return action

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

        icon_path = ":/plugins/wbnm_viewer/icon.png"
        self.add_action(
            icon_path,
            text=self.tr(u"Open WBNM Viewer"),
            callback=self.run,
            parent=self.iface.mainWindow(),
        )

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

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

        # print "** CLOSING WBNMViewer"

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

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

        self.pluginIsActive = False

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

        # print "** UNLOAD WBNMViewer"

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

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

    def select_meta_file(self):
        filename, _filter = QFileDialog.getOpenFileName(
            self.dockwidget, "Select WBNM _Meta.out file", "", "*_Meta.out")
        return filename

    def populate_lists(self):
        processed_peaks = self.peaks[0]

        self.subareas = processed_peaks.subarea.sort_values().unique()
        self.storms = processed_peaks["storm"].sort_values().unique()
        self.aeps = processed_peaks["aep"].sort_values().unique()
        self.durations = processed_peaks["dur"].sort_values().unique()

        self.dockwidget.subareasListWidget.addItems(self.subareas)
        self.dockwidget.subareas2ListWidget.addItems(self.subareas)
        self.dockwidget.subareas3ListWidget.addItems(self.subareas)
        self.dockwidget.stormsListWidget.addItems(self.storms)
        self.dockwidget.aepsListWidget.addItems(
            sorted(self.aeps, key=lambda x: float(x)))
        self.dockwidget.aeps2ListWidget.addItems(
            sorted(self.aeps, key=lambda x: float(x)))
        self.dockwidget.durationsListWidget.addItems(
            sorted(self.durations, key=lambda x: int(x)))

    def process_meta_file(self):
        meta_file = self.select_meta_file()
        if meta_file:
            # process peaks
            processed_peaks = get_peaks(meta_file)
            self.peaks.append(processed_peaks)
            self.populate_lists()

            self.iface.messageBar().pushSuccess(
                "Success", "Meta file processed successfully!")

            # process hydrographs
            progressMessageBar = self.iface.messageBar().createMessage(
                "Processing hydrographs...")
            progress = QProgressBar()
            progress.setMaximum(
                len(self.peaks[0]["storm"].sort_values().unique()))
            progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            progressMessageBar.layout().addWidget(progress)
            self.iface.messageBar().pushWidget(progressMessageBar, Qgis.Info)

            processed_hydrographs = get_hydrographs(meta_file,
                                                    progress=progress)
            self.hydrographs.append(processed_hydrographs)

            self.iface.messageBar().clearWidgets()
            self.iface.messageBar().pushSuccess(
                "Success", "Hydrographs processed successfully!")

            model = DataFrameModel(self.peaks[0])
            self.dockwidget.dataTableView.setModel(model)

    def plot_hydrograph(self):
        subarea = self.dockwidget.subareasListWidget.selectedItems()[0].text()
        storm = self.dockwidget.stormsListWidget.selectedItems()[0].text()

        time = self.hydrographs[0][subarea][storm]["Time"]
        flow = self.hydrographs[0][subarea][storm]["Qout_OS"]
        fig = single_hydrograph(time, flow)
        update_plot(fig, self.dockwidget.chartWidget)

    def plot_box_whisker(self):
        subarea = self.dockwidget.subareas2ListWidget.selectedItems()[0].text()
        aep = self.dockwidget.aepsListWidget.selectedItems()[0].text()

        fig = box_plot(subarea, aep, self.peaks[0])
        update_plot(fig, self.dockwidget.boxWidget)

    def plot_ensembles(self):
        subarea = self.dockwidget.subareas3ListWidget.selectedItems()[0].text()
        aep = self.dockwidget.aeps2ListWidget.selectedItems()[0].text()
        duration = self.dockwidget.durationsListWidget.selectedItems()[0].text(
        )

        storms = self.peaks[0].loc[(self.peaks[0].subarea == subarea)
                                   & (self.peaks[0].aep == aep) &
                                   (self.peaks[0].dur
                                    == duration)].storm.unique()

        times = []
        flows = []
        for storm in storms:
            times.append(self.hydrographs[0][subarea][storm]["Time"])
            flows.append(self.hydrographs[0][subarea][storm]["Qout_OS"])

        fig = ensembles(times, flows, storms)
        update_plot(fig, self.dockwidget.ensembleWidget)

    def filter_storms(self):
        self.dockwidget.stormsListWidget.clear()
        filter_text = self.dockwidget.filterEdit.text()
        if filter_text == "":
            self.dockwidget.stormsListWidget.addItems(self.storms)
        else:
            filtered_storms = fnmatch.filter(self.storms,
                                             "*" + filter_text + "*")
            self.dockwidget.stormsListWidget.addItems(filtered_storms)

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

        if not self.pluginIsActive:
            self.pluginIsActive = True

            # print "** STARTING WBNMViewer"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = WBNMViewerDockWidget()
                self.dockwidget.plotButton.clicked.connect(
                    self.plot_hydrograph)
                self.dockwidget.filterEdit.textChanged.connect(
                    self.filter_storms)
                self.dockwidget.boxButton.clicked.connect(
                    self.plot_box_whisker)
                self.dockwidget.ensembleButton.clicked.connect(
                    self.plot_ensembles)

                # set up menubar
                self.window = QWidget()
                self.vbox = QVBoxLayout()
                self.window.setLayout(self.vbox)
                self.menuBar = QMenuBar()
                self.vbox.addWidget(self.menuBar)
                self.dockwidget.dockWidgetContents.layout().setSpacing(0)
                self.dockwidget.dockWidgetContents.layout().setMargin(0)
                self.dockwidget.dockWidgetContents.layout().setContentsMargins(
                    0, 0, 0, 0)
                self.dockwidget.dockWidgetContents.layout().insertWidget(
                    0, self.window)

                fileMenu = self.menuBar.addMenu("&File")
                self.loadWBNMMetaFile = QAction("Load WBNM *_Meta.out file",
                                                self.window)
                fileMenu.addAction(self.loadWBNMMetaFile)
                self.loadWBNMMetaFile.triggered.connect(self.process_meta_file)

                # set up data tab

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
Beispiel #15
0
    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
                                                   self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
                                                     self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
                                                     self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
                                                     self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
    def initTopMenu(self):
        topMenu = QMenuBar()

        ######################load
        loadMenu = topMenu.addMenu("Load")
        loadSecAct = loadMenu.addAction('Load .sec...')
        loadSecAct.triggered.connect(lambda: self.loadSec(clear=True))

        loadRteAct = loadMenu.addAction('Load .rte...')
        loadRteAct.triggered.connect(
            lambda: self.loadRteDialog.show(clearMode=True))

        loadSrAct = loadMenu.addAction('Load .sr...')
        loadSrAct.triggered.connect(lambda: self.loadSr(clear=True))

        ##################insert
        insertMenu = topMenu.addMenu("Insert")
        #insertMenu.setToolTipsVisible(True)
        insertMenu.hovered.connect(
            lambda action: action.parent().setToolTip(action.toolTip()))

        insertSecAct = insertMenu.addAction('Insert .sec...')
        insertSecAct.triggered.connect(
            lambda: self.loadSec(row=self.rowBox.value(), clear=False))
        insertSecAct.setToolTip(
            'insert .sec file using selected row and direction')

        insertRteAct = insertMenu.addAction('Insert .rte...')
        insertRteAct.triggered.connect(
            lambda: self.loadRteDialog.show(clearMode=False))
        insertRteAct.setToolTip('insert .rte file at row')

        insertSrAct = insertMenu.addAction('Insert .sr...')
        insertSrAct.triggered.connect(
            lambda: self.loadSr(row=self.rowBox.value(), clear=False))
        insertSrAct.setToolTip('insert .sr file at row')

        self.addFeatureAct = insertMenu.addAction('Add Selected Feature')
        self.addFeatureAct.setShortcut(QKeySequence(
            'Alt+1'))  #focus policy of dockwidget probably important here
        self.addFeatureAct.triggered.connect(self.addFeature)
        self.addFeatureAct.setToolTip(
            'Insert selected feature of layer using selected row and direction'
        )

        self.addDummyAct = insertMenu.addAction('Add Dummy')
        self.addDummyAct.setShortcut(QKeySequence(
            'Alt+2'))  #focus policy of dockwidget probably important here
        self.addDummyAct.triggered.connect(self.addDummy)
        self.addDummyAct.setToolTip('Insert dummy at row')

        ############################################save
        saveMenu = topMenu.addMenu("Save")

        saveSrAct = saveMenu.addAction('Save as .sr...')
        saveSrAct.triggered.connect(self.saveAsSr)

        saveSecAct = saveMenu.addAction('Save as .sec...')
        saveSecAct.triggered.connect(self.saveAsSec)

        saveRteAct = saveMenu.addAction('Save as .rte...')
        saveRteAct.triggered.connect(self.saveAsRte)

        #######################help

        helpMenu = topMenu.addMenu('Help')
        openHelpAct = helpMenu.addAction(
            'Open help (in your default web browser)')
        openHelpAct.triggered.connect(self.openHelp)

        self.main_widget.layout().setMenuBar(topMenu)
Beispiel #17
0
class DBManager(QMainWindow):

    def __init__(self, iface, parent=None):
        QMainWindow.__init__(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi()
        self.iface = iface

        # restore the window state
        settings = QgsSettings()
        self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray))
        self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray))

        self.tabs.currentChanged.connect(self.tabChanged)
        self.tree.selectedItemChanged.connect(self.itemChanged)
        self.itemChanged(None)

    def closeEvent(self, e):
        self.unregisterAllActions()
        # clear preview, this will delete the layer in preview tab
        self.preview.loadPreview(None)

        # save the window state
        settings = QgsSettings()
        settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState())
        settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry())

        QMainWindow.closeEvent(self, e)

    def refreshItem(self, item=None):
        with OverrideCursor(Qt.WaitCursor):
            try:
                if item is None:
                    item = self.tree.currentItem()
                self.tree.refreshItem(item)  # refresh item children in the db tree
            except BaseError as e:
                DlgDbError.showError(e, self)

    def itemChanged(self, item):
        with OverrideCursor(Qt.WaitCursor):
            try:
                self.reloadButtons()
                # clear preview, this will delete the layer in preview tab
                self.preview.loadPreview(None)
                self.refreshTabs()
            except BaseError as e:
                DlgDbError.showError(e, self)

    def reloadButtons(self):
        db = self.tree.currentDatabase()
        if not hasattr(self, '_lastDb'):
            self._lastDb = db

        elif db == self._lastDb:
            return

        # remove old actions
        if self._lastDb is not None:
            self.unregisterAllActions()

        # add actions of the selected database
        self._lastDb = db
        if self._lastDb is not None:
            self._lastDb.registerAllActions(self)

    def tabChanged(self, index):
        with OverrideCursor(Qt.WaitCursor):
            try:
                self.refreshTabs()
            except BaseError as e:
                DlgDbError.showError(e, self)

    def refreshTabs(self):
        index = self.tabs.currentIndex()
        item = self.tree.currentItem()
        table = self.tree.currentTable()

        # enable/disable tabs
        self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table is not None)
        self.tabs.setTabEnabled(self.tabs.indexOf(self.preview), table is not None and table.type in [table.VectorType,
                                                                                                      table.RasterType] and table.geomColumn is not None)
        # show the info tab if the current tab is disabled
        if not self.tabs.isTabEnabled(index):
            self.tabs.setCurrentWidget(self.info)

        current_tab = self.tabs.currentWidget()
        if current_tab == self.info:
            self.info.showInfo(item)
        elif current_tab == self.table:
            self.table.loadData(item)
        elif current_tab == self.preview:
            self.preview.loadPreview(item)

    def refreshActionSlot(self):
        self.info.setDirty()
        self.table.setDirty()
        self.preview.setDirty()
        self.refreshItem()

    def importActionSlot(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                     QgsMessageBar.INFO, self.iface.messageTimeout())
            return

        outUri = db.uri()
        schema = self.tree.currentSchema()
        if schema:
            outUri.setDataSource(schema.name, "", "", "")

        from .dlg_import_vector import DlgImportVector

        dlg = DlgImportVector(None, db, outUri, self)
        dlg.exec_()

    def exportActionSlot(self):
        table = self.tree.currentTable()
        if table is None:
            self.infoBar.pushMessage(self.tr("Select the table you want export to file."), QgsMessageBar.INFO,
                                     self.iface.messageTimeout())
            return

        inLayer = table.toMapLayer()
        if inLayer.type() != QgsMapLayer.VectorLayer:
            self.infoBar.pushMessage(
                self.tr("Select a vector or a tabular layer you want export."),
                QgsMessageBar.WARNING, self.iface.messageTimeout())
            return

        from .dlg_export_vector import DlgExportVector

        dlg = DlgExportVector(inLayer, table.database(), self)
        dlg.exec_()

        inLayer.deleteLater()

    def runSqlWindow(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                     QgsMessageBar.INFO, self.iface.messageTimeout())
            # force displaying of the message, it appears on the first tab (i.e. Info)
            self.tabs.setCurrentIndex(0)
            return

        from .dlg_sql_window import DlgSqlWindow

        query = DlgSqlWindow(self.iface, db, self)
        dbname = db.connection().connectionName()
        tabname = self.tr("Query ({0})").format(dbname)
        index = self.tabs.addTab(query, tabname)
        self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)
        query.nameChanged.connect(functools.partial(self.update_query_tab_name, index, dbname))

    def runSqlLayerWindow(self, layer):
        from .dlg_sql_layer_window import DlgSqlLayerWindow
        query = DlgSqlLayerWindow(self.iface, layer, self)
        lname = layer.name()
        tabname = self.tr("Layer ({0})").format(lname)
        index = self.tabs.addTab(query, tabname)
        # self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)

    def update_query_tab_name(self, index, dbname, queryname):
        if not queryname:
            queryname = self.tr("Query")
        tabname = u"%s (%s)" % (queryname, dbname)
        self.tabs.setTabText(index, tabname)

    def showSystemTables(self):
        self.tree.showSystemTables(self.actionShowSystemTables.isChecked())

    def registerAction(self, action, menuName, callback=None):
        """ register an action to the manager's main menu """
        if not hasattr(self, '_registeredDbActions'):
            self._registeredDbActions = {}

        if callback is not None:
            def invoke_callback(x):
                return self.invokeCallback(callback)

        if menuName is None or menuName == "":
            self.addAction(action)

            if menuName not in self._registeredDbActions:
                self._registeredDbActions[menuName] = list()
            self._registeredDbActions[menuName].append(action)

            if callback is not None:
                action.triggered.connect(invoke_callback)
            return True

        # search for the menu
        actionMenu = None
        helpMenuAction = None
        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue
            if a.menu() != self.menuHelp:
                helpMenuAction = a

            actionMenu = a
            break

        # not found, add a new menu before the help menu
        if actionMenu is None:
            menu = QMenu(menuName, self)
            if helpMenuAction is not None:
                actionMenu = self.menuBar.insertMenu(helpMenuAction, menu)
            else:
                actionMenu = self.menuBar.addMenu(menu)

        menu = actionMenu.menu()
        menuActions = menu.actions()

        # get the placeholder's position to insert before it
        pos = 0
        for pos in range(len(menuActions)):
            if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
                menuActions[pos].setVisible(True)
                break

        if pos < len(menuActions):
            before = menuActions[pos]
            menu.insertAction(before, action)
        else:
            menu.addAction(action)

        actionMenu.setVisible(True)  # show the menu

        if menuName not in self._registeredDbActions:
            self._registeredDbActions[menuName] = list()
        self._registeredDbActions[menuName].append(action)

        if callback is not None:
            action.triggered.connect(invoke_callback)

        return True

    def invokeCallback(self, callback, *params):
        """ Call a method passing the selected item in the database tree,
                the sender (usually a QAction), the plugin mainWindow and
                optionally additional parameters.

                This method takes care to override and restore the cursor,
                but also catches exceptions and displays the error dialog.
        """
        with OverrideCursor(Qt.WaitCursor):
            try:
                callback(self.tree.currentItem(), self.sender(), self, *params)
            except BaseError as e:
                # catch database errors and display the error dialog
                DlgDbError.showError(e, self)

    def unregisterAction(self, action, menuName):
        if not hasattr(self, '_registeredDbActions'):
            return

        if menuName is None or menuName == "":
            self.removeAction(action)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

            action.deleteLater()
            return True

        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue

            menu = a.menu()
            menuActions = menu.actions()

            menu.removeAction(action)
            if menu.isEmpty():  # hide the menu
                a.setVisible(False)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

                # hide the placeholder if there're no other registered actions
                if len(self._registeredDbActions[menuName]) <= 0:
                    for i in range(len(menuActions)):
                        if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"):
                            menuActions[i].setVisible(False)
                            break

            action.deleteLater()
            return True

        return False

    def unregisterAllActions(self):
        if not hasattr(self, '_registeredDbActions'):
            return

        for menuName in self._registeredDbActions:
            for action in list(self._registeredDbActions[menuName]):
                self.unregisterAction(action, menuName)
        del self._registeredDbActions

    def close_tab(self, index):
        widget = self.tabs.widget(index)
        if widget not in [self.info, self.table, self.preview]:
            self.tabs.removeTab(index)
            widget.deleteLater()

    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
                                                   self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
                                                     self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
                                                     self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
                                                     self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
Beispiel #18
0
class VeriSO(object):
    def __init__(self, iface):
        self.iface = iface
        self.message_bar = self.iface.messageBar()
        self.plugin_dir = os.path.dirname(__file__)

        self.settings = QSettings("CatAIS", "VeriSO")

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

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

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

        # members
        self.toolbar = None
        self.menubar_projects = None
        self.menubar_file = None
        self.menu_file = None
        self.import_project = None
        self.delete_project = None
        self.menubar_settings = None
        self.menu_projects = None
        self.menu_settings = None
        self.options = None
        self.import_dlg = None
        self.delete_dlg = None
        self.options_dlg = None

    # noinspection PyPep8Naming
    def initGui(self):
        icon_path = ':/plugins/veriso/icon.png'

        # Qt offers some themes which you also can change in QGIS settings.
        # Since the background color of the menu toolbar can be different than
        # the background color of the button toolbars, the veriso toolbar
        # doesn't suit well. So we change it manually by finding out the
        # background color of one (e.g. file) toolbar and applying it
        # to the veriso toolbar.
        # This approach works (well?) for xfce 4.12 and standard (gtk+) theme.
        # We need to do this also in other methods when we add new menus :-(

        # 20150406: Only change QToolBar background color.
        # Otherweise the later added menus will have white hover color and
        # other quirks.
        # Strange: QToolBar stylesheet seems to need an border.
        background_color = self.iface.mainWindow().menuBar().palette().color(
            QPalette.Window).name()

        # main toolbar
        self.toolbar = self.iface.addToolBar("VeriSO")
        self.toolbar.setStyleSheet("QToolBar {background-color: " +
                                   background_color + "; border: 0px solid " +
                                   background_color + ";}")

        self.toolbar.setObjectName("VeriSO.Main.ToolBar")
        self.toolbar.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        # projects
        self.menubar_projects = QMenuBar()
        self.menubar_projects.setObjectName("VeriSO.Main.ProjectsMenuBar")
        self.menubar_projects.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred))
        self.menu_projects = QMenu()
        self.menu_projects.setTitle(tr("Projects"))
        self.menubar_projects.addMenu(self.menu_projects)

        # files
        self.menubar_file = QMenuBar()
        self.menubar_file.setObjectName("VeriSO.Main.FileMenuBar")
        self.menubar_file.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_file = QMenu()
        self.menu_file.setTitle(tr("File"))
        self.import_project = QAction(tr("Import project"),
                                      self.iface.mainWindow())
        self.import_project.triggered.connect(self.do_import_project)
        self.delete_project = QAction(tr("Delete project"),
                                      self.iface.mainWindow())
        self.delete_project.triggered.connect(self.do_delete_project)
        self.menu_file.addActions([self.import_project, self.delete_project])
        self.menubar_file.addMenu(self.menu_file)

        # settings
        self.menubar_settings = QMenuBar()
        self.menubar_settings.setObjectName("VeriSO.Main.SettingsMenuBar")
        self.menubar_settings.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        self.menu_settings = QMenu()
        self.menu_settings.setTitle(tr("Settings"))

        self.options = QAction(tr("Options"), self.iface.mainWindow())
        self.options.triggered.connect(self.do_options)
        self.menu_settings.addActions([self.options])
        self.menubar_settings.addMenu(self.menu_settings)

        # Add menus to toolbar.
        self.toolbar.addWidget(self.menubar_projects)
        self.toolbar.addWidget(self.menubar_file)
        self.toolbar.addWidget(self.menubar_settings)

        # Initial load of project menu entries.
        self.do_load_projects_database()

    def do_import_project(self):
        from .base.file.importproject import ImportProjectDialog
        self.import_dlg = ImportProjectDialog(self.iface)
        if self.import_dlg.init_gui():
            self.import_dlg.show()
            self.import_dlg.projectsDatabaseHasChanged.connect(
                self.do_load_projects_database)

    def do_delete_project(self):
        from .base.file.deleteproject import DeleteProjectDialog
        self.delete_dlg = DeleteProjectDialog(self.iface)
        if self.delete_dlg.init_gui():
            self.delete_dlg.show()
            self.delete_dlg.projectsDatabaseHasChanged.connect(
                self.do_load_projects_database)

    def do_options(self):
        from .base.settings.options import OptionsDialog
        self.options_dlg = OptionsDialog(self.iface)
        self.options_dlg.init_gui()
        self.options_dlg.show()
        self.options_dlg.projectsDatabaseHasChanged.connect(
            self.do_load_projects_database)

    def do_load_projects_database(self):
        projects = get_projects()

        if projects is not None:
            grouped_projects = {}
            for project in projects:
                module_name = project["appmodulename"]
                try:
                    module_list = grouped_projects[module_name]
                except KeyError:
                    module_list = []

                module_list.append(project)
                grouped_projects[module_name] = module_list

            self.menu_projects.clear()
            for key in sorted(grouped_projects):
                modules = grouped_projects[key]
                group_menu = self.menu_projects.addMenu(str(key))
                sorted_projects_list = sorted(modules,
                                              key=lambda k: k['displayname'])
                for project in sorted_projects_list:
                    action = QAction(str(project["displayname"]),
                                     self.iface.mainWindow())
                    group_menu.addAction(action)
                    action.triggered.connect(
                        lambda checked, active_project=project: self.
                        do_load_project(active_project))

    def do_load_project(self, project):
        self.settings.setValue("project/id", str(project["id"]))
        self.settings.setValue("project/displayname",
                               str(project["displayname"]))
        self.settings.setValue("project/appmodule", str(project["appmodule"]))
        self.settings.setValue("project/appmodulename",
                               str(project["appmodulename"]))
        self.settings.setValue("project/ilimodelname",
                               str(project["ilimodelname"]))
        self.settings.setValue("project/epsg", str(project["epsg"]))
        self.settings.setValue("project/provider", str(project["provider"]))
        self.settings.setValue("project/dbhost", str(project["dbhost"]))
        self.settings.setValue("project/dbport", str(project["dbport"]))
        self.settings.setValue("project/dbname", str(project["dbname"]))
        self.settings.setValue("project/dbschema", str(project["dbschema"]))
        self.settings.setValue("project/dbuser", str(project["dbuser"]))
        self.settings.setValue("project/dbpwd", str(project["dbpwd"]))
        self.settings.setValue("project/dbadmin", str(project["dbadmin"]))
        self.settings.setValue("project/dbadminpwd",
                               str(project["dbadminpwd"]))
        self.settings.setValue("project/projectdir",
                               str(project["projectdir"]))

        module_name = str(project["appmodule"]).lower()
        try:
            module_name = "veriso.modules." + module_name + ".applicationmodule"
            module = dynamic_import(module_name)
            application_module = module.ApplicationModule(
                self.iface, self.toolbar, self.locale_path)
            application_module.init_gui()

        except Exception as e:
            self.message_bar.pushMessage("VeriSO",
                                         str(e),
                                         QgsMessageBar.CRITICAL,
                                         duration=0)

    def unload(self):
        self.iface.mainWindow().removeToolBar(self.toolbar)