Example #1
0
class LocationLab:

    def __init__(self, iface):
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.plugin_dir = os.path.dirname(__file__)
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'LocationLab{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
        self.actions = []
        self.menu = QMenu(self.iface.mainWindow())
        self.menu.setObjectName('locationLab')
        self.menu.setTitle(u'&Location Lab')
        # Init modules
        self.catchmentsModule = CatchmentsModule(self)
        self.infoModule = InfoModule(self)
        

    def tr(self, message):
        return QCoreApplication.translate('Catchments', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        checkable=False
            ):

        icon = QIcon(icon_path)
        action = QAction(icon, text, self.iface.mainWindow())
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)
        action.setCheckable(checkable)
        self.menu.addAction(action)
        self.actions.append(action)
        return action

    def initGui(self):
        self.add_action(
            ':/plugins/LocationLab/catchments.png',
            text=self.tr(u'Catchments'),
            callback=self.catchmentsModule.show)
        self.add_action(
           ':/plugins/LocationLab/info.png',
           text=self.tr(u'Info'),
           callback=self.infoModule.show)
        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu)

    def unload(self):
        self.menu.deleteLater()
    def setModel(self, model):
        super( DataLaneSummaryTableView, self ).setModel(model)

        self._retained = []
        roleIndex = 0
        for column in range( LaneColumn.NumColumns, model.columnCount(), DatasetInfoColumn.NumColumns ):
            menu = QMenu(parent=self)
            menu.setObjectName( "SummaryTable_AddButton_{}".format( roleIndex ) )
            self._retained.append(menu)
            menu.addAction( "Add File(s)..." ).triggered.connect( partial(self.addFilesRequested.emit, roleIndex) )
            menu.addAction( "Add Volume from Stack..." ).triggered.connect( partial(self.addStackRequested.emit, roleIndex) )
            menu.addAction( "Add Many by Pattern..." ).triggered.connect( partial(self.addByPatternRequested.emit, roleIndex) )
            
            button = QPushButton("Add File(s)...", self)
            button.setMenu( menu )
            self.addFilesButtons[roleIndex] = button

            lastRow = self.model().rowCount()-1
            modelIndex = self.model().index( lastRow, column )
            self.setIndexWidget( modelIndex, button )
            
            roleIndex += 1

        # TODO: Implement support for the labelable flag again...
        self.setColumnHidden(LaneColumn.LabelsAllowed, True)
    def setModel(self, model):
        super(DataLaneSummaryTableView, self).setModel(model)

        self._retained = []
        roleIndex = 0
        for column in range(LaneColumn.NumColumns, model.columnCount(),
                            DatasetInfoColumn.NumColumns):
            menu = QMenu(parent=self)
            menu.setObjectName("SummaryTable_AddButton_{}".format(roleIndex))
            self._retained.append(menu)
            menu.addAction("Add File(s)...").triggered.connect(
                partial(self.addFilesRequested.emit, roleIndex))
            menu.addAction("Add Volume from Stack...").triggered.connect(
                partial(self.addStackRequested.emit, roleIndex))
            menu.addAction("Add Many by Pattern...").triggered.connect(
                partial(self.addByPatternRequested.emit, roleIndex))

            button = QPushButton("Add File(s)...", self)
            button.setMenu(menu)
            self.addFilesButtons[roleIndex] = button

            lastRow = self.model().rowCount() - 1
            modelIndex = self.model().index(lastRow, column)
            self.setIndexWidget(modelIndex, button)

            roleIndex += 1

        # TODO: Implement support for the labelable flag again...
        self.setColumnHidden(LaneColumn.LabelsAllowed, True)
Example #4
0
    def labelingContextMenu(self,names,op,position5d):
        menu = QMenu(self)
        menu.setObjectName("carving_context_menu")
        posItem = menu.addAction("position %d %d %d" % (position5d[1], position5d[2], position5d[3]))
        posItem.setEnabled(False)
        menu.addSeparator()
        for name in names:
            submenu = QMenu(name,menu)
            
            # Load
            loadAction = submenu.addAction("Load %s" % name)
            loadAction.triggered.connect( partial(op.loadObject, name) )
            
            # Delete
            def onDelAction(_name):
                self.confirmAndDelete([_name])
                if self.render and self._renderMgr.ready:
                    self._update_rendering()
            delAction = submenu.addAction("Delete %s" % name)
            delAction.triggered.connect( partial(onDelAction, name) )

            if self.render:
                if name in self._shownObjects3D:
                    # Remove
                    def onRemove3D(_name):
                        label = self._shownObjects3D.pop(_name)
                        self._renderMgr.removeObject(label)
                        self._update_rendering()
                    removeAction = submenu.addAction("Remove %s from 3D view" % name)
                    removeAction.triggered.connect( partial(onRemove3D, name) )
                else:
                    # Show
                    def onShow3D(_name):
                        label = self._renderMgr.addObject()
                        self._shownObjects3D[_name] = label
                        self._update_rendering()
                    showAction = submenu.addAction("Show 3D %s" % name)
                    showAction.triggered.connect( partial(onShow3D, name ) )
                        
            menu.addMenu(submenu)

        if names:
            menu.addSeparator()

        menu.addSeparator()
        if self.render:
            showSeg3DAction = menu.addAction( "Show Editing Segmentation in 3D" )
            showSeg3DAction.setCheckable(True)
            showSeg3DAction.setChecked( self._showSegmentationIn3D )
            showSeg3DAction.triggered.connect( self._toggleSegmentation3D )
        
        if op.dataIsStorable():
            menu.addAction("Save object").triggered.connect( self.onSaveButton )
        menu.addAction("Browse objects").triggered.connect( self.onShowObjectNames )
        menu.addAction("Segment").triggered.connect( self.onSegmentButton )
        menu.addAction("Clear").triggered.connect( self.topLevelOperatorView.clearCurrentLabeling )
        return menu
Example #5
0
 def addMenu(self, parent, name, title, icon_path):
     """
     Adds a QMenu
     """
     child = QMenu(parent)
     child.setObjectName(name)
     child.setTitle(self.tr(title))
     child.setIcon(QIcon(icon_path))
     parent.addMenu(child)
     return child
Example #6
0
def install_shortcuts(obj, actions, ide):
    short = resources.get_shortcut
    for action in actions:
        short_key = action.get("shortcut", None)
        action_data = action.get("action", None)
        connect = action.get("connect", None)

        shortcut = None
        item_ui = None
        func = None
        if connect:
            func = getattr(obj, connect, None)

        if short_key and not action_data:
            if isinstance(short_key, QKeySequence):
                shortcut = QShortcut(short_key, ide)
            else:
                shortcut = QShortcut(short(short_key), ide)
            shortcut.setContext(Qt.ApplicationShortcut)
            if isinstance(func, collections.Callable):
                ide.connect(shortcut, SIGNAL("activated()"), func)
        if action_data:
            is_menu = action_data.get('is_menu', False)
            if is_menu:
                item_ui = QMenu(action_data['text'], ide)
            else:
                item_ui = QAction(action_data['text'], ide)
                object_name = "%s.%s" % (obj.__class__.__name__, connect)
                item_ui.setObjectName(object_name)
            image_name = action_data.get('image', None)
            section = action_data.get('section', None)
            weight = action_data.get('weight', None)
            keysequence = action_data.get('keysequence', None)
            if image_name:
                if isinstance(image_name, int):
                    icon = ide.style().standardIcon(image_name)
                    item_ui.setIcon(icon)
                elif isinstance(image_name, str):
                    icon = QIcon(":img/" + image_name)
                    item_ui.setIcon(icon)
            if short_key and not is_menu:
                item_ui.setShortcut(short(short_key))
                item_ui.setShortcutContext(Qt.ApplicationShortcut)
            elif keysequence and not is_menu:
                item_ui.setShortcut(short(keysequence))
                item_ui.setShortcutContext(Qt.ApplicationShortcut)
            if isinstance(func, collections.Callable) and not is_menu:
                ide.connect(item_ui, SIGNAL("triggered()"), func)
            if section and section[0] is not None and weight:
                ide.register_menuitem(item_ui, section, weight)
                if image_name and not is_menu:
                    ide.register_toolbar(item_ui, section, weight)

        if short_key and shortcut:
            ide.register_shortcut(short_key, shortcut, item_ui)
Example #7
0
def install_shortcuts(obj, actions, ide):
    short = resources.get_shortcut
    for action in actions:
        short_key = action.get("shortcut", None)
        action_data = action.get("action", None)
        connect = action.get("connect", None)

        shortcut = None
        item_ui = None
        func = None
        if connect:
            func = getattr(obj, connect, None)

        if short_key and not action_data:
            if isinstance(short_key, QKeySequence):
                shortcut = QShortcut(short_key, ide)
            else:
                shortcut = QShortcut(short(short_key), ide)
            shortcut.setContext(Qt.ApplicationShortcut)
            if isinstance(func, collections.Callable):
                ide.connect(shortcut, SIGNAL("activated()"), func)
        if action_data:
            is_menu = action_data.get('is_menu', False)
            if is_menu:
                item_ui = QMenu(action_data['text'], ide)
            else:
                item_ui = QAction(action_data['text'], ide)
                object_name = "%s.%s" % (obj.__class__.__name__, connect)
                item_ui.setObjectName(object_name)
            image_name = action_data.get('image', None)
            section = action_data.get('section', None)
            weight = action_data.get('weight', None)
            keysequence = action_data.get('keysequence', None)
            if image_name:
                if isinstance(image_name, int):
                    icon = ide.style().standardIcon(image_name)
                    item_ui.setIcon(icon)
                elif isinstance(image_name, str):
                    icon = QIcon(":img/" + image_name)
                    item_ui.setIcon(icon)
            if short_key and not is_menu:
                item_ui.setShortcut(short(short_key))
                item_ui.setShortcutContext(Qt.ApplicationShortcut)
            elif keysequence and not is_menu:
                item_ui.setShortcut(short(keysequence))
                item_ui.setShortcutContext(Qt.ApplicationShortcut)
            if isinstance(func, collections.Callable) and not is_menu:
                ide.connect(item_ui, SIGNAL("triggered()"), func)
            if section and section[0] is not None and weight:
                ide.register_menuitem(item_ui, section, weight)
                if image_name and not is_menu:
                    ide.register_toolbar(item_ui, section, weight)

        if short_key and shortcut:
            ide.register_shortcut(short_key, shortcut, item_ui)
Example #8
0
    def _initTableViews(self):
        self.fileInfoTabWidget.setTabText(0, "Summary")
        self.laneSummaryTableView.setModel(DataLaneSummaryTableModel(self, self.topLevelOperator))
        self.laneSummaryTableView.dataLaneSelected.connect(self.showDataset)
        self.laneSummaryTableView.addFilesRequested.connect(self.handleAddFiles)
        self.laneSummaryTableView.addStackRequested.connect(self.handleAddStack)
        self.laneSummaryTableView.addByPatternRequested.connect(self.handleAddByPattern)
        self.removeLaneButton.clicked.connect(self.handleRemoveLaneButtonClicked)
        self.laneSummaryTableView.removeLanesRequested.connect(self.handleRemoveLaneButtonClicked)

        self._retained = []  # Retain menus so they don't get deleted
        self._detailViewerWidgets = []
        for roleIndex, role in enumerate(self.topLevelOperator.DatasetRoles.value):
            detailViewer = DataDetailViewerWidget(self, self.topLevelOperator, roleIndex)
            self._detailViewerWidgets.append(detailViewer)

            # Button
            menu = QMenu(parent=self)
            menu.setObjectName("addFileButton_role_{}".format(roleIndex))
            menu.addAction("Add File(s)...").triggered.connect(partial(self.handleAddFiles, roleIndex))
            menu.addAction("Add Volume from Stack...").triggered.connect(partial(self.handleAddStack, roleIndex))
            menu.addAction("Add Many by Pattern...").triggered.connect(partial(self.handleAddByPattern, roleIndex))
            detailViewer.appendButton.setMenu(menu)
            self._retained.append(menu)

            # Context menu
            detailViewer.datasetDetailTableView.replaceWithFileRequested.connect(
                partial(self.handleReplaceFile, roleIndex)
            )
            detailViewer.datasetDetailTableView.replaceWithStackRequested.connect(
                partial(self.replaceWithStack, roleIndex)
            )
            detailViewer.datasetDetailTableView.editRequested.connect(partial(self.editDatasetInfo, roleIndex))
            detailViewer.datasetDetailTableView.resetRequested.connect(partial(self.handleClearDatasets, roleIndex))

            # Drag-and-drop
            detailViewer.datasetDetailTableView.addFilesRequested.connect(
                partial(self.addFileNames, roleIndex=roleIndex)
            )

            # Selection handling
            def showFirstSelectedDataset(_roleIndex, lanes):
                if lanes:
                    self.showDataset(lanes[0], _roleIndex)

            detailViewer.datasetDetailTableView.dataLaneSelected.connect(partial(showFirstSelectedDataset, roleIndex))

            self.fileInfoTabWidget.insertTab(roleIndex, detailViewer, role)

        self.fileInfoTabWidget.currentChanged.connect(self.handleSwitchTabs)
        self.fileInfoTabWidget.setCurrentIndex(0)
Example #9
0
    def mkEditMenu(self, interface):

        def deleteIntermediate(value):
            self.deleteInterface(interface)
            self.updateToolbar()

        def editIntermediate(value):
            self.editIface(interface)
            self.updateToolbar()

        edit_interface = QAction(QIcon(":icons/edit"), tr("Edit interface parameters"), self)
        self.connect(edit_interface, SIGNAL('triggered(bool)'), editIntermediate )

        actions = [edit_interface]

        if interface.freeForIp():
            def addNetIntermediate(value):
                self.newNet(interface)
                self.updateToolbar()

            add_net = QAction(QIcon(":icons/addnetwork"), tr("Add a network to this interface"), self)
            self.connect(add_net, SIGNAL('triggered(bool)'), addNetIntermediate )

            actions.append(add_net)

        propose_del_action = True
        if isinstance(interface, Ethernet):
            if hasIPConfiguration(interface):
                del_message = tr("Delete configuration")
            else:
                propose_del_action = False
        else:
            del_message = tr("Delete this interface")

        if interface.hasHA():
            propose_del_action = False

        if propose_del_action:
            del_interface = QAction(QIcon(":icons/delete"), del_message, self)
            self.connect(del_interface, SIGNAL('triggered(bool)'), deleteIntermediate)
            actions.append(del_interface)

        menu = QMenu(self)
        menu.setObjectName("menu_%s" % interface.fullName())
        for action in actions:
            menu.addAction(action)

        return menu
Example #10
0
 def labelingContextMenu(self,names,op,position5d):
     menu = QMenu(self)
     menu.setObjectName("carving_context_menu")
     menu.addAction("position %d %d %d" % (position5d[1], position5d[2], position5d[3]))
     menu.addSeparator()
     for name in names:
         submenu = QMenu(name,menu)
         submenu.addAction("Load %s" % name)
         submenu.addAction("Delete %s" % name)
         if self.render:
             if name in self._shownObjects3D:
                 submenu.addAction("Remove %s from 3D view" % name)
             else:
                 submenu.addAction("Show 3D %s" % name)
         menu.addMenu(submenu)
     if names:menu.addSeparator()
     
     if op.dataIsStorable():
         menu.addAction("Save objects")
     menu.addAction("Browse objects")
     menu.addAction("Segment")
     menu.addAction("Clear")
     return menu
Example #11
0
class MainWindow(QMainWindow, object):
    """
    QMainWindow displays pipeline
    Parameters
    ----------
    port : str
        used port to communicate with pipeline
        Note: The firewall must be configure to accept input/output on this port
    """

    def __init__(self, port):
        super(MainWindow, self).__init__()
        self.setupUi(port)

    def setupUi(self, port):
        self.setObjectName("MainWindow")
        self.resize(600,600)
        self.centralwidget = QWidget(self)
        p = self.centralwidget.palette()
        self.centralwidget.setAutoFillBackground(True)
        p.setColor(self.centralwidget.backgroundRole(), QColor(126, 135, 152))
        self.centralwidget.setPalette(p)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 808, 25))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.actionQuit = QAction(self)
        self.actionQuit.setObjectName("actionQuit")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
        self.menubar.addAction(self.menuFile.menuAction())
        self.actionReset = QAction(self)
        self.actionReset.setObjectName("reset")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionReset)
        self.menubar.addAction(self.menuFile.menuAction())
        # add other GUI objects
        self.graph_widget = GraphWidget(self.statusbar)
        self.gridLayout.addWidget(self.graph_widget, 1, 11, 10, 10 )
        pixmap = QPixmap(':/images/cta-logo-mini.png')
        lbl = QLabel()
        lbl.setPixmap(pixmap)
        self.gridLayout.addWidget(lbl, 0, 0)
        p = self.graph_widget.palette()
        self.graph_widget.setAutoFillBackground(True)
        p.setColor(
            self.graph_widget.backgroundRole(),QColor(255,255,255))# QColor(226, 235, 252))
        self.graph_widget.setPalette(p)
        self.quitButton = QPushButton()  # self.centralwidget)
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setText(QApplication.translate
                                ("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.gridLayout.addWidget(self.quitButton, 12, 0, 1, 1)
        self.info_label = InfoLabel(0,4)
        self.info_label.setAutoFillBackground(True)
        self.gridLayout.addWidget(self.info_label,1, 0, 1, 5)
        #self.info_label.setAlignment(PyQt4.Qt.AlignCenter);
        palette = QPalette()
        palette.setColor(self.info_label.backgroundRole(),Qt.lightGray)
        self.info_label.setPalette(palette)
        QObject.connect(
            self.quitButton, SIGNAL("clicked()"), self.stop)
        QObject.connect(
            self.actionQuit, SIGNAL("triggered()"), self.stop)
        QMetaObject.connectSlotsByName(self)
        self.retranslateUi()
        QObject.connect(
            self.actionQuit, SIGNAL("triggered()"), self.close)
        QMetaObject.connectSlotsByName(self)
        # Create GuiConnexion for ZMQ comminucation with pipeline
        self.guiconnection = GuiConnexion(gui_port=port, statusBar=self.statusbar)
        self.guiconnection.message.connect(self.graph_widget.pipechange)
        self.guiconnection.message.connect(self.info_label.pipechange)
        self.guiconnection.reset_message.connect(self.graph_widget.reset)
        self.guiconnection.reset_message.connect(self.info_label.reset)
        self.guiconnection.mode_message.connect(self.info_label.mode_receive)
        QObject.connect(
            self.actionReset, SIGNAL("triggered()"), self.guiconnection.reset)
        QMetaObject.connectSlotsByName(self)
        # start the process
        self.guiconnection.start()

    def retranslateUi(self):
        self.setWindowTitle(QApplication.translate(
            "ctapipe flow based GUI", "ctapipe flow based GUI", None, QApplication.UnicodeUTF8))
        self.menuFile.setTitle(QApplication.translate(
            "MainWindow", "File", None, QApplication.UnicodeUTF8))
        self.actionQuit.setText(QApplication.translate(
            "MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.actionReset.setText(QApplication.translate(
            "MainWindow", "Reset", None, QApplication.UnicodeUTF8))

    def stop(self):
        """Method connect (via Qt slot) to exit button
        Stops self.guiconnection (for ZMQ communication) process.
        Close main_windows
        """
        self.guiconnection.finish()
        self.guiconnection.join()
        self.close()

    def closeEvent(self, event):
            self.guiconnection.finish()
            self.guiconnection.join()
            event.accept()  # let the window close
Example #12
0
class FreeseerApp(QMainWindow):
    def __init__(self, config):
        super(FreeseerApp, self).__init__()
        self.config = config
        self.icon = QIcon()
        self.icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")),
                            QIcon.Normal, QIcon.Off)
        self.setWindowIcon(self.icon)

        self.aboutDialog = AboutDialog()
        self.aboutDialog.setModal(True)

        self.logDialog = LogDialog()

        #
        # Translator
        #
        self.app = QApplication.instance()
        self.current_language = None
        self.uiTranslator = QTranslator()
        self.uiTranslator.load(":/languages/tr_en_US.qm")
        self.app.installTranslator(self.uiTranslator)
        self.langActionGroup = QActionGroup(self)
        self.langActionGroup.setExclusive(True)
        QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8'))
        self.connect(self.langActionGroup, SIGNAL('triggered(QAction *)'),
                     self.translate)
        # --- Translator

        #
        # Setup Menubar
        #
        self.menubar = self.menuBar()

        self.menubar.setGeometry(QRect(0, 0, 500, 50))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        self.menuLanguage = QMenu(self.menubar)
        self.menuLanguage.setObjectName(_fromUtf8("menuLanguage"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName(_fromUtf8("menuHelp"))

        exitIcon = QIcon.fromTheme("application-exit")
        self.actionExit = QAction(self)
        self.actionExit.setShortcut("Ctrl+Q")
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setIcon(exitIcon)

        helpIcon = QIcon.fromTheme("help-contents")
        self.actionOnlineHelp = QAction(self)
        self.actionOnlineHelp.setObjectName(_fromUtf8("actionOnlineHelp"))
        self.actionOnlineHelp.setIcon(helpIcon)

        self.actionAbout = QAction(self)
        self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
        self.actionAbout.setIcon(self.icon)

        self.actionLog = QAction(self)
        self.actionLog.setObjectName(_fromUtf8("actionLog"))
        self.actionLog.setShortcut("Ctrl+L")

        # Actions
        self.menuFile.addAction(self.actionExit)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addAction(self.actionLog)
        self.menuHelp.addAction(self.actionOnlineHelp)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuLanguage.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.setupLanguageMenu()
        # --- End Menubar

        self.connect(self.actionExit, SIGNAL('triggered()'), self.close)
        self.connect(self.actionAbout, SIGNAL('triggered()'),
                     self.aboutDialog.show)
        self.connect(self.actionLog, SIGNAL('triggered()'),
                     self.logDialog.show)
        self.connect(self.actionOnlineHelp, SIGNAL('triggered()'),
                     self.openOnlineHelp)

        self.retranslateFreeseerApp()
        self.aboutDialog.aboutWidget.retranslate("en_US")

    def openOnlineHelp(self):
        """Opens a link to the Freeseer Online Help"""
        url = QUrl("http://freeseer.readthedocs.org")
        QDesktopServices.openUrl(url)

    def translate(self, action):
        """Translates the GUI via menu action.

        When a language is selected from the language menu, this function is
        called and the language to be changed to is retrieved.
        """
        self.current_language = str(
            action.data().toString()).strip("tr_").rstrip(".qm")

        log.info("Switching language to: %s" % action.text())
        self.uiTranslator.load(":/languages/tr_%s.qm" % self.current_language)
        self.app.installTranslator(self.uiTranslator)

        self.retranslateFreeseerApp()
        self.aboutDialog.aboutWidget.retranslate(self.current_language)
        self.retranslate()
        self.logDialog.retranslate()

    def retranslate(self):
        """
        Reimplement this function to provide translations to your app.
        """
        pass

    def retranslateFreeseerApp(self):
        #
        # Menubar
        #
        self.menuFile.setTitle(self.app.translate("FreeseerApp", "&File"))
        self.menuLanguage.setTitle(
            self.app.translate("FreeseerApp", "&Language"))
        self.menuHelp.setTitle(self.app.translate("FreeseerApp", "&Help"))

        self.actionExit.setText(self.app.translate("FreeseerApp", "&Quit"))
        self.actionAbout.setText(self.app.translate("FreeseerApp", "&About"))
        self.actionLog.setText(self.app.translate("FreeseerApp", "View &Log"))
        self.actionOnlineHelp.setText(
            self.app.translate("FreeseerApp", "Online Documentation"))
        # --- Menubar

    def setupLanguageMenu(self):
        self.languages = QDir(":/languages").entryList()

        if self.current_language is None:
            self.current_language = QLocale.system().name(
            )  # Retrieve Current Locale from the operating system.
            log.debug("Detected user's locale as %s" % self.current_language)

        for language in self.languages:
            translator = QTranslator(
            )  # Create a translator to translate Language Display Text.
            translator.load(":/languages/%s" % language)
            language_display_text = translator.translate(
                "Translation", "Language Display Text")

            languageAction = QAction(self)
            languageAction.setCheckable(True)
            languageAction.setText(language_display_text)
            languageAction.setData(language)
            self.menuLanguage.addAction(languageAction)
            self.langActionGroup.addAction(languageAction)
class ProfilesPlugin:

    def __init__(self, iface):
        self.iface = iface
        QSettings().setValue('/UI/Customization/enabled', False)

        try:
            from profiles.tests import testerplugin
            from qgistester.tests import addTestModule
            addTestModule(testerplugin, 'Profiles plugin')
        except:
            pass

        self.userProfileAction = None
        self.profilesMenu = None

        iface.initializationCompleted.connect(self.initProfile)

    def unload(self):
        if self.profilesMenu is not None:
            self.profilesMenu.deleteLater()
        self.iface.removePluginMenu(self.tr('Profiles'), self.autoloadAction)
        self.iface.removePluginMenu(self.tr('Profiles'), self.saveProfileAction)
        try:
            from profiles.tests import testerplugin
            from qgistester.tests import removeTestModule
            removeTestModule(testerplugin, 'Profiles plugin')
        except:
            pass
        saveCurrentPluginState()

    def initGui(self):
        self.addMenus()

    def addMenus(self):
        if self.profilesMenu is not None:
            self.profilesMenu.clear()
        self.actions = defaultdict(list)
        settings = QSettings()
        defaultProfile = settings.value('profilesplugin/LastProfile', 'Default', unicode)
        autoLoad = settings.value('profilesplugin/AutoLoad', False, bool)
        for k, v in profiles.iteritems():
            action = QAction(k, self.iface.mainWindow())
            action.setCheckable(True)
            if k == defaultProfile and autoLoad:
                action.setChecked(True)
            action.triggered.connect(lambda _, menuName=k: self.applyProfile(menuName))
            action.setObjectName('mProfilesPlugin_' + k)
            self.actions[v.group].append(action)

        actions = self.iface.mainWindow().menuBar().actions()
        settingsMenu = None
        self.profilesGroup = QActionGroup(self.iface.mainWindow())
        if self.profilesMenu is None:
            for action in actions:
                if action.menu().objectName() == 'mSettingsMenu':
                    settingsMenu = action.menu()
                    self.profilesMenu = QMenu(settingsMenu)
                    self.profilesMenu.setObjectName('mProfilesPlugin')
                    self.profilesMenu.setTitle(self.tr('Profiles'))
                    settingsMenu.addMenu(self.profilesMenu)
                    break

        if self.profilesMenu is not None:
            for k,v in self.actions.iteritems():
                submenu = QMenu(self.profilesMenu)
                submenu.setObjectName('mProfilesPlugin_submenu_' + k)
                submenu.setTitle(k)
                for action in v:
                    self.profilesGroup.addAction(action)
                    submenu.addAction(action)
                self.profilesMenu.addMenu(submenu)

        self.profilesMenu.addSeparator()

        settings = QSettings()
        def _setAutoLoad():
            settings.setValue('profilesplugin/AutoLoad', self.autoloadAction.isChecked())

        self.autoloadAction = QAction(self.tr('Auto-load last profile on QGIS start'), iface.mainWindow())
        self.autoloadAction.setCheckable(True)
        autoLoad = settings.value('profilesplugin/AutoLoad', False, bool)
        self.autoloadAction.setChecked(autoLoad)
        self.autoloadAction.setObjectName('mProfilesPluginAutoLoad')
        self.autoloadAction.triggered.connect(_setAutoLoad)
        self.profilesMenu.addAction(self.autoloadAction)

        self.saveProfileAction = QAction(self.tr('Profiles manager...'),
                                         self.iface.mainWindow())
        self.saveProfileAction.setObjectName('mProfilesPluginProfilesManager')
        self.saveProfileAction.triggered.connect(self.saveProfile)
        self.profilesMenu.addAction(self.saveProfileAction)

        self.showHelpAction = QAction(self.tr('Help'), self.iface.mainWindow())
        self.showHelpAction.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.showHelpAction.setObjectName('mProfilesPluginShowHelp')
        self.showHelpAction.triggered.connect(self.showHelp)
        self.profilesMenu.addAction(self.showHelpAction)


    def applyProfile(self, name):
        profile = profiles.get(name)
        applyProfile(profile)

    def initProfile(self):
        settings = QSettings()
        autoLoad = settings.value('profilesplugin/AutoLoad', False, bool)
        if autoLoad:
            profileName = settings.value('profilesplugin/LastProfile', '', unicode)
            if profileName in profiles:
                profile = profiles[profileName]
                if not profile.hasToInstallPlugins():
                    applyProfile(profile, False)

    def saveProfile(self):
        dlg = ProfileManager(iface.mainWindow())
        dlg.exec_()

    def showHelp(self):
        if not QDesktopServices.openUrl(
                QUrl('file://{}'.format(os.path.join(pluginPath, 'docs', 'html', 'index.html')))):
            QMessageBox.warning(None,
                                self.tr('Error'),
                                self.tr('Can not open help URL in browser'))

    def tr(self, text):
        return QCoreApplication.translate('Profiles', text)
    def load_menus(self, profile=None, schema=None):
        """
        Load menus in the main windows qgis bar
        """
        if not schema:
            schema = self.combo_schema.currentText()
        if not profile:
            profile = self.combo_profile.currentText()
        # remove previous menus
        for menu in self.uiparent.menus:
            self.uiparent.iface.mainWindow().menuBar().removeAction(menu.menuAction())

        with self.transaction():
            cur = self.connection.cursor()
            select = """
                select name, profile, model_index, datasource_uri
                from {}.{}
                where profile = '{}'
                """.format(schema, self.table, profile)
            cur.execute(select)
            rows = cur.fetchall()
        # item accessor ex: '0-menu/0-submenu/1-item/'
        menudict = {}
        # reference to parent item
        parent = ''
        # reference to qgis main menu bar
        menubar = self.uiparent.iface.mainWindow().menuBar()

        for name, profile, model_index, datasource_uri in self.sortby_modelindex(rows):
            uri_struct = QgsMimeDataUtils.Uri(datasource_uri)
            indexes = json.loads(model_index)
            # root menu
            parent = '{}-{}/'.format(indexes[0][0], indexes[0][1])
            if parent not in menudict:
                menu = QMenu(self.uiparent.iface.mainWindow())
                self.uiparent.menus.append(menu)
                menu.setObjectName(indexes[0][1])
                menu.setTitle(indexes[0][1])
                menubar.insertMenu(
                    self.uiparent.iface.firstRightStandardMenu().menuAction(),
                    menu)
                menudict[parent] = menu
            else:
                # menu already there
                menu = menudict[parent]

            for idx, subname in indexes[1:-1]:
                # intermediate submenus
                parent += '{}-{}/'.format(idx, subname)
                if parent not in menudict:
                    submenu = menu.addMenu(subname)
                    submenu.setObjectName(subname)
                    submenu.setTitle(subname)
                    menu = submenu
                    # store it for later use
                    menudict[parent] = menu
                    continue
                # already treated
                menu = menudict[parent]

            # last item = layer
            layer = QAction(name, self.uiparent.iface.mainWindow())

            if uri_struct.providerKey in ICON_MAPPER:
                layer.setIcon(QIcon(ICON_MAPPER[uri_struct.providerKey]))

            if uri_struct.providerKey == 'postgres':
                # set tooltip to postgres comment
                comment = self.get_table_comment(uri_struct.uri)
                layer.setStatusTip(comment)
                layer.setToolTip(comment)

            layer.setData(uri_struct.uri)
            layer.setWhatsThis(uri_struct.providerKey)
            layer.triggered.connect(self.layer_handler[uri_struct.layerType])
            menu.addAction(layer)
Example #15
0
class ProcessingPlugin:

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

    def initGui(self):
        Processing.initialize()

        self.commander = None
        self.toolbox = ProcessingToolbox()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        Processing.addAlgListListener(self.toolbox)

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName('processing')
        self.menu.setTitle(self.tr('Pro&cessing'))

        self.toolboxAction = self.toolbox.toggleViewAction()
        self.toolboxAction.setObjectName('toolboxAction')
        self.toolboxAction.setIcon(
            QIcon(os.path.join(cmd_folder, 'images', 'alg.png')))
        self.toolboxAction.setText(self.tr('&Toolbox'))
        self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T')
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'model.png')),
            self.tr('Graphical &Modeler...'), self.iface.mainWindow())
        self.modelerAction.setObjectName('modelerAction')
        self.modelerAction.triggered.connect(self.openModeler)
        self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M')
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'history.gif')),
            self.tr('&History...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H')
        self.menu.addAction(self.historyAction)

        self.configAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'config.png')),
            self.tr('&Options...'), self.iface.mainWindow())
        self.configAction.setObjectName('configAction')
        self.configAction.triggered.connect(self.openConfig)
        self.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C')
        self.menu.addAction(self.configAction)

        self.resultsAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'results.png')),
            self.tr('&Results Viewer...'), self.iface.mainWindow())
        self.resultsAction.setObjectName('resultsAction')
        self.resultsAction.triggered.connect(self.openResults)
        self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R')
        self.menu.addAction(self.resultsAction)

        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.menu)

        self.commanderAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'commander.png')),
            self.tr('&Commander'), self.iface.mainWindow())
        self.commanderAction.setObjectName('commanderAction')
        self.commanderAction.triggered.connect(self.openCommander)
        self.menu.addAction(self.commanderAction)
        self.iface.registerMainWindowAction(self.commanderAction,
                                            self.tr('Ctrl+Alt+M'))

    def unload(self):
        self.toolbox.setVisible(False)
        self.menu.deleteLater()

        # delete temporary output files
        folder = tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.commanderAction)

    def openCommander(self):
        if self.commander is None:
            self.commander = CommanderWindow(
                self.iface.mainWindow(),
                self.iface.mapCanvas())
            Processing.addAlgListListener(self.commander)
        self.commander.prepareGui()
        self.commander.show()

    def openToolbox(self):
        if self.toolbox.isVisible():
            self.toolbox.hide()
        else:
            self.toolbox.show()

    def openModeler(self):
        dlg = ModelerDialog()
        dlg.show()
        dlg.exec_()
        if dlg.update:
            self.toolbox.updateProvider('model')

    def openResults(self):
        dlg = ResultsDialog()
        dlg.show()
        dlg.exec_()

    def openHistory(self):
        dlg = HistoryDialog()
        dlg.exec_()

    def openConfig(self):
        dlg = ConfigDialog(self.toolbox)
        dlg.exec_()

    def tr(self, message):
        return QCoreApplication.translate('ProcessingPlugin', message)
Example #16
0
class GuiMain(object):
    def __init__(self, data):
        
        self.data = data
        self.loadSave = False
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        #Set size of window and make it non-resizeable
        MainWindow.resize(818, 665)
        MainWindow.setFixedHeight(665)
        MainWindow.setFixedWidth(818)
        
        MainWindow.setWindowTitle("Map Master: Search for the Lost City")
        MainWindow.setWindowIcon(QIcon("icon_medium.ico"))

        #Set window backgrounds
        self.background = QLabel(MainWindow)
        
        
        self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png"))
        self.backgroundPixmapSettings = QPixmap(normpath("images/gameMenuSettings2.png"))
        self.background.setPixmap(self.backgroundPixmapMenu)       
        
        self.background.setGeometry(QtCore.QRect(0, 0, 818, 665))
        
        #Stylesheet settings for labels and buttons
        self.fg = "QLabel {color:black}"
        self.fgb = "QPushButton {color:black}"

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        #Main Menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.startButton = QPushButton(self.menuPage)
        self.startButton.setStyleSheet(self.fgb)
        self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60))
        self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8))
        self.startButton.setObjectName("startButton")
        self.loadButton = QPushButton(self.menuPage)
        self.loadButton.setStyleSheet(self.fgb)
        self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60))
        self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8))
        self.loadButton.setObjectName("loadButton")
        self.settingsButton = QPushButton(self.menuPage)
        self.settingsButton.setStyleSheet(self.fgb)
        self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60))
        self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.settingsButton.setObjectName("settingsButton")
        self.quitButton = QPushButton(self.menuPage)
        self.quitButton.setStyleSheet(self.fgb)
        self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60))
        self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.quitButton.setObjectName("quitButton")
        self.instrButton = QPushButton(self.menuPage)
        self.instrButton.setStyleSheet(self.fgb)
        self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60))
        self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8))
        self.instrButton.setObjectName("instrButton")
        self.stackedWidget.addWidget(self.menuPage)
        
        #Settings page
        self.settingsPage = QWidget()
        self.settingsPage.setObjectName("settingsPage")
        self.volumeSlider = QSlider(self.settingsPage)
        self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30))
        self.volumeSlider.setProperty("value", 50)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.soundLabel = QLabel(self.settingsPage)
        self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.soundLabel.setFont(font)
        self.soundLabel.setStyleSheet(self.fg)
        self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8))
        self.soundLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.soundLabel.setObjectName("soundLabel")
        
        #Quiet Sound Graphic
        self.quietGraphic = QLabel(self.settingsPage)
        self.quietGraphic.setPixmap(QPixmap(normpath("images/speakerQuiet.png")))
        self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80))
        self.quietGraphic.setObjectName("quietGraphic")
        
        #Loud Sound Graphic
        self.loudGraphic = QLabel(self.settingsPage)
        self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png")))
        self.loudGraphic.setEnabled(True)
        self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80))
        self.loudGraphic.setObjectName("loudGraphic")
        
        self.settingsLabel = QLabel(self.settingsPage)
        self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.settingsLabel.setFont(font)
        self.settingsLabel.setStyleSheet(self.fg)
        self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.settingsLabel.setObjectName("settingsLabel")
        self.doneButton = QPushButton(self.settingsPage)
        self.doneButton.setStyleSheet(self.fgb)
        self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton.setObjectName("doneButton")
        self.stackedWidget.addWidget(self.settingsPage)
        
        self.soundManager = Sounds(self.volumeSlider.sliderPosition())
        
        #Main Game page
        self.mainPage = QWidget()
        self.mainPage.setObjectName("mainPage")
        
        #Person View
        self.personView = ViewGraphics(self.mainPage)
        self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500))
        self.personView.setObjectName("personView")
        
        #Map View
        self.mapView = ViewGraphics(self.mainPage)
        self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500))
        self.mapView.setObjectName("mapView")
        
        #ClueView
        self.clueView = QLabel(self.mainPage)
        self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91))
        self.clueView.setObjectName("clueView")
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.clueView.setFont(font)
        self.clueView.setStyleSheet(self.fg)
        
        #Map Toggles
        self.latLongCheck = QCheckBox(self.mainPage)
        self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 97, 41))
        self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n"
        "Longitude", None, QApplication.UnicodeUTF8))
        self.latLongCheck.setObjectName("latLongCheck")

        self.colorCheck = QCheckBox(self.mainPage)
        self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41))
        self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n"
        "Coding", None, QApplication.UnicodeUTF8))
        self.colorCheck.setObjectName("colorCheck")
        self.legendCheck = QCheckBox(self.mainPage)
        self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22))
        self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8))
        self.legendCheck.setObjectName("legendCheck")
        self.searchButton = QPushButton(self.mainPage)
        self.searchButton.setStyleSheet(self.fgb)
        self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 41))
        self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.searchButton.setObjectName("searchButton")
        
        #Score pieces
        self.scoreBox = QLabel(self.mainPage)
        self.scoreBox.setStyleSheet(self.fg)
        self.scoreBox.setGeometry(QtCore.QRect(720, 560, 71, 41))
        self.scoreBox.setObjectName("scoreBox")
        self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8))
        self.scoreLabel = QLabel(self.mainPage)
        self.scoreLabel.setStyleSheet(self.fg)
        self.scoreLabel.setGeometry(QtCore.QRect(660, 570, 51, 17))
        self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8))
        self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreLabel.setObjectName("scoreLabel")
        self.stackedWidget.addWidget(self.mainPage)
        
        #Help page
        self.helpPage = QWidget()
        self.helpPage.setObjectName("helpPage")
        self.HelpLabel = QLabel(self.helpPage)
        self.HelpLabel.setStyleSheet(self.fg)
        self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.HelpLabel.setFont(font)
        self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8))
        self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.HelpLabel.setObjectName("HelpLabel")
        self.wInstr = QLabel(self.helpPage)
        self.wInstr.setStyleSheet(self.fg)
        self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.wInstr.setFont(font)
        self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8))
        self.wInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr.setObjectName("wInstr")
        self.sInstr = QLabel(self.helpPage)
        self.sInstr.setStyleSheet(self.fg)
        self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.sInstr.setFont(font)
        self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8))
        self.sInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr.setObjectName("sInstr")
        self.aInstr = QLabel(self.helpPage)
        self.aInstr.setStyleSheet(self.fg)
        self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.aInstr.setFont(font)
        self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8))
        self.aInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr.setObjectName("aInstr")
        self.dInstr = QLabel(self.helpPage)
        self.dInstr.setStyleSheet(self.fg)
        self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr.setFont(font)
        self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8))
        self.dInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr.setObjectName("dInstr")
        self.wInstr2 = QLabel(self.helpPage)
        self.wInstr2.setStyleSheet(self.fg)
        self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.wInstr2.setFont(font)
        self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8))
        self.wInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr2.setObjectName("wInstr2")
        self.sInstr2 = QLabel(self.helpPage)
        self.sInstr2.setStyleSheet(self.fg)
        self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.sInstr2.setFont(font)
        self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8))
        self.sInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr2.setObjectName("sInstr2")
        self.aInstr2 = QLabel(self.helpPage)
        self.aInstr2.setStyleSheet(self.fg)
        self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.aInstr2.setFont(font)
        self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8))
        self.aInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr2.setObjectName("aInstr2")
        self.dInstr2 = QLabel(self.helpPage)
        self.dInstr2.setStyleSheet(self.fg)
        self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr2.setFont(font)
        self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8))
        self.dInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2.setObjectName("dInstr2")
        self.searchInstr = QPushButton(self.helpPage)
        self.searchInstr.setStyleSheet(self.fgb)
        self.searchInstr.setEnabled(True)
        self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30))
        self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.searchInstr.setAutoDefault(False)
        self.searchInstr.setDefault(False)
        self.searchInstr.setFlat(False)
        self.searchInstr.setObjectName("searchInstr")
        self.dInstr2_2 = QLabel(self.helpPage)
        self.dInstr2_2.setStyleSheet(self.fg)
        self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr2_2.setFont(font)
        self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8))
        self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2_2.setObjectName("dInstr2_2")
        self.doneButton2 = QPushButton(self.helpPage)
        self.doneButton2.setStyleSheet(self.fgb)
        self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton2.setObjectName("doneButton2")
        self.stackedWidget.addWidget(self.helpPage)
        
        #Credits page
        self.creditsPage = QWidget()
        self.creditsPage.setObjectName("creditsPage")
        self.creditsLabel = QLabel(self.creditsPage)
        self.creditsLabel.setStyleSheet(self.fg)
        self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.creditsLabel.setFont(font)
        self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8))
        self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.creditsLabel.setObjectName("creditsLabel")
        self.credits = QLabel(self.creditsPage)
        self.credits.setStyleSheet(self.fg)
        self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.credits.setFont(font)
        self.credits.setText(QApplication.translate("MainWindow", 
        "Gary Lent\n"
        "Grant Stafford\n"
        "Jessie Liu\n"
        "Peter Andrien\n"
        "Nokia (Qt4 framework)\n"
        "Riverbank Computing Ltd (PyQt)\n"
        "Celestial Aeon Project", None, QApplication.UnicodeUTF8))
        self.credits.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.credits.setObjectName("credits")
        self.doneButton3 = QPushButton(self.creditsPage)
        self.doneButton3.setStyleSheet(self.fgb)
        self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton3.setObjectName("doneButton3")
        self.stackedWidget.addWidget(self.creditsPage)
        
        #Story page
        self.storyPage = QWidget()
        self.storyPage.setObjectName("storyPage")
        self.storyLabel = QLabel(self.storyPage)
        self.storyLabel.setStyleSheet(self.fg)
        self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(25)
        self.storyLabel.setFont(font)
        self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently lost my job, but stumbled\n on a clue that may change my life \nforever. I've set off on a quest - a quest\n to find a lost city. I've found a clue,\n and believe there may be more.\n Help me find the lost city.  ", None, QApplication.UnicodeUTF8))
        self.storyLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.storyLabel.setObjectName("storyLabel")
        self.nextButton = QPushButton(self.storyPage)
        self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8))
        self.nextButton.setObjectName("nextButton")
        self.stackedWidget.addWidget(self.storyPage)
        
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #Menu bar
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QMenu(self.menubar)
        self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8))
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.actionSave_Game = QAction(MainWindow)
        self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8))
        self.actionSave_Game.setObjectName("actionSave_Game")
        self.actionCredits = QAction(MainWindow)
        self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8))
        self.actionCredits.setObjectName("actionCredits")
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.actionQuit.setObjectName("actionQuit")
        self.actionSettings = QAction(MainWindow)
        self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setObjectName("actionSettings")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8))
        self.actionHelp.setObjectName("actionHelp")
        self.actionMain_Menu = QAction(MainWindow)
        self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8))
        self.actionMain_Menu.setObjectName("actionMain_Menu")
        self.menuMenu.addAction(self.actionSettings)
        self.menuMenu.addAction(self.actionHelp)
        self.menuMenu.addAction(self.actionSave_Game)
        self.menuMenu.addAction(self.actionCredits)
        self.menuMenu.addAction(self.actionMain_Menu)
        self.menuMenu.addAction(self.actionQuit)
        self.menubar.addAction(self.menuMenu.menuAction())
        

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        #These are the slots and signals to connect buttons to other functions
        self.location = 0
        QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL("triggered()"), MainWindow.close)
        QtCore.QObject.connect(self.quitButton, QtCore.SIGNAL("released()"), MainWindow.close)
        QtCore.QObject.connect(self.settingsButton, QtCore.SIGNAL("released()"), self.setSettings)
        QtCore.QObject.connect(self.actionSettings, QtCore.SIGNAL("triggered()"), self.setSettings)
        QtCore.QObject.connect(self.loadButton, QtCore.SIGNAL("released()"), self.load_file_dialog)
        QtCore.QObject.connect(self.actionSave_Game, QtCore.SIGNAL("triggered()"),self.save_file_dialog)
        QtCore.QObject.connect(self.doneButton, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.startButton, QtCore.SIGNAL("released()"), self.newGame)
        QtCore.QObject.connect(self.actionMain_Menu, QtCore.SIGNAL("triggered()"), self.setMain)
        QtCore.QObject.connect(self.actionHelp, QtCore.SIGNAL("triggered()"), self.setInstructions)
        QtCore.QObject.connect(self.instrButton, QtCore.SIGNAL("released()"), self.setInstructions)
        QtCore.QObject.connect(self.doneButton2, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.doneButton3, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.actionCredits, QtCore.SIGNAL("triggered()"), self.setCredits)
        self.latLongCheck.stateChanged.connect(self.latLong)
        self.colorCheck.stateChanged.connect(self.colorize)
        self.legendCheck.stateChanged.connect(self.legend)
        QtCore.QObject.connect(self.searchButton, QtCore.SIGNAL("released()"), self.doSearch)
        QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL("released()"), self.storyButton)
        self.volumeSlider.sliderMoved.connect(self.setVol)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass

    #Custom signals are here        
    def setSettings(self):
        self.background.setPixmap(self.backgroundPixmapSettings)    
        self.stackedWidget.setCurrentIndex(1)
        
    def setInstructions(self):
        self.background.setPixmap(self.backgroundPixmapSettings)    
        self.stackedWidget.setCurrentIndex(3)
        
    def setCredits(self):
        self.background.setPixmap(self.backgroundPixmapSettings)       
        self.stackedWidget.setCurrentIndex(4)
        
    def goBack(self):
        self.stackedWidget.setCurrentIndex(self.location)
        if self.location == 0:
            self.background.setPixmap(self.backgroundPixmapMenu)
        else:
            None
            #Should be something here later.
        
    def load_file_dialog(self):
        fd = QFileDialog()
        self.filename = fd.getOpenFileName(None, "Load Saved Game", "saves", "MapMaster Save files (*.save)")
        if isfile(self.filename):
            self.loadSaved = True
            self.stackedWidget.setCurrentIndex(2)
            self.location = 2
            self.soundManager.switchSongs(self.location)
            
            
    def save_file_dialog(self):
        filename = QtGui.QFileDialog.getSaveFileName(None,"Save Game", "saves", "MapMaster Save files (*.save)")
        if filename == "":
            print "No file specified!"
        else:
           
            if ".save" in filename:
                self.fname = open(filename, "w")
            else:
                self.fname = open(filename + ".save",'w')
                
            score = str(self.data.score)
            numClues = str(len(self.data.clueStack))
            charX, charY = self.data.character.getCenter()
            whiteSpace = "       "
            toWriteList = whiteSpace + str(charX) + whiteSpace + str(charY) + whiteSpace + numClues + whiteSpace + score
            self.fname.write(toWriteList)     
            self.fname.close()
            
    
        
       
    def newGame(self):
        self.background.setPixmap(self.backgroundPixmapSettings)
        self.filename = None    
        self.stackedWidget.setCurrentIndex(5)
        self.location = 5
        
    def storyButton(self):
    
        self.stackedWidget.setCurrentIndex(2)
        self.location = 2
        self.soundManager.switchSongs(self.location)
       
    def setMain(self):
        self.save_file_dialog()
        self.background.setPixmap(self.backgroundPixmapMenu)
        self.stackedWidget.setCurrentIndex(0)
        self.location = 0
        self.soundManager.switchSongs(self.location)      
           
        
    def latLong(self):
        if self.latLongCheck.isChecked():
            print "Lat/long overlay on"
        else:
            print "Lat/long overlay off"
        self.data.overlays['latLongOverlay'].mViewObj.setVisible(self.latLongCheck.isChecked())
        
    def colorize(self):
        if self.colorCheck.isChecked():
            print "Color overlay on"
        else:
            print "Color overlay off"
        self.data.overlays['colorOverlay'].mViewObj.setVisible(self.colorCheck.isChecked())
        
    def legend(self):
        if self.legendCheck.isChecked():
            print "Legend overlay on"
        else:
            print "Legend overlay off"
        self.data.overlays['legendOverlay'].mViewObj.setVisible(self.legendCheck.isChecked())
    
    def setVol(self):
        self.soundManager.setVolume(self.volumeSlider.sliderPosition())
    
    def doSearch(self):
        searchLandmark(self.data)
Example #17
0
class fToolsPlugin:

    def __init__(self, iface):
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

    def getThemeIcon(self, icon):
        settings = QSettings()
        pluginPath = os.path.dirname(__file__)
        themePath = "icons" + QDir.separator() + settings.value("/Themes", "default") + QDir.separator() + icon
        defaultPath = "icons" + QDir.separator() + "default" + QDir.separator() + icon
        if QFile.exists(pluginPath + QDir.separator() + themePath):
            return QIcon(":" + themePath)
        elif QFile.exists(pluginPath + QDir.separator() + defaultPath):
            return QIcon(":" + defaultPath)
        else:
            return QIcon()

    def updateThemeIcons(self, theme):
        self.analysisMenu.setIcon(QIcon(self.getThemeIcon("analysis.png")))
        self.distMatrix.setIcon(QIcon(self.getThemeIcon("matrix.png")))
        self.sumLines.setIcon(QIcon(self.getThemeIcon("sum_lines.png")))
        self.pointsPoly.setIcon(QIcon(self.getThemeIcon("sum_points.png")))
        self.compStats.setIcon(QIcon(self.getThemeIcon("basic_statistics.png")))
        self.listUnique.setIcon(QIcon(self.getThemeIcon("unique.png")))
        self.nearestNeigh.setIcon(QIcon(self.getThemeIcon("neighbour.png")))
        self.meanCoords.setIcon(QIcon(self.getThemeIcon("mean.png")))
        self.intLines.setIcon(QIcon(self.getThemeIcon("intersections.png")))

        self.researchMenu.setIcon(QIcon(self.getThemeIcon("sampling.png")))
        self.randSel.setIcon(QIcon(self.getThemeIcon("random_selection.png")))
        self.randSub.setIcon(QIcon(self.getThemeIcon("sub_selection.png")))
        self.randPoints.setIcon(QIcon(self.getThemeIcon("random_points.png")))
        self.regPoints.setIcon(QIcon(self.getThemeIcon("regular_points.png")))
        self.vectGrid.setIcon(QIcon(self.getThemeIcon("vector_grid.png")))
        self.selectLocation.setIcon(QIcon(self.getThemeIcon("select_location.png")))
        self.layerExtent.setIcon(QIcon(self.getThemeIcon("layer_extent.png")))

        self.geoMenu.setIcon(QIcon(self.getThemeIcon("geoprocessing.png")))
        self.minConvex.setIcon(QIcon(self.getThemeIcon("convex_hull.png")))
        self.dynaBuffer.setIcon(QIcon(self.getThemeIcon("buffer.png")))
        self.intersect.setIcon(QIcon(self.getThemeIcon("intersect.png")))
        self.union.setIcon(QIcon(self.getThemeIcon("union.png")))
        self.symDifference.setIcon(QIcon(self.getThemeIcon("sym_difference.png")))
        self.clip.setIcon(QIcon(self.getThemeIcon("clip.png")))
        self.dissolve.setIcon(QIcon(self.getThemeIcon("dissolve.png")))
        self.erase.setIcon(QIcon(self.getThemeIcon("difference.png")))
        self.eliminate.setIcon(QIcon(self.getThemeIcon("eliminate.png")))

        self.conversionMenu.setIcon(QIcon(self.getThemeIcon("geometry.png")))
        self.compGeo.setIcon(QIcon(self.getThemeIcon("export_geometry.png")))
        self.checkGeom.setIcon(QIcon(self.getThemeIcon("check_geometry.png")))
        self.centroids.setIcon(QIcon(self.getThemeIcon("centroids.png")))
        self.delaunay.setIcon(QIcon(self.getThemeIcon("delaunay.png")))
        self.voronoi.setIcon(QIcon(self.getThemeIcon("voronoi.png")))
        self.extNodes.setIcon(QIcon(self.getThemeIcon("extract_nodes.png")))
        self.simplify.setIcon(QIcon(self.getThemeIcon("simplify.png")))
        self.densify.setIcon(QIcon(self.getThemeIcon("densify.png")))
        self.multiToSingle.setIcon(QIcon(self.getThemeIcon("multi_to_single.png")))
        self.singleToMulti.setIcon(QIcon(self.getThemeIcon("single_to_multi.png")))
        self.polysToLines.setIcon(QIcon(self.getThemeIcon("to_lines.png")))
        self.linesToPolys.setIcon(QIcon(self.getThemeIcon("to_lines.png")))

        self.dataManageMenu.setIcon(QIcon(self.getThemeIcon("management.png")))
        self.define.setIcon(QIcon(self.getThemeIcon("define_projection.png")))
        self.spatJoin.setIcon(QIcon(self.getThemeIcon("join_location.png")))
        self.splitVect.setIcon(QIcon(self.getThemeIcon("split_layer.png")))
        self.mergeShapes.setIcon(QIcon(self.getThemeIcon("merge_shapes.png")))
        self.spatialIndex.setIcon(QIcon(self.getThemeIcon("spatial_index.png")))

    def initGui(self):
        if int(self.QgisVersion) < 1:
            QMessageBox.warning(
                self.iface.getMainWindow(), "fTools",
                QCoreApplication.translate("fTools", "QGIS version detected: ") + unicode(self.QgisVersion) + ".xx\n"
                + QCoreApplication.translate("fTools", "This version of fTools requires at least QGIS version 1.0.0\nPlugin will not be enabled."))
            return None
        QObject.connect(self.iface, SIGNAL("currentThemeChanged (QString)"), self.updateThemeIcons)

        self.analysisMenu = QMenu(QCoreApplication.translate("fTools", "&Analysis Tools"))
        self.analysisMenu.setObjectName("analysisMenu")
        self.distMatrix = QAction(QCoreApplication.translate("fTools", "Distance Matrix..."), self.iface.mainWindow())
        self.distMatrix.setObjectName("distMatrix")
        self.sumLines = QAction(QCoreApplication.translate("fTools", "Sum Line Lengths..."), self.iface.mainWindow())
        self.sumLines.setObjectName("sumLines")
        self.pointsPoly = QAction(QCoreApplication.translate("fTools", "Points in Polygon..."), self.iface.mainWindow())
        self.pointsPoly.setObjectName("pointsPoly")
        self.compStats = QAction(QCoreApplication.translate("fTools", "Basic Statistics..."), self.iface.mainWindow())
        self.compStats.setObjectName("compStats")
        self.listUnique = QAction(QCoreApplication.translate("fTools", "List Unique Values..."), self.iface.mainWindow())
        self.listUnique.setObjectName("listUnique")
        self.nearestNeigh = QAction(QCoreApplication.translate("fTools", "Nearest Neighbour Analysis..."), self.iface.mainWindow())
        self.nearestNeigh.setObjectName("nearestNeigh")
        self.meanCoords = QAction(QCoreApplication.translate("fTools", "Mean Coordinate(s)..."), self.iface.mainWindow())
        self.meanCoords.setObjectName("meanCoords")
        self.intLines = QAction(QCoreApplication.translate("fTools", "Line Intersections..."), self.iface.mainWindow())
        self.intLines.setObjectName("intLines")
        self.analysisMenu.addActions([
            self.distMatrix, self.sumLines, self.pointsPoly,
            self.listUnique, self.compStats, self.nearestNeigh, self.meanCoords, self.intLines])

        self.researchMenu = QMenu(QCoreApplication.translate("fTools", "&Research Tools"))
        self.researchMenu.setObjectName("researchMenu")
        self.randSel = QAction(QCoreApplication.translate("fTools", "Random Selection..."), self.iface.mainWindow())
        self.randSel.setObjectName("randSel")
        self.randSub = QAction(QCoreApplication.translate("fTools", "Random Selection Within Subsets..."), self.iface.mainWindow())
        self.randSub.setObjectName("randSub")
        self.randPoints = QAction(QCoreApplication.translate("fTools", "Random Points..."), self.iface.mainWindow())
        self.randPoints.setObjectName("randPoints")
        self.regPoints = QAction(QCoreApplication.translate("fTools", "Regular Points..."), self.iface.mainWindow())
        self.regPoints.setObjectName("regPoints")
        self.vectGrid = QAction(QCoreApplication.translate("fTools", "Vector Grid..."), self.iface.mainWindow())
        self.vectGrid.setObjectName("vectGrid")
        self.selectLocation = QAction(QCoreApplication.translate("fTools", "Select by Location..."), self.iface.mainWindow())
        self.selectLocation.setObjectName("selectLocation")
        self.layerExtent = QAction(QCoreApplication.translate("fTools", "Polygon from Layer Extent..."), self.iface.mainWindow())
        self.layerExtent.setObjectName("layerExtent")
        self.researchMenu.addActions([
            self.randSel, self.randSub, self.randPoints,
            self.regPoints, self.vectGrid, self.selectLocation, self.layerExtent])

        self.geoMenu = QMenu(QCoreApplication.translate("fTools", "&Geoprocessing Tools"))
        self.geoMenu.setObjectName("geoMenu")
        self.minConvex = QAction(QCoreApplication.translate("fTools", "Convex Hull(s)..."), self.iface.mainWindow())
        self.minConvex.setObjectName("minConvex")
        self.dynaBuffer = QAction(QCoreApplication.translate("fTools", "Buffer(s)..."), self.iface.mainWindow())
        self.dynaBuffer.setObjectName("dynaBuffer")
        self.intersect = QAction(QCoreApplication.translate("fTools", "Intersect..."), self.iface.mainWindow())
        self.intersect.setObjectName("intersect")
        self.union = QAction(QCoreApplication.translate("fTools", "Union..."), self.iface.mainWindow())
        self.union.setObjectName("union")
        self.symDifference = QAction(QCoreApplication.translate("fTools", "Symmetrical Difference..."), self.iface.mainWindow())
        self.symDifference.setObjectName("symDifference")
        self.clip = QAction(QCoreApplication.translate("fTools", "Clip..."), self.iface.mainWindow())
        self.clip.setObjectName("clip")
        self.dissolve = QAction(QCoreApplication.translate("fTools", "Dissolve..."), self.iface.mainWindow())
        self.dissolve.setObjectName("dissolve")
        self.erase = QAction(QCoreApplication.translate("fTools", "Difference..."), self.iface.mainWindow())
        self.erase.setObjectName("erase")
        self.eliminate = QAction(QCoreApplication.translate("fTools", "Eliminate Sliver Polygons..."), self.iface.mainWindow())
        self.eliminate.setObjectName("eliminate")
        self.geoMenu.addActions([
            self.minConvex, self.dynaBuffer, self.intersect,
            self.union, self.symDifference, self.clip, self.erase, self.dissolve,
            self.eliminate])

        self.conversionMenu = QMenu(QCoreApplication.translate("fTools", "G&eometry Tools"))
        self.conversionMenu.setObjectName("conversionMenu")
        self.compGeo = QAction(QCoreApplication.translate("fTools", "Export/Add Geometry Columns..."), self.iface.mainWindow())
        self.compGeo.setObjectName("compGeo")
        self.checkGeom = QAction(QCoreApplication.translate("fTools", "Check Geometry Validity..."), self.iface.mainWindow())
        self.checkGeom.setObjectName("checkGeom")
        self.centroids = QAction(QCoreApplication.translate("fTools", "Polygon Centroids..."), self.iface.mainWindow())
        self.centroids.setObjectName("centroids")
        self.delaunay = QAction(QCoreApplication.translate("fTools", "Delaunay Triangulation..."), self.iface.mainWindow())
        self.delaunay.setObjectName("delaunay")
        self.voronoi = QAction(QCoreApplication.translate("fTools", "Voronoi Polygons..."), self.iface.mainWindow())
        self.voronoi.setObjectName("voronoi")
        self.extNodes = QAction(QCoreApplication.translate("fTools", "Extract Nodes..."), self.iface.mainWindow())
        self.extNodes.setObjectName("extNodes")
        self.simplify = QAction(QCoreApplication.translate("fTools", "Simplify Geometries..."), self.iface.mainWindow())
        self.simplify.setObjectName("simplify")
        self.densify = QAction(QCoreApplication.translate("fTools", "Densify Geometries..."), self.iface.mainWindow())
        self.densify.setObjectName("densify")
        self.multiToSingle = QAction(QCoreApplication.translate("fTools", "Multipart to Singleparts..."), self.iface.mainWindow())
        self.multiToSingle.setObjectName("multiToSingle")
        self.singleToMulti = QAction(QCoreApplication.translate("fTools", "Singleparts to Multipart..."), self.iface.mainWindow())
        self.singleToMulti.setObjectName("singleToMulti")
        self.polysToLines = QAction(QCoreApplication.translate("fTools", "Polygons to Lines..."), self.iface.mainWindow())
        self.polysToLines.setObjectName("polysToLines")
        self.linesToPolys = QAction(QCoreApplication.translate("fTools", "Lines to Polygons..."), self.iface.mainWindow())
        self.linesToPolys.setObjectName("linesToPolys")
        self.conversionMenu.addActions([
            self.checkGeom, self.compGeo, self.centroids, self.delaunay, self.voronoi,
            self.simplify, self.densify, self.multiToSingle, self.singleToMulti, self.polysToLines, self.linesToPolys,
            self.extNodes])

        self.dataManageMenu = QMenu(QCoreApplication.translate("fTools", "&Data Management Tools"))
        self.dataManageMenu.setObjectName("dataManageMenu")
        self.define = QAction(QCoreApplication.translate("fTools", "Define Current Projection..."), self.iface.mainWindow())
        self.define.setObjectName("define")
        self.spatJoin = QAction(QCoreApplication.translate("fTools", "Join Attributes by Location..."), self.iface.mainWindow())
        self.spatJoin.setObjectName("spatJoin")
        self.splitVect = QAction(QCoreApplication.translate("fTools", "Split Vector Layer..."), self.iface.mainWindow())
        self.splitVect.setObjectName("splitVect")
        self.mergeShapes = QAction(QCoreApplication.translate("fTools", "Merge Shapefiles to One..."), self.iface.mainWindow())
        self.mergeShapes.setObjectName("mergeShapes")
        self.spatialIndex = QAction(QCoreApplication.translate("fTools", "Create Spatial Index..."), self.iface.mainWindow())
        self.spatialIndex.setObjectName("spatialIndex")
        self.dataManageMenu.addActions([self.define, self.spatJoin, self.splitVect, self.mergeShapes, self.spatialIndex])

        self.updateThemeIcons("theme")

        self.menu = self.iface.vectorMenu()
        self.menu.addMenu(self.analysisMenu)
        self.menu.addMenu(self.researchMenu)
        self.menu.addMenu(self.geoMenu)
        self.menu.addMenu(self.conversionMenu)
        self.menu.addMenu(self.dataManageMenu)

        QObject.connect(self.distMatrix, SIGNAL("triggered()"), self.dodistMatrix)
        QObject.connect(self.sumLines, SIGNAL("triggered()"), self.dosumLines)
        QObject.connect(self.pointsPoly, SIGNAL("triggered()"), self.dopointsPoly)
        QObject.connect(self.compStats, SIGNAL("triggered()"), self.docompStats)
        QObject.connect(self.listUnique, SIGNAL("triggered()"), self.dolistUnique)
        QObject.connect(self.nearestNeigh, SIGNAL("triggered()"), self.donearestNeigh)
        QObject.connect(self.meanCoords, SIGNAL("triggered()"), self.domeanCoords)
        QObject.connect(self.intLines, SIGNAL("triggered()"), self.dointLines)

        QObject.connect(self.randSel, SIGNAL("triggered()"), self.dorandSel)
        QObject.connect(self.randSub, SIGNAL("triggered()"), self.dorandSub)
        QObject.connect(self.randPoints, SIGNAL("triggered()"), self.dorandPoints)
        QObject.connect(self.regPoints, SIGNAL("triggered()"), self.doregPoints)
        QObject.connect(self.vectGrid, SIGNAL("triggered()"), self.dovectGrid)
        QObject.connect(self.selectLocation, SIGNAL("triggered()"), self.doselectLocation)
        QObject.connect(self.layerExtent, SIGNAL("triggered()"), self.doextent)

        QObject.connect(self.minConvex, SIGNAL("triggered()"), self.dominConvex)
        QObject.connect(self.intersect, SIGNAL("triggered()"), self.dointersect)
        QObject.connect(self.dissolve, SIGNAL("triggered()"), self.dodissolve)
        QObject.connect(self.symDifference, SIGNAL("triggered()"), self.dosymdifference)
        QObject.connect(self.erase, SIGNAL("triggered()"), self.doerase)
        QObject.connect(self.union, SIGNAL("triggered()"), self.dounion)
        QObject.connect(self.clip, SIGNAL("triggered()"), self.doclip)
        QObject.connect(self.dynaBuffer, SIGNAL("triggered()"), self.dodynaBuffer)
        QObject.connect(self.eliminate, SIGNAL("triggered()"), self.doEliminate)

        QObject.connect(self.multiToSingle, SIGNAL("triggered()"), self.domultiToSingle)
        QObject.connect(self.singleToMulti, SIGNAL("triggered()"), self.dosingleToMulti)
        QObject.connect(self.checkGeom, SIGNAL("triggered()"), self.docheckGeom)
        QObject.connect(self.simplify, SIGNAL("triggered()"), self.doSimplify)
        QObject.connect(self.densify, SIGNAL("triggered()"), self.doDensify)
        QObject.connect(self.centroids, SIGNAL("triggered()"), self.docentroids)
        QObject.connect(self.delaunay, SIGNAL("triggered()"), self.dodelaunay)
        QObject.connect(self.voronoi, SIGNAL("triggered()"), self.dovoronoi)
        QObject.connect(self.polysToLines, SIGNAL("triggered()"), self.dopolysToLines)
        QObject.connect(self.linesToPolys, SIGNAL("triggered()"), self.dolinesToPolys)
        QObject.connect(self.compGeo, SIGNAL("triggered()"), self.docompGeo)
        QObject.connect(self.extNodes, SIGNAL("triggered()"), self.doextNodes)

        QObject.connect(self.define, SIGNAL("triggered()"), self.dodefine)
        QObject.connect(self.spatJoin, SIGNAL("triggered()"), self.dospatJoin)
        QObject.connect(self.splitVect, SIGNAL("triggered()"), self.dosplitVect)
        QObject.connect(self.mergeShapes, SIGNAL("triggered()"), self.doMergeShapes)
        QObject.connect(self.spatialIndex, SIGNAL("triggered()"), self.doSpatIndex)

    def unload(self):
        self.menu.removeAction(self.analysisMenu.menuAction())
        self.menu.removeAction(self.researchMenu.menuAction())
        self.menu.removeAction(self.geoMenu.menuAction())
        self.menu.removeAction(self.conversionMenu.menuAction())
        self.menu.removeAction(self.dataManageMenu.menuAction())

    def doSimplify(self):
        d = doSimplify.Dialog(self.iface, 1)
        d.show()
        d.exec_()

    def doDensify(self):
        d = doSimplify.Dialog(self.iface, 2)
        d.show()
        d.exec_()

    def dopolysToLines(self):
        d = doGeometry.GeometryDialog(self.iface, 4)
        d.exec_()

    def dolinesToPolys(self):
        d = doGeometry.GeometryDialog(self.iface, 11)
        d.exec_()

    def docheckGeom(self):
        d = doValidate.ValidateDialog(self.iface)
        d.show()
        d.exec_()

    def domultiToSingle(self):
        d = doGeometry.GeometryDialog(self.iface, 2)
        d.exec_()

    def dosingleToMulti(self):
        d = doGeometry.GeometryDialog(self.iface, 1)
        d.exec_()

    def doselectLocation(self):
        d = doSelectByLocation.Dialog(self.iface)
        d.exec_()

    def domeanCoords(self):
        d = doMeanCoords.Dialog(self.iface, 1)
        d.exec_()

    def dominConvex(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 2)
        d.exec_()

    def dodynaBuffer(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 1)
        d.exec_()

    def dointersect(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 5)
        d.exec_()

    def dodissolve(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 4)
        d.exec_()

    def doerase(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 3)
        d.exec_()

    def dosymdifference(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 7)
        d.exec_()

    def dounion(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 6)
        d.exec_()

    def doclip(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 8)
        d.exec_()

    def donearestNeigh(self):
        d = doVisual.VisualDialog(self.iface, 4)
        d.exec_()

    def dodistMatrix(self):
        d = doPointDistance.Dialog(self.iface)
        d.exec_()

    def docentroids(self):
        d = doGeometry.GeometryDialog(self.iface, 7)
        d.exec_()

    def dodelaunay(self):
        d = doGeometry.GeometryDialog(self.iface, 8)
        d.exec_()

    def dovoronoi(self):
        d = doGeometry.GeometryDialog(self.iface, 10)
        d.exec_()

    def doextent(self):
        d = doGeometry.GeometryDialog(self.iface, 9)
        d.exec_()

    def dosumLines(self):
        d = doSumLines.Dialog(self.iface)
        d.exec_()

    def dopointsPoly(self):
        d = doPointsInPolygon.Dialog(self.iface)
        d.show()
        d.exec_()

    def dorandSel(self):
        d = doRandom.Dialog(self.iface)
        d.exec_()

    def dorandSub(self):
        d = doSubsetSelect.Dialog(self.iface)
        d.exec_()

    def dorandPoints(self):
        d = doRandPoints.Dialog(self.iface)
        d.exec_()

    def doregPoints(self):
        d = doRegPoints.Dialog(self.iface)
        d.exec_()

    def dovectGrid(self):
        d = doVectorGrid.Dialog(self.iface)
        d.exec_()

    def doextNodes(self):
        d = doGeometry.GeometryDialog(self.iface, 3)
        d.exec_()

    def dointLines(self):
        d = doIntersectLines.Dialog(self.iface)
        d.exec_()

    def dosplitVect(self):
        d = doVectorSplit.Dialog(self.iface)
        d.show()
        d.exec_()

    def docompGeo(self):
        d = doGeometry.GeometryDialog(self.iface, 5)
        d.exec_()

    def dolistUnique(self):
        d = doVisual.VisualDialog(self.iface, 2)
        d.exec_()

    def docompStats(self):
        d = doVisual.VisualDialog(self.iface, 3)
        d.exec_()

    def dodefine(self):
        d = doDefineProj.Dialog(self.iface)
        d.exec_()

    def dospatJoin(self):
        d = doSpatialJoin.Dialog(self.iface)
        d.exec_()

    def doMergeShapes(self):
        d = doMergeShapes.Dialog(self.iface)
        d.show()
        d.exec_()

    def doSpatIndex(self):
        d = doSpatialIndex.Dialog(self.iface)
        d.show()
        d.exec_()

    def doEliminate(self):
        d = doEliminate.Dialog(self.iface)
        d.exec_()
Example #18
0
class Gui(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        #Set size of window and make it non-resizeable
        MainWindow.resize(818, 665)
        MainWindow.setFixedHeight(665)
        MainWindow.setFixedWidth(818)
        
        MainWindow.setWindowTitle("Map Master: Search for the Lost City")
        MainWindow.setWindowIcon(QIcon("icon_medium.ico"))

        #Set window backgrounds
        self.background = QLabel(MainWindow)
        
        
        self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png"))
        self.backgroundPixmapSettings = QPixmap(normpath(
                                            "images/gameMenuSettings2.png"))
        self.background.setPixmap(self.backgroundPixmapMenu)       
        
        self.background.setGeometry(QtCore.QRect(0, 0, 818, 665))
        
        self.popupPixmap = QPixmap(normpath("images/popupBG.png"))
        
        font = QFont()
        if "linux" in platform:
            font.setFamily("Century Schoolbook L")
        else:
            font.setFamily("Century Schoolbook")
        
        
        #Stylesheet settings for labels and buttons
        self.fg = "QLabel {color:black}"
        self.fgb = "QPushButton {color:black}"

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        #Main Menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        
        self.startButton = QPushButton(self.menuPage)
        self.startButton.setStyleSheet(self.fgb)
        self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60))
        self.startButton.setText(QApplication.translate("MainWindow", 
                                 "Start Game", None, QApplication.UnicodeUTF8))
        self.startButton.setObjectName("startButton")
        font.setPointSize(15)
        
        self.startButton.setFont(font)
        self.loadButton = QPushButton(self.menuPage)
        self.loadButton.setStyleSheet(self.fgb)
        self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60))
        self.loadButton.setText(QApplication.translate("MainWindow", 
                                "Load Game", None, QApplication.UnicodeUTF8))
        self.loadButton.setObjectName("loadButton")
        self.loadButton.setFont(font)
        
        self.settingsButton = QPushButton(self.menuPage)
        self.settingsButton.setStyleSheet(self.fgb)
        self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60))
        self.settingsButton.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.settingsButton.setObjectName("settingsButton")
        self.settingsButton.setFont(font)
        
        self.quitButton = QPushButton(self.menuPage)
        self.quitButton.setStyleSheet(self.fgb)
        self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60))
        self.quitButton.setText(QApplication.translate("MainWindow", 
                                "Quit", None, QApplication.UnicodeUTF8))
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setFont(font)
        
        self.instrButton = QPushButton(self.menuPage)
        self.instrButton.setStyleSheet(self.fgb)
        self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60))
        self.instrButton.setText(QApplication.translate("MainWindow", 
                               "Instructions", None, QApplication.UnicodeUTF8))
        self.instrButton.setObjectName("instrButton")
        self.instrButton.setFont(font)
        self.stackedWidget.addWidget(self.menuPage)
        
        #Settings page
        self.settingsPage = QWidget()
        self.settingsPage.setObjectName("settingsPage")
        self.volumeSlider = QSlider(self.settingsPage)
        self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30))
        self.volumeSlider.setProperty("value", 50)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.soundLabel = QLabel(self.settingsPage)
        self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30))
        font.setPointSize(20)
        self.soundLabel.setFont(font)
        self.soundLabel.setStyleSheet(self.fg)
        self.soundLabel.setText(QApplication.translate("MainWindow", 
                                "Volume", None, QApplication.UnicodeUTF8))
        self.soundLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.soundLabel.setObjectName("soundLabel")
        
        #Quiet Sound Graphic
        self.quietGraphic = QLabel(self.settingsPage)
        self.quietGraphic.setPixmap(QPixmap(normpath(
                                    "images/speakerQuiet.png")))
        self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80))
        self.quietGraphic.setObjectName("quietGraphic")
        
        #Loud Sound Graphic
        self.loudGraphic = QLabel(self.settingsPage)
        self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png")))
        self.loudGraphic.setEnabled(True)
        self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80))
        self.loudGraphic.setObjectName("loudGraphic")
        
        self.settingsLabel = QLabel(self.settingsPage)
        self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.settingsLabel.setFont(font)
        self.settingsLabel.setStyleSheet(self.fg)
        self.settingsLabel.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.settingsLabel.setObjectName("settingsLabel")
        self.doneButton = QPushButton(self.settingsPage)
        self.doneButton.setStyleSheet(self.fgb)
        self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton.setText(QApplication.translate("MainWindow", 
                                "Done", None, QApplication.UnicodeUTF8))
        self.doneButton.setObjectName("doneButton")
        font.setPointSize(15)
        self.doneButton.setFont(font)
        self.stackedWidget.addWidget(self.settingsPage)
        
        self.soundManager = Sounds(self.volumeSlider.sliderPosition())
        
        #Main Game page
        self.mainPage = QWidget()
        self.mainPage.setObjectName("mainPage")
        
        #Person View
        self.personView = ViewGraphics(self.mainPage)
        self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500))
        self.personView.setObjectName("personView")
        
        #Map View
        self.mapView = ViewGraphics(self.mainPage)
        self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500))
        self.mapView.setObjectName("mapView")
        
        #ClueView
        self.clueView = QLabel(self.mainPage)
        self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91))
        self.clueView.setObjectName("clueView")
        font.setPointSize(20)
        self.clueView.setFont(font)
        self.clueView.setStyleSheet(self.fg)
        
        #Map Toggles
        self.latLongCheck = QCheckBox(self.mainPage)
        self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 103, 41))
        self.latLongCheck.setText(QApplication.translate("MainWindow", 
                                  "Latitude/ \n"
                                  "Longitude", None, QApplication.UnicodeUTF8))
        self.latLongCheck.setObjectName("latLongCheck")
        font.setPointSize(12)
        self.latLongCheck.setFont(font)
        self.latLongCheck.setFocusPolicy(QtCore.Qt.NoFocus)

        self.colorCheck = QCheckBox(self.mainPage)
        self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41))
        self.colorCheck.setText(QApplication.translate("MainWindow", 
                                "Color\n"
                                "Coding", None, QApplication.UnicodeUTF8))
        self.colorCheck.setObjectName("colorCheck")
        self.colorCheck.setFont(font)
        self.colorCheck.setFocusPolicy(QtCore.Qt.NoFocus)
        
        self.legendCheck = QCheckBox(self.mainPage)
        self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22))
        self.legendCheck.setText(QApplication.translate("MainWindow", 
                                 "Legend", None, QApplication.UnicodeUTF8))
        self.legendCheck.setObjectName("legendCheck")
        self.legendCheck.setFocusPolicy(QtCore.Qt.NoFocus)
        
        font.setPointSize(12)
        self.legendCheck.setFont(font)
        self.searchButton = QPushButton(self.mainPage)
        self.searchButton.setStyleSheet(self.fgb)
        self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 55))
        self.searchButton.setText(QApplication.translate("MainWindow", 
                                  "Search", None, QApplication.UnicodeUTF8))
        self.searchButton.setObjectName("searchButton")
        font.setPointSize(15)
        self.searchButton.setFont(font)
        self.searchButton.setFocusPolicy(QtCore.Qt.NoFocus)
        
        #Score pieces
        self.scoreBox = QLabel(self.mainPage)
        self.scoreBox.setStyleSheet(self.fg)
        self.scoreBox.setGeometry(QtCore.QRect(720, 570, 71, 41))
        self.scoreBox.setObjectName("scoreBox")
        self.scoreBox.setText(QApplication.translate("MainWindow", 
                              "0", None, QApplication.UnicodeUTF8))
        self.scoreBox.setFont(font)
        self.scoreLabel = QLabel(self.mainPage)
        self.scoreLabel.setStyleSheet(self.fg)
        self.scoreLabel.setGeometry(QtCore.QRect(650, 580, 70, 17))
        self.scoreLabel.setText(QApplication.translate("MainWindow", 
                                "Score:", None, QApplication.UnicodeUTF8))
        self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreLabel.setObjectName("scoreLabel")
        self.scoreLabel.setFont(font)
        
        self.popup = ViewGraphics(self.mainPage)
        self.popup.setStyleSheet(
                "QGraphicsView {background:transparent;border-style:none}")
        self.popupImage = self.popup.scene.addPixmap(self.popupPixmap)
        self.popup.setGeometry(QtCore.QRect(25, 25, 750, 450))
        self.popup.setObjectName("popupLabel")
        font.setPointSize(25)
        self.popupText = self.popup.scene.addText("", font)
        self.textColor = QColor('black')
        self.popupText.setDefaultTextColor(self.textColor)
        self.popupText.setX(350)
        self.popupText.setY(225)
        self.popupImage.setOpacity(0)
        self.popupText.setOpacity(0)
        self.stackedWidget.addWidget(self.mainPage)
        
        #Help page
        self.helpPage = QWidget()
        self.helpPage.setObjectName("helpPage")
        self.HelpLabel = QLabel(self.helpPage)
        self.HelpLabel.setStyleSheet(self.fg)
        self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.HelpLabel.setFont(font)
        self.HelpLabel.setText(QApplication.translate("MainWindow", 
                               "Instructions", None, QApplication.UnicodeUTF8))
        self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.HelpLabel.setObjectName("HelpLabel")
        self.wInstr = QLabel(self.helpPage)
        self.wInstr.setStyleSheet(self.fg)
        self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30))
        font.setPointSize(20)
        self.wInstr.setFont(font)
        self.wInstr.setText(QApplication.translate("MainWindow", 
                            "W", None, QApplication.UnicodeUTF8))
        self.wInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr.setObjectName("wInstr")
        self.sInstr = QLabel(self.helpPage)
        self.sInstr.setStyleSheet(self.fg)
        self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30))
        self.sInstr.setFont(font)
        self.sInstr.setText(QApplication.translate("MainWindow", 
                            "S", None, QApplication.UnicodeUTF8))
        self.sInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr.setObjectName("sInstr")
        self.aInstr = QLabel(self.helpPage)
        self.aInstr.setStyleSheet(self.fg)
        self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30))
        self.aInstr.setFont(font)
        self.aInstr.setText(QApplication.translate("MainWindow", 
                            "A", None, QApplication.UnicodeUTF8))
        self.aInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr.setObjectName("aInstr")
        self.dInstr = QLabel(self.helpPage)
        self.dInstr.setStyleSheet(self.fg)
        self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30))
        self.dInstr.setFont(font)
        self.dInstr.setText(QApplication.translate("MainWindow", 
                            "D", None, QApplication.UnicodeUTF8))
        self.dInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr.setObjectName("dInstr")
        self.wInstr2 = QLabel(self.helpPage)
        self.wInstr2.setStyleSheet(self.fg)
        self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30))
        self.wInstr2.setFont(font)
        self.wInstr2.setText(QApplication.translate("MainWindow", 
                            "Move North", None, QApplication.UnicodeUTF8))
        self.wInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr2.setObjectName("wInstr2")
        self.sInstr2 = QLabel(self.helpPage)
        self.sInstr2.setStyleSheet(self.fg)
        self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30))
        self.sInstr2.setFont(font)
        self.sInstr2.setText(QApplication.translate("MainWindow", 
                            "Move South", None, QApplication.UnicodeUTF8))
        self.sInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr2.setObjectName("sInstr2")
        self.aInstr2 = QLabel(self.helpPage)
        self.aInstr2.setStyleSheet(self.fg)
        self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30))
        self.aInstr2.setFont(font)
        self.aInstr2.setText(QApplication.translate("MainWindow", 
                            "Move West", None, QApplication.UnicodeUTF8))
        self.aInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr2.setObjectName("aInstr2")
        self.dInstr2 = QLabel(self.helpPage)
        self.dInstr2.setStyleSheet(self.fg)
        self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30))
        self.dInstr2.setFont(font)
        self.dInstr2.setText(QApplication.translate("MainWindow", 
                            "Move East", None, QApplication.UnicodeUTF8))
        self.dInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2.setObjectName("dInstr2")
        self.searchInstr = QPushButton(self.helpPage)
        self.searchInstr.setStyleSheet(self.fgb)
        self.searchInstr.setEnabled(True)
        self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30))
        self.searchInstr.setText(QApplication.translate("MainWindow", 
                                "Search", None, QApplication.UnicodeUTF8))
        self.searchInstr.setAutoDefault(False)
        self.searchInstr.setDefault(False)
        self.searchInstr.setFlat(False)
        self.searchInstr.setObjectName("searchInstr")
        font.setPointSize(15)
        self.searchInstr.setFont(font)
        self.dInstr2_2 = QLabel(self.helpPage)
        self.dInstr2_2.setStyleSheet(self.fg)
        self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30))
        font.setPointSize(20)
        self.dInstr2_2.setFont(font)
        self.dInstr2_2.setText(QApplication.translate("MainWindow", 
                           "Search for clues", None, QApplication.UnicodeUTF8))
        self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2_2.setObjectName("dInstr2_2")
        self.doneButton2 = QPushButton(self.helpPage)
        self.doneButton2.setStyleSheet(self.fgb)
        self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton2.setText(QApplication.translate("MainWindow", 
                                 "Done", None, QApplication.UnicodeUTF8))
        self.doneButton2.setObjectName("doneButton2")
        font.setPointSize(15)
        self.doneButton2.setFont(font)
        self.stackedWidget.addWidget(self.helpPage)
        
        #Credits page
        self.creditsPage = QWidget()
        self.creditsPage.setObjectName("creditsPage")
        self.creditsLabel = QLabel(self.creditsPage)
        self.creditsLabel.setStyleSheet(self.fg)
        self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.creditsLabel.setFont(font)
        self.creditsLabel.setText(QApplication.translate("MainWindow", 
                                  "Credits", None, QApplication.UnicodeUTF8))
        self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.creditsLabel.setObjectName("creditsLabel")
        self.credits = QLabel(self.creditsPage)
        self.credits.setStyleSheet(self.fg)
        self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400))
        font.setPointSize(20)
        self.credits.setFont(font)
        self.credits.setText(QApplication.translate("MainWindow", 
        "Gary Lent\n"
        "Grant Stafford\n"
        "Jessie Liu\n"
        "Peter Andrien\n"
        "Nokia (Qt4 framework)\n"
        "Riverbank Computing Ltd (PyQt)\n"
        "Celestial Aeon Project", None, QApplication.UnicodeUTF8))
        self.credits.setAlignment(
                QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.credits.setObjectName("credits")
        self.doneButton3 = QPushButton(self.creditsPage)
        self.doneButton3.setStyleSheet(self.fgb)
        self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton3.setText(QApplication.translate("MainWindow", 
                                "Done", None, QApplication.UnicodeUTF8))
        self.doneButton3.setObjectName("doneButton3")
        font.setPointSize(15)
        self.doneButton3.setFont(font)
        self.stackedWidget.addWidget(self.creditsPage)
        
        #Story page
        self.storyPage = QWidget()
        self.storyPage.setObjectName("storyPage")
        self.storyLabel = QLabel(self.storyPage)
        self.storyLabel.setStyleSheet(self.fg)
        self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400))
        font.setPointSize(25)
        self.storyLabel.setFont(font)
        self.storyLabel.setText(QApplication.translate("MainWindow", 
        "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently"
        " lost my job, but stumbled\n on a clue that may change my life"
        " \nforever. I've set off on a quest - a quest\n to find a lost city. "
        "I've found a clue,\n and believe there may be more.\n Help me find "
        "the lost city.  ", None, QApplication.UnicodeUTF8))
        self.storyLabel.setAlignment(
                QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.storyLabel.setObjectName("storyLabel")
        self.nextButton = QPushButton(self.storyPage)
        self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.nextButton.setText(QApplication.translate("MainWindow", 
                                "Next", None, QApplication.UnicodeUTF8))
        self.nextButton.setObjectName("nextButton")
        self.nextButton.setStyleSheet(self.fgb)
        font.setPointSize(15)
        self.nextButton.setFont(font)
        self.stackedWidget.addWidget(self.storyPage)
        
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #Menu bar
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QMenu(self.menubar)
        self.menuMenu.setTitle(QApplication.translate("MainWindow", 
                               "Menu", None, QApplication.UnicodeUTF8))
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.actionSave_Game = QAction(MainWindow)
        self.actionSave_Game.setText(QApplication.translate("MainWindow", 
                                  "Save Game", None, QApplication.UnicodeUTF8))
        self.actionSave_Game.setObjectName("actionSave_Game")
        self.actionCredits = QAction(MainWindow)
        self.actionCredits.setText(QApplication.translate("MainWindow", 
                                   "Credits", None, QApplication.UnicodeUTF8))
        self.actionCredits.setObjectName("actionCredits")
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setText(QApplication.translate("MainWindow", 
                                "Quit", None, QApplication.UnicodeUTF8))
        self.actionQuit.setObjectName("actionQuit")
        self.actionSettings = QAction(MainWindow)
        self.actionSettings.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setObjectName("actionSettings")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setText(QApplication.translate("MainWindow", 
                                "Help", None, QApplication.UnicodeUTF8))
        self.actionHelp.setObjectName("actionHelp")
        self.actionMain_Menu = QAction(MainWindow)
        self.actionMain_Menu.setText(QApplication.translate("MainWindow", 
                                "Main Menu", None, QApplication.UnicodeUTF8))
        self.actionMain_Menu.setObjectName("actionMain_Menu")
        self.menuMenu.addAction(self.actionSettings)
        self.menuMenu.addAction(self.actionHelp)
        self.menuMenu.addAction(self.actionSave_Game)
        self.menuMenu.addAction(self.actionCredits)
        self.menuMenu.addAction(self.actionMain_Menu)
        self.menuMenu.addAction(self.actionQuit)
        self.menubar.addAction(self.menuMenu.menuAction())
        

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)

        self.stackIndex = 0

    def retranslateUi(self, MainWindow):
        pass
Example #19
0
class VolumeEditorWidget(QWidget):
    def __init__(self, parent=None, editor=None):
        super(VolumeEditorWidget, self).__init__(parent=parent)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setFocusPolicy(Qt.StrongFocus)

        self.editor = None
        if editor != None:
            self.init(editor)

        self._viewMenu = None

        self.allZoomToFit = QAction(QIcon(":/icons/icons/view-fullscreen.png"),
                                    "Zoom to &Fit", self)
        self.allZoomToFit.triggered.connect(self._fitToScreen)

        self.allToggleHUD = QAction(QIcon(), "Show &HUDs", self)
        self.allToggleHUD.setCheckable(True)
        self.allToggleHUD.setChecked(True)
        self.allToggleHUD.toggled.connect(self._toggleHUDs)

        self.allCenter = QAction(QIcon(), "&Center views", self)
        self.allCenter.triggered.connect(self._centerAllImages)

        self.selectedCenter = QAction(QIcon(), "C&enter view", self)
        self.selectedCenter.triggered.connect(self._centerImage)

        self.selectedZoomToFit = QAction(
            QIcon(":/icons/icons/view-fullscreen.png"), "Zoom to Fit", self)
        self.selectedZoomToFit.triggered.connect(self._fitImage)

        self.selectedZoomToOriginal = QAction(QIcon(), "Reset Zoom", self)
        self.selectedZoomToOriginal.triggered.connect(
            self._restoreImageToOriginalSize)

        self.rubberBandZoom = QAction(QIcon(), "Rubberband Zoom", self)
        self.rubberBandZoom.triggered.connect(self._rubberBandZoom)

        self.toggleSelectedHUD = QAction(QIcon(), "Show HUD", self)
        self.toggleSelectedHUD.setCheckable(True)
        self.toggleSelectedHUD.setChecked(True)
        self.toggleSelectedHUD.toggled.connect(self._toggleSelectedHud)

    def _setupVolumeExtent(self):
        '''Setup min/max values of position/coordinate control elements.

        Position/coordinate information is read from the volumeEditor's positionModel.

        '''
        maxTime = self.editor.posModel.shape5D[0] - 1
        self.quadview.statusBar.timeLabel.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setRange(0, maxTime)
        self.quadview.statusBar.timeSpinBox.setSuffix("/{}".format(maxTime))
        self.quadview.statusBar.hideTimeSlider(maxTime == 0)

        cropMidPos = [(b + a) // 2
                      for [a, b] in self.editor.cropModel._crop_extents]
        for i in range(3):
            self.editor.imageViews[i].hud.setMaximum(
                self.editor.posModel.volumeExtent(i) - 1)
            self.editor.navCtrl.changeSliceAbsolute(cropMidPos[i], i)
        self.editor.navCtrl.changeTime(self.editor.cropModel._crop_times[0])

    def init(self, volumina):
        self.editor = volumina

        self.hudsShown = [True] * 3

        def onViewFocused():
            axis = self.editor._lastImageViewFocus
            self.toggleSelectedHUD.setChecked(
                self.editor.imageViews[axis]._hud.isVisible())

        self.editor.newImageView2DFocus.connect(onViewFocused)

        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.setLayout(self.layout)

        # setup quadview
        axisLabels = ["X", "Y", "Z"]
        axisColors = [QColor("#dc143c"), QColor("green"), QColor("blue")]
        for i, v in enumerate(self.editor.imageViews):
            v.hud = ImageView2DHud(v)
            #connect interpreter
            v.hud.createImageView2DHud(axisLabels[i], 0, axisColors[i],
                                       QColor("white"))
            v.hud.sliceSelector.valueChanged.connect(
                partial(self.editor.navCtrl.changeSliceAbsolute, axis=i))

        self.quadview = QuadView(self, self.editor.imageViews[2],
                                 self.editor.imageViews[0],
                                 self.editor.imageViews[1], self.editor.view3d)
        self.quadview.installEventFilter(self)
        self.quadViewStatusBar = QuadStatusBar()
        self.quadViewStatusBar.createQuadViewStatusBar(QColor("#dc143c"),
                                                       QColor("white"),
                                                       QColor("green"),
                                                       QColor("white"),
                                                       QColor("blue"),
                                                       QColor("white"))
        self.quadview.addStatusBar(self.quadViewStatusBar)
        self.layout.addWidget(self.quadview)

        # Here we subscribe to the dirtyChanged() signal from all slicing views,
        #  and show the status bar "busy indicator" if any view is dirty.
        # Caveat: To avoid a flickering indicator for quick updates, we use a
        #         timer that prevents the indicator from showing for a bit.
        def updateDirtyStatus(fromTimer=False):
            # We only care about views that are both VISIBLE and DIRTY.
            dirties = map(lambda v: v.scene().dirty, self.editor.imageViews)
            visibilities = map(lambda v: v.isVisible(), self.editor.imageViews)
            visible_dirtiness = numpy.logical_and(visibilities, dirties)

            if not any(visible_dirtiness):
                # Not dirty: Hide immediately
                self.quadViewStatusBar.busyIndicator.setVisible(False)
            else:
                if fromTimer:
                    # The timer finished and we're still dirty:
                    # Time to show the busy indicator.
                    self.quadViewStatusBar.busyIndicator.setVisible(True)
                elif not self.quadViewStatusBar.busyIndicator.isVisible(
                ) and not self._dirtyTimer.isActive():
                    # We're dirty, but delay for a bit before showing the busy indicator.
                    self._dirtyTimer.start(750)

        self._dirtyTimer = QTimer()
        self._dirtyTimer.setSingleShot(True)
        self._dirtyTimer.timeout.connect(
            partial(updateDirtyStatus, fromTimer=True))
        for i, view in enumerate(self.editor.imageViews):
            view.scene().dirtyChanged.connect(updateDirtyStatus)

        # If the user changes the position in the quad-view status bar (at the bottom),
        # Update the position of the whole editor.
        def setPositionFromQuadBar(x, y, z):
            self.editor.posModel.slicingPos = (x, y, z)
            self.editor.posModel.cursorPos = (x, y, z)
            self.editor.navCtrl.panSlicingViews((x, y, z), [0, 1, 2])

        self.quadViewStatusBar.positionChanged.connect(setPositionFromQuadBar)

        ## Why do we have to prevent TimerEvents reaching the SpinBoxes?
        #
        # Sometimes clicking a SpinBox once caused the value to increase by
        # two. This is why:
        #
        # When a MouseClicked event is received by the SpinBox it fires a timerevent to control
        # the repeated increase of the value as long as the mouse button is pressed. The timer
        # is killed when it receives a MouseRelease event. If a slot connected to the valueChanged
        # signal of the SpinBox takes to long to process the signal the mouse release
        # and timer events get queued up and sometimes the timer event reaches the widget before
        # the mouse release event. That's why it increases the value by another step. To prevent
        # this we are blocking the timer events at the cost of no autorepeat anymore.
        #
        # See also:
        # http://lists.trolltech.com/qt-interest/2002-04/thread00137-0.html
        # http://www.qtcentre.org/threads/43078-QSpinBox-Timer-Issue
        # http://qt.gitorious.org/qt/qt/blobs/4.8/src/gui/widgets/qabstractspinbox.cpp#line1195
        self.quadview.statusBar.timeSpinBox.installEventFilter(_timerEater)

        def setTime(t):
            if t == self.editor.posModel.time:
                return
            self.editor.posModel.time = t

        self.quadview.statusBar.timeSpinBox.delayedValueChanged.connect(
            setTime)

        def setTimeSpinBox(newT):
            self.quadview.statusBar.timeSpinBox.setValue(newT)

        self.editor.posModel.timeChanged.connect(setTimeSpinBox)

        def toggleSliceIntersection(state):
            self.editor.navCtrl.indicateSliceIntersection = (
                state == Qt.Checked)

        self.quadview.statusBar.positionCheckBox.stateChanged.connect(
            toggleSliceIntersection)
        toggleSliceIntersection(
            self.quadview.statusBar.positionCheckBox.checkState())

        self.editor.posModel.cursorPositionChanged.connect(
            self._updateInfoLabels)

        def onShapeChanged():
            # By default, 3D HUD buttons are visible,
            #  but we'll turn them off below if the dataset is 2D.
            for axis in [0, 1, 2]:
                self.editor.imageViews[axis].hud.set3DButtonsVisible(True)

            singletonDims = filter(
                lambda (i, dim): dim == 1,
                enumerate(self.editor.posModel.shape5D[1:4]))
            if len(singletonDims) == 1:
                # Maximize the slicing view for this axis
                axis = singletonDims[0][0]
                self.quadview.ensureMaximized(axis)
                self.hudsShown[axis] = self.editor.imageViews[axis].hudVisible(
                )
                self.editor.imageViews[axis].hud.set3DButtonsVisible(False)
                self.quadViewStatusBar.showXYCoordinates()

                self.quadview.statusBar.positionCheckBox.setVisible(False)
            else:
                self.quadViewStatusBar.showXYZCoordinates()
                for i in range(3):
                    self.editor.imageViews[i].setHudVisible(self.hudsShown[i])
                self.quadview.statusBar.positionCheckBox.setVisible(True)

            if self.editor.cropModel._crop_extents[0][
                    0] == None or self.editor.cropModel.cropZero():
                self.quadViewStatusBar.updateShape5D(
                    self.editor.posModel.shape5D)
            else:
                cropMin = (self.editor.posModel.time,
                           self.editor.cropModel._crop_extents[0][0],
                           self.editor.cropModel._crop_extents[1][0],
                           self.editor.cropModel._crop_extents[2][0], 0)
                self.quadViewStatusBar.updateShape5Dcropped(
                    cropMin, self.editor.posModel.shape5D)

            self._setupVolumeExtent()

        self.editor.shapeChanged.connect(onShapeChanged)

        self.updateGeometry()
        self.update()
        self.quadview.update()
        if hasattr(self.editor.view3d, 'bUndock'):
            self.editor.view3d.bUndock.clicked.connect(
                partial(self.quadview.on_dock,
                        self.quadview.dock2_ofSplitHorizontal2))

        # shortcuts
        self._initShortcuts()

    def _toggleDebugPatches(self, show):
        self.editor.showDebugPatches = show

    def _fitToScreen(self):
        shape = self.editor.posModel.shape
        for i, v in enumerate(self.editor.imageViews):
            s = list(copy.copy(shape))
            del s[i]
            v.changeViewPort(v.scene().data2scene.mapRect(QRectF(0, 0, *s)))

    def _fitImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].fitImage()

    def _restoreImageToOriginalSize(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()

    def _rubberBandZoom(self):
        if self.editor._lastImageViewFocus is not None:
            if not self.editor.imageViews[
                    self.editor._lastImageViewFocus]._isRubberBandZoom:
                self.editor.imageViews[
                    self.editor._lastImageViewFocus]._isRubberBandZoom = True
                self.editor.imageViews[
                    self.editor.
                    _lastImageViewFocus]._cursorBackup = self.editor.imageViews[
                        self.editor._lastImageViewFocus].cursor()
                self.editor.imageViews[
                    self.editor._lastImageViewFocus].setCursor(Qt.CrossCursor)
            else:
                self.editor.imageViews[
                    self.editor._lastImageViewFocus]._isRubberBandZoom = False
                self.editor.imageViews[
                    self.editor._lastImageViewFocus].setCursor(
                        self.editor.imageViews[
                            self.editor._lastImageViewFocus]._cursorBackup)

    def _toggleHUDs(self, checked):
        for v in self.editor.imageViews:
            v.setHudVisible(checked)

    def _toggleSelectedHud(self, checked):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[
                self.editor._lastImageViewFocus].setHudVisible(checked)

    def _centerAllImages(self):
        for v in self.editor.imageViews:
            v.centerImage()

    def _centerImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[
                self.editor._lastImageViewFocus].centerImage()

    def _initShortcuts(self):
        # TODO: Fix this dependency on ImageView/HUD internals
        mgr = ShortcutManager()
        ActionInfo = ShortcutManager.ActionInfo
        mgr.register(
            "x",
            ActionInfo("Navigation", "Minimize/Maximize x-Window",
                       "Minimize/Maximize x-Window",
                       self.quadview.switchXMinMax,
                       self.editor.imageViews[0].hud.buttons['maximize'],
                       self.editor.imageViews[0].hud.buttons['maximize']))

        mgr.register(
            "y",
            ActionInfo("Navigation", "Minimize/Maximize y-Window",
                       "Minimize/Maximize y-Window",
                       self.quadview.switchYMinMax,
                       self.editor.imageViews[1].hud.buttons['maximize'],
                       self.editor.imageViews[1].hud.buttons['maximize']))

        mgr.register(
            "z",
            ActionInfo("Navigation", "Minimize/Maximize z-Window",
                       "Minimize/Maximize z-Window",
                       self.quadview.switchZMinMax,
                       self.editor.imageViews[2].hud.buttons['maximize'],
                       self.editor.imageViews[2].hud.buttons['maximize']))

        for i, v in enumerate(self.editor.imageViews):
            mgr.register(
                "+",
                ActionInfo("Navigation", "Zoom in", "Zoom in", v.zoomIn, v,
                           None))
            mgr.register(
                "-",
                ActionInfo("Navigation", "Zoom out", "Zoom out", v.zoomOut, v,
                           None))

            mgr.register(
                "c",
                ActionInfo("Navigation", "Center image", "Center image",
                           v.centerImage, v, None))

            mgr.register(
                "h",
                ActionInfo("Navigation", "Toggle hud", "Toggle hud",
                           v.toggleHud, v, None))

            # FIXME: The nextChannel/previousChannel functions don't work right now.
            #self._shortcutHelper("q", "Navigation", "Switch to next channel",     v, self.editor.nextChannel,     Qt.WidgetShortcut))
            #self._shortcutHelper("a", "Navigation", "Switch to previous channel", v, self.editor.previousChannel, Qt.WidgetShortcut))

            def sliceDelta(axis, delta):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] += delta
                newPos[axis] = max(0, newPos[axis])
                newPos[axis] = min(self.editor.posModel.shape[axis] - 1,
                                   newPos[axis])
                self.editor.posModel.slicingPos = newPos

            def jumpToFirstSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = 0
                self.editor.posModel.slicingPos = newPos

            def jumpToLastSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = self.editor.posModel.shape[axis] - 1
                self.editor.posModel.slicingPos = newPos

            # TODO: Fix this dependency on ImageView/HUD internals
            mgr.register(
                "Ctrl+Up",
                ActionInfo("Navigation", "Slice up", "Slice up",
                           partial(sliceDelta, i, 1), v,
                           v.hud.buttons['slice'].upLabel))

            mgr.register(
                "Ctrl+Down",
                ActionInfo("Navigation", "Slice up", "Slice up",
                           partial(sliceDelta, i, -1), v,
                           v.hud.buttons['slice'].downLabel))

            #            self._shortcutHelper("p", "Navigation", "Slice up (alternate shortcut)",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut)
            #            self._shortcutHelper("o", "Navigation", "Slice down (alternate shortcut)", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut)

            mgr.register(
                "Ctrl+Shift+Up",
                ActionInfo("Navigation", "10 slices up", "10 slices up",
                           partial(sliceDelta, i, 10), v, None))

            mgr.register(
                "Ctrl+Shift+Down",
                ActionInfo("Navigation", "10 slices down", "10 slices down",
                           partial(sliceDelta, i, -10), v, None))

            mgr.register(
                "Shift+Up",
                ActionInfo("Navigation",
                           "Jump to first slice", "Jump to first slice",
                           partial(jumpToFirstSlice, i), v, None))

            mgr.register(
                "Shift+Down",
                ActionInfo("Navigation",
                           "Jump to last slice", "Jump to last slice",
                           partial(jumpToLastSlice, i), v, None))

    def _updateInfoLabels(self, pos):
        self.quadViewStatusBar.setMouseCoords(*pos)

    def eventFilter(self, watched, event):
        # If the user performs a ctrl+scroll on the splitter itself,
        # scroll all views.
        if event.type() == QEvent.Wheel and (event.modifiers()
                                             == Qt.ControlModifier):
            for view in self.editor.imageViews:
                if event.delta() > 0:
                    view.zoomIn()
                else:
                    view.zoomOut()
            return True
        return False

    def getViewMenu(self, debug_mode=False):
        """
        Return a QMenu with a set of actions for our editor.
        """
        if self._viewMenu is None:
            self._initViewMenu()
        for action in self._debugActions:
            action.setEnabled(debug_mode)
            action.setVisible(debug_mode)
        return self._viewMenu

    def _initViewMenu(self):
        self._viewMenu = QMenu("View", parent=self)
        self._viewMenu.setObjectName("view_menu")
        self._debugActions = []

        ActionInfo = ShortcutManager.ActionInfo

        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionFitToScreen = self._viewMenu.addAction(
            "&Zoom to &fit")
        self._viewMenu.actionFitToScreen.triggered.connect(self._fitToScreen)

        def toggleHud():
            hide = not self.editor.imageViews[0]._hud.isVisible()
            for v in self.editor.imageViews:
                v.setHudVisible(hide)

        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionToggleAllHuds = self._viewMenu.addAction(
            "Toggle huds")
        self._viewMenu.actionToggleAllHuds.triggered.connect(toggleHud)

        def resetAllAxes():
            for s in self.editor.imageScenes:
                s.resetAxes()

        self._viewMenu.addAction("Reset all axes").triggered.connect(
            resetAllAxes)

        def centerAllImages():
            for v in self.editor.imageViews:
                v.centerImage()

        self._viewMenu.addAction("Center images").triggered.connect(
            centerAllImages)

        def toggleDebugPatches(show):
            self.editor.showDebugPatches = show

        actionShowTiling = self._viewMenu.addAction("Show Tiling")
        actionShowTiling.setCheckable(True)
        actionShowTiling.toggled.connect(toggleDebugPatches)
        ShortcutManager().register(
            "Ctrl+D",
            ActionInfo("Navigation", "Show tiling", "Show tiling",
                       actionShowTiling.toggle, self, None))
        self._debugActions.append(actionShowTiling)

        def setCacheSize(cache_size):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget(QLabel("Cached Slices Per View:"))

            spinBox = QSpinBox(parent=dlg)
            spinBox.setRange(0, 1000)
            spinBox.setValue(self.editor.cacheSize)
            layout.addWidget(spinBox)
            okButton = QPushButton("OK", parent=dlg)
            okButton.clicked.connect(dlg.accept)
            layout.addWidget(okButton)
            dlg.setLayout(layout)
            dlg.setModal(True)
            if dlg.exec_() == QDialog.Accepted:
                self.editor.cacheSize = spinBox.value()

        self._viewMenu.addAction("Set layer cache size").triggered.connect(
            setCacheSize)

        def enablePrefetching(enable):
            # Enable for Z view only
            self.editor.imageScenes[2].setPrefetchingEnabled(enable)
#             for scene in self.editor.imageScenes:
#                 scene.setPrefetchingEnabled( enable )

        actionUsePrefetching = self._viewMenu.addAction("Use prefetching")
        actionUsePrefetching.setCheckable(True)
        actionUsePrefetching.toggled.connect(enablePrefetching)

        def blockGuiForRendering():
            for v in self.editor.imageViews:
                v.scene().joinRenderingAllTiles()
                v.repaint()
            QApplication.processEvents()

        actionBlockGui = self._viewMenu.addAction("Block for rendering")
        actionBlockGui.triggered.connect(blockGuiForRendering)
        ShortcutManager().register(
            "Ctrl+B",
            ActionInfo("Navigation", "Block gui for rendering",
                       "Block gui for rendering", actionBlockGui.trigger, self,
                       None))
        self._debugActions.append(actionBlockGui)

        # ------ Separator ------
        self._viewMenu.addAction("").setSeparator(True)

        # Text only
        actionOnlyForSelectedView = self._viewMenu.addAction(
            "Only for selected view")
        actionOnlyForSelectedView.setIconVisibleInMenu(True)
        font = actionOnlyForSelectedView.font()
        font.setItalic(True)
        font.setBold(True)
        actionOnlyForSelectedView.setFont(font)

        def setCurrentAxisIcon():
            """Update the icon that shows the currently selected axis."""
            actionOnlyForSelectedView.setIcon(
                QIcon(self.editor.imageViews[
                    self.editor._lastImageViewFocus]._hud.axisLabel.pixmap()))

        self.editor.newImageView2DFocus.connect(setCurrentAxisIcon)
        setCurrentAxisIcon()

        actionFitImage = self._viewMenu.addAction("Fit image")
        actionFitImage.triggered.connect(self._fitImage)
        ShortcutManager().register(
            "K",
            ActionInfo("Navigation", "Fit image on screen",
                       "Fit image on screen", actionFitImage.trigger, self,
                       None))

        def toggleSelectedHud():
            self.editor.imageViews[self.editor._lastImageViewFocus].toggleHud()

        actionToggleSelectedHud = self._viewMenu.addAction("Toggle hud")
        actionToggleSelectedHud.triggered.connect(toggleSelectedHud)

        def resetAxes():
            self.editor.imageScenes[
                self.editor._lastImageViewFocus].resetAxes()

        self._viewMenu.addAction("Reset axes").triggered.connect(resetAxes)

        def centerImage():
            self.editor.imageViews[
                self.editor._lastImageViewFocus].centerImage()

        actionCenterImage = self._viewMenu.addAction("Center image")
        actionCenterImage.triggered.connect(centerImage)
        ShortcutManager().register(
            "C",
            ActionInfo("Navigation", "Center image", "Center image",
                       actionCenterImage.trigger, self, None))

        def restoreImageToOriginalSize():
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()

        actionResetZoom = self._viewMenu.addAction("Reset zoom")
        actionResetZoom.triggered.connect(restoreImageToOriginalSize)
        ShortcutManager().register(
            "W",
            ActionInfo("Navigation", "Reset zoom", "Reset zoom",
                       actionResetZoom.trigger, self, None))

        def updateHudActions():
            dataShape = self.editor.dataShape
            # if the image is 2D, do not show the HUD action (issue #190)
            is2D = numpy.sum(numpy.asarray(dataShape[1:4]) == 1) == 1
            actionToggleSelectedHud.setVisible(not is2D)
            self._viewMenu.actionToggleAllHuds.setVisible(not is2D)

        self.editor.shapeChanged.connect(updateHudActions)
Example #20
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app, debug=False):
        super(MainWindow, self).__init__()
        # Tab management private attributes, modify at own risk
        self.__tabMoved = False
        self.__tabAreaInformation = (-1, -1, [])
        self.__tabConnections = set()
        self.app = app
        self.debug = debug
        self.sched = scheduler.sched
        self.vfs = vfs.vfs()
        self.createRootNodes()
        self.dialog = Dialog(self)
        self.initCallback()
        self.setupUi(self)
        self.translation()
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 1014, 693).size()).expandedTo(
                self.minimumSizeHint()))
        self.shellActions = ShellActions(self)
        self.interpreterActions = InterpreterActions(self)
        self.setCentralWidget(None)
        self.setDockNestingEnabled(True)
        self.init()
        self.status = QStackedWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        self.status.setSizePolicy(sizePolicy)
        self.statusBar().addWidget(self.status)

    def setupUi(self, MainWindow):
        self.actionWizard = QAction(self)
        icon = QIcon()
        icon.addPixmap(QPixmap(QString.fromUtf8(":/wizard")), QIcon.Normal,
                       QIcon.Off)
        self.actionWizard.setIcon(icon)
        self.actionWizard.setObjectName(QString.fromUtf8("actionWizard"))

        Ui_MainWindow.setupUi(self, MainWindow)
        self.menuFile.insertAction(self.actionOpen_evidence, self.actionWizard)
        self.retranslateUi(MainWindow)

        if REPORT_EDITOR:
            self.actionReport = QAction(self)
            icon = QIcon()
            icon.addPixmap(QPixmap(QString.fromUtf8(":report")), QIcon.Normal,
                           QIcon.Off)
            self.actionReport.setIcon(icon)
            self.actionReport.setObjectName(QString.fromUtf8("actionReport"))

            self.menuReport = QMenu(self.menubar)
            self.menuReport.setObjectName(QString.fromUtf8("menuReport"))
            self.menuReport.addAction(self.actionReport)
            self.actionReport.setText(
                QApplication.translate("MainWindow", "Report", None,
                                       QApplication.UnicodeUTF8))
            self.actionReport.setToolTip(
                QApplication.translate("MainWindow", "Open the report editor",
                                       None, QApplication.UnicodeUTF8))
            try:
                self.menuReport.setTitle(
                    QApplication.translate("MainWindow", "Report", None,
                                           QApplication.UnicodeUTF8))
            except AttributeError:
                pass

    def retranslateUi(self, MainWindow):
        Ui_MainWindow.retranslateUi(self, MainWindow)
        self.actionWizard.setText(
            QApplication.translate("MainWindow", "Wizard", None,
                                   QApplication.UnicodeUTF8))

    def init(self):
        self.initConnection()
        # Set up toolbar
        self.initToolbarList()
        self.setupToolBar()

        # Set up modules menu
        self.MenuTags = MenuTags(self, self)
        self.refreshTabifiedDockWidgets()

    def cclose(self):
        #stats = yappi.get_func_stats()
        #stats.save("func_stats_cgrind.out", type="callgrind")
        #stats.save("func_stats_pstat.out", type="pstat")
        #threadstats = yappi.get_thread_stats()
        #threadstats.save("thread_stats_cgrind.out", type="callgrind")
        #threadstats.save("thread_stats_pstat.out", type="pstat")
        self.close()

    def initConnection(self):
        ## File menu
        self.connect(self.actionOpen_evidence, SIGNAL("triggered()"),
                     self.dialog.addFiles)
        self.connect(self.actionOpen_device, SIGNAL("triggered()"),
                     self.dialog.addDevices)
        self.connect(self.actionExit, SIGNAL("triggered()"), self.cclose)
        ## Edit menu
        self.connect(self.actionPreferences, SIGNAL("triggered()"),
                     self.dialog.preferences)
        ## Module menu
        self.connect(self.actionLoadModule, SIGNAL("triggered()"),
                     self.dialog.loadDriver)
        self.connect(self.actionBrowse_modules, SIGNAL("triggered()"),
                     self.dialog.manager)
        ## Ide menu
        #self.connect(self.actionIdeOpen, SIGNAL("triggered()"), self.addIde)
        ## View menu
        self.connect(self.actionMaximize, SIGNAL("triggered()"),
                     self.maximizeDockwidget)
        self.connect(self.actionFullscreen_mode, SIGNAL("triggered()"),
                     self.fullscreenMode)
        self.connect(self.actionNodeBrowser, SIGNAL("triggered()"),
                     self.addNodeBrowser)
        self.connect(self.actionShell, SIGNAL("triggered()"),
                     self.shellActions.create)
        self.connect(self.actionPython_interpreter, SIGNAL("triggered()"),
                     self.interpreterActions.create)  ## About menu

        self.connect(self.actionHelp, SIGNAL("triggered()"),
                     self.addHelpWidget)
        self.connect(self.actionAbout, SIGNAL("triggered()"),
                     self.dialog.about)
        self.connect(self.actionWizard, SIGNAL('triggered()'), self.autoWizard)
        if REPORT_EDITOR:
            self.connect(self.actionReport, SIGNAL("triggered()"),
                         self.addReportEdit)
            self.connect(self, SIGNAL("addReportEdit()"), self.addReportEdit)

    def initToolbarList(self):
        self.toolbarList = [
            self.actionOpen_evidence,
            self.actionOpen_device,
            None,
            self.actionNodeBrowser,
            self.actionShell,
            self.actionPython_interpreter,
            #                            self.actionIdeOpen,
            #                            self.actionHelp,
            #                            None,
            #                            self.actionMaximize,
            #                            self.actionFullscreen_mode,
            #                            self.actionBrowse_modules,
        ]
        self.toolbarList.insert(0, self.actionWizard)
        if REPORT_EDITOR:
            self.toolbarList.insert(
                len(self.toolbarList) - 1, self.actionReport)

#############  DOCKWIDGETS FUNCTIONS ###############

    def createDockWidget(self, widget, widgetName):
        dockwidget = DockWidget(self, widget, widgetName)
        dockwidget.setAllowedAreas(Qt.AllDockWidgetAreas)
        return dockwidget

    def addDockWidgets(self, widget, internalName, master=True):
        if widget is None:
            return
        if self.last_state is not None:
            self.maximizeDockwidget()
        if widget.windowTitle() != "":
            wname = widget.windowTitle()
        else:
            wname = widget.name
        new_master = self.getMasterDockWidget()
        if new_master != None:
            self.master = new_master
        dockwidget = self.createDockWidget(widget, wname)
        docIndex, docTitle = self.getWidgetName(wname)
        dockwidget.setWindowTitle(QString.fromUtf8(docTitle))
        self.connect(dockwidget, SIGNAL("resizeEvent"), widget.resize)

        self.addDockWidget(self.masterArea, dockwidget)
        if master:
            self.tabifyDockWidget(self.master, dockwidget)
        else:
            self.tabifyDockWidget(self.second, dockwidget)

        if docIndex:
            self.dockWidget[internalName + str(docIndex)] = dockwidget
        else:
            self.dockWidget[internalName] = dockwidget
        self.refreshTabifiedDockWidgets()

    def getWidgetName(self, name):
        did = 0
        for d in self.dockWidget:
            if self.dockWidget[d].windowTitle().startsWith(QString(name)):
                did += 1
        if did > 0:
            name = name + ' ' + str(did)
        return (did, name)

    def addSingleDock(self, name, cl, master=False):
        try:
            self.dockWidget[name].show()
            self.refreshTabifiedDockWidgets()
        except KeyError:
            w = cl(self)
            self.addDockWidgets(w, name, master)

    def getNodeBrowser(self):
        nb = self.nodeListWidgets()
        return nb

    def addNodeBrowser(self, rootpath=None, selectedNode=None):
        nb = self.getNodeBrowser()
        self.addDockWidgets(nb, 'nodeBrowser')
        nb.setCurrentContext(rootpath, selected=selectedNode)

    def addSearchTab(self, search):
        self.addDockWidgets(search, 'Searchr')

    def addHelpWidget(self):
        if hasattr(sys, "frozen"):
            path = os.path.abspath(
                os.path.join(os.path.dirname(sys.executable),
                             "resources/docs/dff_doc.qhc"))
        else:
            conf = Conf()
            path = conf.docPath
        file = QFile(path)
        if not file.exists(path):
            if path:
                dialog = QMessageBox.warning(
                    self, self.errorLoadingHelp,
                    QString(path) + ": " + self.notAnHelpFile)
            else:
                dialog = QMessageBox.warning(self, self.errorLoadingHelp,
                                             self.noSuchHelpFile)
            return
        self.addDockWidgets(Help(self, path=path), 'help')

    def addInterpreter(self):
        self.addSingleDock("Interpreter", Interpreter)

    def initDockWidgets(self):
        """Init Dock in application and init DockWidgets"""
        widgetPos = [
            (Qt.TopLeftCorner, Qt.LeftDockWidgetArea, QTabWidget.North),
            (Qt.BottomLeftCorner, Qt.BottomDockWidgetArea, QTabWidget.North),
            (Qt.TopLeftCorner, Qt.TopDockWidgetArea, QTabWidget.North),
            (Qt.BottomRightCorner, Qt.RightDockWidgetArea, QTabWidget.North)
        ]

        for corner, area, point in widgetPos:
            self.setCorner(corner, area)
            try:
                self.setTabPosition(area, point)
            except AttributeError:
                pass
        self.dockWidget = {}
        self.widget = {}
        self.masterArea = Qt.TopDockWidgetArea
        self.secondArea = Qt.BottomDockWidgetArea
        self.last_state = None
        self.last_dockwidget = None
        self.last_widget = None

        self.createFirstWidgets()

        self.refreshSecondWidgets()
        self.refreshTabifiedDockWidgets()
        if REPORT_EDITOR:
            self.addReportEdit()
            self.dockWidget['Report'].setVisible(False)

    def autoWizard(self):
        autoWiz = AutoWizard(self)
        autoWiz.exec_()

    def nodeListWidgets(self, parent=None):
        return NodeListWidgets(parent)

    def createProcessusWidget(self):
        return Processus(self)

    def createSTDOutWidget(self):
        return STDOut(self, self.debug)

    def createSTDErrWidget(self):
        return STDErr(self, self.debug)

    def addReportEdit(self):
        self.addSingleDock("Report", ReportEditor, master=True)

    def showReportEdit(self):
        self.emit(SIGNAL("addReportEdit()"))

    def createFirstWidgets(self):
        self.nodeBrowser = self.nodeListWidgets(parent=self)
        root = self.vfs.getnode('/')
        self.nodeBrowser.setCurrentContext(root)

        self.master = self.createDockWidget(self.nodeBrowser,
                                            self.nodeBrowser.name)
        self.master.setAllowedAreas(Qt.AllDockWidgetAreas)
        self.master.setWindowTitle(self.nodeBrowser.name)
        self.dockWidget["nodebrowser"] = self.master

        self.wprocessus = self.createProcessusWidget()
        self.second = self.createDockWidget(self.wprocessus, "Task manager")
        self.second.setAllowedAreas(Qt.AllDockWidgetAreas)
        self.second.setWindowTitle(self.wprocessus.windowTitle())
        self.dockWidget["Task manager"] = self.second
        self.addDockWidget(self.masterArea, self.master)
        self.addDockWidget(self.secondArea, self.second)
        self.timer = QTimer(self)
        self.connect(self.timer, SIGNAL("timeout()"),
                     self.refreshSecondWidgets)
        self.timer.start(2000)

        self.wstdout = self.createSTDOutWidget()
        self.wstderr = self.createSTDErrWidget()

        self.addDockWidgets(self.wstdout, 'stdout', master=False)
        self.addDockWidgets(self.wstderr, 'stderr', master=False)
        self.wmodules = Modules(self)
        self.addDockWidgets(self.wmodules, 'modules', master=False)
        self.preview = Preview(self)
        self.addDockWidgets(self.preview, 'preview', master=False)
        self.connect(self, SIGNAL("previewUpdate"), self.preview.update)

        self.wpostprocess = PostProcessStateWidget(self)
        self.addDockWidgets(self.wpostprocess, "Post Process State", False)

    def maximizeDockwidget(self):
        if self.last_state is None:
            self.last_state = self.saveState()
            focus_widget = QApplication.focusWidget()
            for key, dock in self.dockWidget.iteritems():
                dock.hide()
                if dock.isAncestorOf(focus_widget):
                    self.last_dockwidget = dock
            if self.last_dockwidget != None:
                self.last_widget = self.last_dockwidget.widget()
                self.last_dockwidget.toggleViewAction().setDisabled(True)
                self.setCentralWidget(self.last_dockwidget.widget())
                self.last_dockwidget.visibility_changed(True)
                self.actionNodeBrowser.setEnabled(False)
                self.actionShell.setEnabled(False)
                self.actionPython_interpreter.setEnabled(False)
                #self.actionIdeOpen.setEnabled(False)
                self.actionHelp.setEnabled(False)
            else:
                self.last_state = None
        else:
            self.last_dockwidget.setWidget(self.last_widget)
            self.last_dockwidget.toggleViewAction().setEnabled(True)
            self.setCentralWidget(None)
            self.restoreState(self.last_state)
            self.last_dockwidget.setFocus()
            self.last_state = None
            self.last_widget = None
            self.last_dockwidget = None
            self.refreshTabifiedDockWidgets()
            self.actionNodeBrowser.setEnabled(True)
            self.actionShell.setEnabled(True)
            self.actionPython_interpreter.setEnabled(True)
            #self.actionIdeOpen.setEnabled(True)
            self.actionHelp.setEnabled(True)

    def fullscreenMode(self):
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()

    def refreshSecondWidgets(self):
        if self.dockWidget["Task manager"].visibility():
            self.wprocessus.LoadInfoProcess()
        if self.dockWidget["modules"].visibility():
            self.wmodules.LoadInfoModules()

    #
    # Following methods are in charge of tab management
    # By default tabified dock widgets are not movable.
    # And juste setting setMovable(True) is not enough.
    # All the magic is done in private class of Qt and
    # can't be overloaded. The last chance is to play
    # with signal and children management.
    #
    def updateTabConnections(self):
        children = self.children()
        for child in children:
            if child.inherits("QTabBar"):
                tabCount = child.count()
                child.setMovable(True)
                if child not in self.__tabConnections:
                    child.tabMoved.connect(self.tabMoved,
                                           type=Qt.UniqueConnection)
                    self.__tabConnections.add(child)

    # overloaded to add connections on new tabbar item
    def tabifyDockWidget(self, first, second):
        QMainWindow.tabifyDockWidget(self, first, second)
        self.updateTabConnections()

    # overloaded to connect to dockwidget location update
    def addDockWidget(self, area, dockwidget):
        dockwidget.dockLocationChanged.connect(self.updateTabConnections)
        return QMainWindow.addDockWidget(self, area, dockwidget)

    def event(self, event):
        mouse_status = int(QApplication.mouseButtons())
        # if updating tabbar while mouse pressed, behaviour can be weird
        if mouse_status & 0x00000001 == 0 and self.__tabMoved:
            self.__tabMoved = False
            self.updateTabBar()
        return QMainWindow.event(self, event)

    def updateTabBar(self):
        tab, to, _from = self.__tabAreaInformation
        dockwidget, siblings = self.findDockWidgetsFromTabBar(tab)
        updated_siblings = []
        visible = []
        hidden = []
        for sibling in siblings:
            if sibling.isVisible():
                visible.append(sibling)
            else:
                hidden.append(sibling)
        if to == 0:
            updated_siblings.append(dockwidget)
            updated_siblings += visible + hidden
        else:
            master = visible.pop(0)
            updated_siblings.append(master)
            visible.insert(to - 1, dockwidget)
            updated_siblings += visible + hidden
        master = updated_siblings.pop(0)
        for sibling in updated_siblings:
            # always check if sibling != None or result in segfault if happens
            if sibling is not None:
                self.tabifyDockWidget(master, sibling)
        tab.setCurrentIndex(to)
        self.refreshTabifiedDockWidgets()

    # returns the location of the master dock widget (first created browser)
    def getMasterDockWidget(self):
        x_max = self.geometry().bottomRight().x()
        y_max = self.geometry().bottomRight().y()
        children = self.children()
        item = None
        for child in children:
            if child.inherits("QTabBar") or (child.inherits("QDockWidget")
                                             and child.isVisible()):
                child_x = child.geometry().topLeft().x()
                child_y = child.geometry().topLeft().y()
                if child_x >= 0 and child_y >= 0 and child_x <= x_max and child_y <= y_max:
                    x_max = child_x
                    y_max = child_y
                    item = child
        if item is not None:
            if item.inherits("QDockWidget"):
                return item
            else:
                title = item.tabText(0)
                for dockwidget in self.dockWidget.values():
                    if title.startsWith(dockwidget.windowTitle()):
                        return dockwidget
        else:
            # at init, there's no information, return None and keep self.master as is
            return None

    def refreshTabifiedDockWidgets(self):
        children = self.children()
        for child in children:
            if child.inherits("QTabBar"):
                tabCount = child.count()
                for idx in xrange(0, tabCount):
                    for v in self.dockWidget.values():
                        if v.widget() and child.tabText(idx).startsWith(
                                v.windowTitle(
                                )) and not v.widget().windowIcon().isNull():
                            child.setTabIcon(idx, v.widget().windowIcon())

    # to and _from are volontary swapped here compared to the sent signal.
    def tabMoved(self, to, _from):
        tab = self.sender()
        self.__tabAreaInformation = (tab, to, _from)
        self.__tabMoved = True

    # gather all widgets associated to a tabbar
    # returns a tuple with first element being the
    # widget associated to currentIndex and the second
    # elements being its siblings
    def findDockWidgetsFromTabBar(self, tab):
        tabwidget = None
        tabname = ""
        if not isinstance(tab, QTabBar):
            return None
        siblings = []
        current_widget = None
        for i in xrange(0, tab.count()):
            title = tab.tabText(i)
            for dockwidget in self.dockWidget.values():
                if title == dockwidget.windowTitle():
                    if i == tab.currentIndex():
                        current_widget = dockwidget
                    else:
                        siblings.append(dockwidget)
        return (current_widget, siblings)


#############  END OF DOCKWIDGETS FUNCTIONS ###############

    def applyModule(self, modname, modtype, selected):
        appMod = ApplyModule(self)
        appMod.openApplyModule(modname, modtype, selected)

    def initCallback(self):
        self.sched.set_callback("add_qwidget", self.qwidgetResult)
        self.connect(self, SIGNAL("qwidgetResultView"), self.qwidgetResultView)
        self.connect(self, SIGNAL("strResultView"), self.strResultView)

    def qwidgetResult(self, qwidget):
        self.emit(SIGNAL("qwidgetResultView"), qwidget)

    def strResult(self, proc):
        self.emit(SIGNAL("strResultView"), proc)

    def qwidgetResultView(self, proc):
        proc.inst.g_display()
        self.addDockWidgets(proc.inst, proc.name)
        proc.inst.updateWidget()

    def strResultView(self, proc):
        widget = TextEdit(proc)
        try:
            res = ''
            txt = proc.stream.get(0)
            res += txt
            while txt:
                txt = proc.stream.get(0)
                res += txt
        except Empty:
            pass
        if res and res != '':
            widget.emit(SIGNAL("puttext"), res)
            self.addDockWidgets(widget, proc.name)

    def addToolBars(self, action):
        """ Init Toolbar"""
        if not action:
            #Add separator
            self.toolBar.addSeparator()
        else:
            action.setText(action.text())
            self.toolBar.addAction(action)

    def addAction(self, name, text, func=None, iconName=None, iconText=None):
        self.action[name] = QtGui.QAction(self)
        self.action[name].setObjectName("action" + name)
        self.action[name].setText(text)
        if iconName:
            self.action[name].setIcon(QIcon(iconName))
            if iconText:
                self.action[name].setIconText(iconText)
        if func:
            self.connect(self.action[name], SIGNAL("triggered()"), func)

    def setupToolBar(self):
        for action in self.toolbarList:
            self.addToolBars(action)

    def createRootNodes(self):
        root = self.vfs.getnode('/')
        self.devicenode = deviceNode(root, str('Local devices'))
        self.logicalenode = logicalNode(root, str('Logical files'))
        self.modulesrootnode = ModulesRootNode(VFS.Get(), root)
        self.booknode = bookNode(root, str('Bookmarks'))

    def changeEvent(self, event):
        """ Search for a language change event

        This event have to call retranslateUi to change interface language on
        the fly.
        """
        if event.type() == QEvent.LanguageChange:
            self.retranslateUi(self)
            self.translation()
        else:
            QMainWindow.changeEvent(self, event)

    def translation(self):
        self.errorLoadingHelp = self.tr('Error while loading help')
        self.onlineHelp = self.tr(
            '<br>You can check on-line help at <a href=\"http://wiki.digital-forensic.org/\">http://wiki.digital-forensic.org</a>.'
        )
        self.notAnHelpFile = self.tr('Not an help file.') + self.onlineHelp
        self.noSuchHelpFile = self.tr(
            'Documentation path not found.') + self.onlineHelp
Example #21
0
class GdalTools:

    def __init__(self, iface):
        if not valid:
            return

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

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

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

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

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

        # The list of actions added to menus, so we can remove them when unloading the plugin
        self._menuActions = []

    def initGui(self):
        if not valid:
            return
        if int(self.QgisVersion) < 1:
            QMessageBox.warning(
                self.iface.getMainWindow(), "Gdal Tools",
                QCoreApplication.translate("GdalTools", "QGIS version detected: ") + unicode(self.QgisVersion) + ".xx\n"
                + QCoreApplication.translate("GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled."))
            return None

        from tools.GdalTools_utils import GdalConfig, LayerRegistry
        self.GdalVersionNum = GdalConfig.versionNum()
        LayerRegistry.setIface(self.iface)

        # find the Raster menu
        rasterMenu = None
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()

        rasterText = QCoreApplication.translate("QgisApp", "&Raster")

        for a in actions:
            if a.menu() is not None and a.menu().title() == rasterText:
                rasterMenu = a.menu()
                break

        if rasterMenu is None:
            # no Raster menu, create and insert it before the Help menu
            self.menu = QMenu(rasterText, self.iface.mainWindow())
            lastAction = actions[len(actions) - 1]
            menu_bar.insertMenu(lastAction, self.menu)
        else:
            self.menu = rasterMenu
            self._menuActions.append(self.menu.addSeparator())

        # projections menu (Warp (Reproject), Assign projection)
        self.projectionsMenu = QMenu(QCoreApplication.translate("GdalTools", "Projections"), self.iface.mainWindow())
        self.projectionsMenu.setObjectName("projectionsMenu")

        self.warp = QAction(QIcon(":/icons/warp.png"), QCoreApplication.translate("GdalTools", "Warp (Reproject)..."), self.iface.mainWindow())
        self.warp.setObjectName("warp")
        self.warp.setStatusTip(QCoreApplication.translate("GdalTools", "Warp an image into a new coordinate system"))
        QObject.connect(self.warp, SIGNAL("triggered()"), self.doWarp)

        self.projection = QAction(QIcon(":icons/projection-add.png"), QCoreApplication.translate("GdalTools", "Assign Projection..."), self.iface.mainWindow())
        self.projection.setObjectName("projection")
        self.projection.setStatusTip(QCoreApplication.translate("GdalTools", "Add projection info to the raster"))
        QObject.connect(self.projection, SIGNAL("triggered()"), self.doProjection)

        self.extractProj = QAction(QIcon(":icons/projection-export.png"), QCoreApplication.translate("GdalTools", "Extract Projection..."), self.iface.mainWindow())
        self.extractProj.setObjectName("extractProj")
        self.extractProj.setStatusTip(QCoreApplication.translate("GdalTools", "Extract projection information from raster(s)"))
        QObject.connect(self.extractProj, SIGNAL("triggered()"), self.doExtractProj)

        self.projectionsMenu.addActions([self.warp, self.projection, self.extractProj])

        # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB)
        self.conversionMenu = QMenu(QCoreApplication.translate("GdalTools", "Conversion"), self.iface.mainWindow())
        self.conversionMenu.setObjectName("conversionMenu")

        if self.GdalVersionNum >= 1300:
            self.rasterize = QAction(QIcon(":/icons/rasterize.png"), QCoreApplication.translate("GdalTools", "Rasterize (Vector to Raster)..."), self.iface.mainWindow())
            self.rasterize.setObjectName("rasterize")
            self.rasterize.setStatusTip(QCoreApplication.translate("GdalTools", "Burns vector geometries into a raster"))
            QObject.connect(self.rasterize, SIGNAL("triggered()"), self.doRasterize)
            self.conversionMenu.addAction(self.rasterize)

        if self.GdalVersionNum >= 1600:
            self.polygonize = QAction(QIcon(":/icons/polygonize.png"), QCoreApplication.translate("GdalTools", "Polygonize (Raster to Vector)..."), self.iface.mainWindow())
            self.polygonize.setObjectName("polygonize")
            self.polygonize.setStatusTip(QCoreApplication.translate("GdalTools", "Produces a polygon feature layer from a raster"))
            QObject.connect(self.polygonize, SIGNAL("triggered()"), self.doPolygonize)
            self.conversionMenu.addAction(self.polygonize)

        self.translate = QAction(QIcon(":/icons/translate.png"), QCoreApplication.translate("GdalTools", "Translate (Convert Format)..."), self.iface.mainWindow())
        self.translate.setObjectName("translate")
        self.translate.setStatusTip(QCoreApplication.translate("GdalTools", "Converts raster data between different formats"))
        QObject.connect(self.translate, SIGNAL("triggered()"), self.doTranslate)

        self.paletted = QAction(QIcon(":icons/24-to-8-bits.png"), QCoreApplication.translate("GdalTools", "RGB to PCT..."), self.iface.mainWindow())
        self.paletted.setObjectName("paletted")
        self.paletted.setStatusTip(QCoreApplication.translate("GdalTools", "Convert a 24bit RGB image to 8bit paletted"))
        QObject.connect(self.paletted, SIGNAL("triggered()"), self.doPaletted)

        self.rgb = QAction(QIcon(":icons/8-to-24-bits.png"), QCoreApplication.translate("GdalTools", "PCT to RGB..."), self.iface.mainWindow())
        self.rgb.setObjectName("rgb")
        self.rgb.setStatusTip(QCoreApplication.translate("GdalTools", "Convert an 8bit paletted image to 24bit RGB"))
        QObject.connect(self.rgb, SIGNAL("triggered()"), self.doRGB)

        self.conversionMenu.addActions([self.translate, self.paletted, self.rgb])

        # extraction menu (Clipper, Contour)
        self.extractionMenu = QMenu(QCoreApplication.translate("GdalTools", "Extraction"), self.iface.mainWindow())
        self.extractionMenu.setObjectName("extractionMenu")

        if self.GdalVersionNum >= 1600:
            self.contour = QAction(QIcon(":/icons/contour.png"), QCoreApplication.translate("GdalTools", "Contour..."), self.iface.mainWindow())
            self.contour.setObjectName("contour")
            self.contour.setStatusTip(QCoreApplication.translate("GdalTools", "Builds vector contour lines from a DEM"))
            QObject.connect(self.contour, SIGNAL("triggered()"), self.doContour)
            self.extractionMenu.addAction(self.contour)

        self.clipper = QAction(QIcon(":icons/raster-clip.png"), QCoreApplication.translate("GdalTools", "Clipper..."), self.iface.mainWindow())
        self.clipper.setObjectName("clipper")
        #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") )
        QObject.connect(self.clipper, SIGNAL("triggered()"), self.doClipper)

        self.extractionMenu.addActions([self.clipper])

        # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve)
        self.analysisMenu = QMenu(QCoreApplication.translate("GdalTools", "Analysis"), self.iface.mainWindow())
        self.analysisMenu.setObjectName("analysisMenu")

        if self.GdalVersionNum >= 1600:
            self.sieve = QAction(QIcon(":/icons/sieve.png"), QCoreApplication.translate("GdalTools", "Sieve..."), self.iface.mainWindow())
            self.sieve.setObjectName("sieve")
            self.sieve.setStatusTip(QCoreApplication.translate("GdalTools", "Removes small raster polygons"))
            QObject.connect(self.sieve, SIGNAL("triggered()"), self.doSieve)
            self.analysisMenu.addAction(self.sieve)

        if self.GdalVersionNum >= 1500:
            self.nearBlack = QAction(QIcon(":/icons/nearblack.png"), QCoreApplication.translate("GdalTools", "Near Black..."), self.iface.mainWindow())
            self.nearBlack.setObjectName("nearBlack")
            self.nearBlack.setStatusTip(QCoreApplication.translate("GdalTools", "Convert nearly black/white borders to exact value"))
            QObject.connect(self.nearBlack, SIGNAL("triggered()"), self.doNearBlack)
            self.analysisMenu.addAction(self.nearBlack)

        if self.GdalVersionNum >= 1700:
            self.fillNodata = QAction(QIcon(":/icons/fillnodata.png"), QCoreApplication.translate("GdalTools", "Fill nodata..."), self.iface.mainWindow())
            self.fillNodata.setObjectName("fillNodata")
            self.fillNodata.setStatusTip(QCoreApplication.translate("GdalTools", "Fill raster regions by interpolation from edges"))
            QObject.connect(self.fillNodata, SIGNAL("triggered()"), self.doFillNodata)
            self.analysisMenu.addAction(self.fillNodata)

        if self.GdalVersionNum >= 1600:
            self.proximity = QAction(QIcon(":/icons/proximity.png"), QCoreApplication.translate("GdalTools", "Proximity (Raster Distance)..."), self.iface.mainWindow())
            self.proximity.setObjectName("proximity")
            self.proximity.setStatusTip(QCoreApplication.translate("GdalTools", "Produces a raster proximity map"))
            QObject.connect(self.proximity, SIGNAL("triggered()"), self.doProximity)
            self.analysisMenu.addAction(self.proximity)

        if self.GdalVersionNum >= 1500:
            self.grid = QAction(QIcon(":/icons/grid.png"), QCoreApplication.translate("GdalTools", "Grid (Interpolation)..."), self.iface.mainWindow())
            self.grid.setObjectName("grid")
            self.grid.setStatusTip(QCoreApplication.translate("GdalTools", "Create raster from the scattered data"))
            QObject.connect(self.grid, SIGNAL("triggered()"), self.doGrid)
            self.analysisMenu.addAction(self.grid)

        if self.GdalVersionNum >= 1700:
            self.dem = QAction(QIcon(":icons/dem.png"), QCoreApplication.translate("GdalTools", "DEM (Terrain Models)..."), self.iface.mainWindow())
            self.dem.setObjectName("dem")
            self.dem.setStatusTip(QCoreApplication.translate("GdalTools", "Tool to analyze and visualize DEMs"))
            QObject.connect(self.dem, SIGNAL("triggered()"), self.doDEM)
            self.analysisMenu.addAction(self.dem)

        #self.analysisMenu.addActions( [  ] )

        # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog))
        self.miscellaneousMenu = QMenu(QCoreApplication.translate("GdalTools", "Miscellaneous"), self.iface.mainWindow())
        self.miscellaneousMenu.setObjectName("miscellaneousMenu")

        if self.GdalVersionNum >= 1600:
            self.buildVRT = QAction(QIcon(":/icons/vrt.png"), QCoreApplication.translate("GdalTools", "Build Virtual Raster (Catalog)..."), self.iface.mainWindow())
            self.buildVRT.setObjectName("buildVRT")
            self.buildVRT.setStatusTip(QCoreApplication.translate("GdalTools", "Builds a VRT from a list of datasets"))
            QObject.connect(self.buildVRT, SIGNAL("triggered()"), self.doBuildVRT)
            self.miscellaneousMenu.addAction(self.buildVRT)

        self.merge = QAction(QIcon(":/icons/merge.png"), QCoreApplication.translate("GdalTools", "Merge..."), self.iface.mainWindow())
        self.merge.setObjectName("merge")
        self.merge.setStatusTip(QCoreApplication.translate("GdalTools", "Build a quick mosaic from a set of images"))
        QObject.connect(self.merge, SIGNAL("triggered()"), self.doMerge)

        self.info = QAction(QIcon(":/icons/raster-info.png"), QCoreApplication.translate("GdalTools", "Information..."), self.iface.mainWindow())
        self.info.setObjectName("info")
        self.info.setStatusTip(QCoreApplication.translate("GdalTools", "Lists information about raster dataset"))
        QObject.connect(self.info, SIGNAL("triggered()"), self.doInfo)

        self.overview = QAction(QIcon(":icons/raster-overview.png"), QCoreApplication.translate("GdalTools", "Build Overviews (Pyramids)..."), self.iface.mainWindow())
        self.overview.setObjectName("overview")
        self.overview.setStatusTip(QCoreApplication.translate("GdalTools", "Builds or rebuilds overview images"))
        QObject.connect(self.overview, SIGNAL("triggered()"), self.doOverview)

        self.tileindex = QAction(QIcon(":icons/tiles.png"), QCoreApplication.translate("GdalTools", "Tile Index..."), self.iface.mainWindow())
        self.tileindex.setObjectName("tileindex")
        self.tileindex.setStatusTip(QCoreApplication.translate("GdalTools", "Build a shapefile as a raster tileindex"))
        QObject.connect(self.tileindex, SIGNAL("triggered()"), self.doTileIndex)

        self.miscellaneousMenu.addActions([self.merge, self.info, self.overview, self.tileindex])

        self._menuActions.append(self.menu.addMenu(self.projectionsMenu))
        self._menuActions.append(self.menu.addMenu(self.conversionMenu))
        self._menuActions.append(self.menu.addMenu(self.extractionMenu))

        if not self.analysisMenu.isEmpty():
            self._menuActions.append(self.menu.addMenu(self.analysisMenu))

        self._menuActions.append(self.menu.addMenu(self.miscellaneousMenu))

        self.settings = QAction(QCoreApplication.translate("GdalTools", "GdalTools Settings..."), self.iface.mainWindow())
        self.settings.setObjectName("settings")
        self.settings.setStatusTip(QCoreApplication.translate("GdalTools", "Various settings for Gdal Tools"))
        QObject.connect(self.settings, SIGNAL("triggered()"), self.doSettings)
        self.menu.addAction(self.settings)
        self._menuActions.append(self.settings)

    def unload(self):
        if not valid:
            return
        for a in self._menuActions:
            self.menu.removeAction(a)

    def doBuildVRT(self):
        from tools.doBuildVRT import GdalToolsDialog as BuildVRT
        d = BuildVRT(self.iface)
        self.runToolDialog(d)

    def doContour(self):
        from tools.doContour import GdalToolsDialog as Contour
        d = Contour(self.iface)
        self.runToolDialog(d)

    def doRasterize(self):
        from tools.doRasterize import GdalToolsDialog as Rasterize
        d = Rasterize(self.iface)
        self.runToolDialog(d)

    def doPolygonize(self):
        from tools.doPolygonize import GdalToolsDialog as Polygonize
        d = Polygonize(self.iface)
        self.runToolDialog(d)

    def doMerge(self):
        from tools.doMerge import GdalToolsDialog as Merge
        d = Merge(self.iface)
        self.runToolDialog(d)

    def doSieve(self):
        from tools.doSieve import GdalToolsDialog as Sieve
        d = Sieve(self.iface)
        self.runToolDialog(d)

    def doProximity(self):
        from tools.doProximity import GdalToolsDialog as Proximity
        d = Proximity(self.iface)
        self.runToolDialog(d)

    def doNearBlack(self):
        from tools.doNearBlack import GdalToolsDialog as NearBlack
        d = NearBlack(self.iface)
        self.runToolDialog(d)

    def doFillNodata(self):
        from tools.doFillNodata import GdalToolsDialog as FillNodata
        d = FillNodata(self.iface)
        self.runToolDialog(d)

    def doWarp(self):
        from tools.doWarp import GdalToolsDialog as Warp
        d = Warp(self.iface)
        self.runToolDialog(d)

    def doGrid(self):
        from tools.doGrid import GdalToolsDialog as Grid
        d = Grid(self.iface)
        self.runToolDialog(d)

    def doTranslate(self):
        from tools.doTranslate import GdalToolsDialog as Translate
        d = Translate(self.iface)
        self.runToolDialog(d)

    def doInfo(self):
        from tools.doInfo import GdalToolsDialog as Info
        d = Info(self.iface)
        self.runToolDialog(d)

    def doProjection(self):
        from tools.doProjection import GdalToolsDialog as Projection
        d = Projection(self.iface)
        self.runToolDialog(d)

    def doOverview(self):
        from tools.doOverview import GdalToolsDialog as Overview
        d = Overview(self.iface)
        self.runToolDialog(d)

    def doClipper(self):
        from tools.doClipper import GdalToolsDialog as Clipper
        d = Clipper(self.iface)
        self.runToolDialog(d)

    def doPaletted(self):
        from tools.doRgbPct import GdalToolsDialog as RgbPct
        d = RgbPct(self.iface)
        self.runToolDialog(d)

    def doRGB(self):
        from tools.doPctRgb import GdalToolsDialog as PctRgb
        d = PctRgb(self.iface)
        self.runToolDialog(d)

    def doTileIndex(self):
        from tools.doTileIndex import GdalToolsDialog as TileIndex
        d = TileIndex(self.iface)
        self.runToolDialog(d)

    def doExtractProj(self):
        from tools.doExtractProj import GdalToolsDialog as ExtractProj
        d = ExtractProj(self.iface)
        d.exec_()

    def doDEM(self):
        from tools.doDEM import GdalToolsDialog as DEM
        d = DEM(self.iface)
        self.runToolDialog(d)

    def runToolDialog(self, dlg):
        dlg.show_()
        dlg.exec_()
        del dlg

    def doSettings(self):
        from tools.doSettings import GdalToolsSettingsDialog as Settings
        d = Settings(self.iface)
        d.exec_()
Example #22
0
class VolumeEditorWidget(QWidget):
    def __init__( self, parent=None, editor=None ):
        super(VolumeEditorWidget, self).__init__(parent=parent)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setFocusPolicy(Qt.StrongFocus)
        
        self.editor = None
        if editor!=None:
            self.init(editor)

        self._viewMenu = None

        self.allZoomToFit = QAction(QIcon(":/icons/icons/view-fullscreen.png"), "Zoom to &Fit", self)
        self.allZoomToFit.triggered.connect(self._fitToScreen)

        self.allToggleHUD = QAction(QIcon(), "Show &HUDs", self)
        self.allToggleHUD.setCheckable(True)
        self.allToggleHUD.setChecked(True)
        self.allToggleHUD.toggled.connect(self._toggleHUDs)

        self.allCenter = QAction(QIcon(), "&Center views", self)
        self.allCenter.triggered.connect(self._centerAllImages)

        self.selectedCenter = QAction(QIcon(), "C&enter view", self)
        self.selectedCenter.triggered.connect(self._centerImage)

        self.selectedZoomToFit = QAction(QIcon(":/icons/icons/view-fullscreen.png"), "Zoom to Fit", self)
        self.selectedZoomToFit.triggered.connect(self._fitImage)

        self.selectedZoomToOriginal = QAction(QIcon(), "Reset Zoom", self)
        self.selectedZoomToOriginal.triggered.connect(self._restoreImageToOriginalSize)

        self.rubberBandZoom = QAction(QIcon(), "Rubberband Zoom", self)
        self.rubberBandZoom.triggered.connect(self._rubberBandZoom)

        self.toggleSelectedHUD = QAction(QIcon(), "Show HUD", self)
        self.toggleSelectedHUD.setCheckable(True)
        self.toggleSelectedHUD.setChecked(True)
        self.toggleSelectedHUD.toggled.connect(self._toggleSelectedHud)


    def _setupVolumeExtent( self ):
        '''Setup min/max values of position/coordinate control elements.

        Position/coordinate information is read from the volumeEditor's positionModel.

        '''
        maxTime = self.editor.posModel.shape5D[0] - 1
        self.quadview.statusBar.timeLabel.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setRange(0,maxTime)
        self.quadview.statusBar.timeSpinBox.setSuffix("/{}".format( maxTime ) )
        
        for i in range(3):
            self.editor.imageViews[i].hud.setMaximum(self.editor.posModel.volumeExtent(i)-1)
    
    def init(self, volumina):
        self.editor = volumina
        
        self.hudsShown = [True]*3
        
        def onViewFocused():
            axis = self.editor._lastImageViewFocus;
            self.toggleSelectedHUD.setChecked( self.editor.imageViews[axis]._hud.isVisible() )
        self.editor.newImageView2DFocus.connect(onViewFocused)

        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        
        self.setLayout(self.layout)
        
        # setup quadview
        axisLabels = ["X", "Y", "Z"]
        axisColors = [QColor("#dc143c"), QColor("green"), QColor("blue")]
        for i, v in enumerate(self.editor.imageViews):
            v.hud = ImageView2DHud(v)
            #connect interpreter
            v.hud.createImageView2DHud(axisLabels[i], 0, axisColors[i], QColor("white"))
            v.hud.sliceSelector.valueChanged.connect(partial(self.editor.navCtrl.changeSliceAbsolute, axis=i))

        self.quadview = QuadView(self, self.editor.imageViews[2],
                                 self.editor.imageViews[0], self.editor.imageViews[1],
                                 self.editor.view3d)
        self.quadview.installEventFilter(self)
        self.quadViewStatusBar = QuadStatusBar()
        self.quadViewStatusBar.createQuadViewStatusBar(
            QColor("#dc143c"),
            QColor("white"),
            QColor("green"),
            QColor("white"),
            QColor("blue"),
            QColor("white"))
        self.quadview.addStatusBar(self.quadViewStatusBar)
        self.layout.addWidget(self.quadview)

        ## Why do we have to prevent TimerEvents reaching the SpinBoxes?
        #
        # Sometimes clicking a SpinBox once caused the value to increase by
        # two. This is why:
        #
        # When a MouseClicked event is received by the SpinBox it fires a timerevent to control
        # the repeated increase of the value as long as the mouse button is pressed. The timer
        # is killed when it receives a MouseRelease event. If a slot connected to the valueChanged
        # signal of the SpinBox takes to long to process the signal the mouse release
        # and timer events get queued up and sometimes the timer event reaches the widget before
        # the mouse release event. That's why it increases the value by another step. To prevent
        # this we are blocking the timer events at the cost of no autorepeat anymore.
        #
        # See also:
        # http://lists.trolltech.com/qt-interest/2002-04/thread00137-0.html
        # http://www.qtcentre.org/threads/43078-QSpinBox-Timer-Issue
        # http://qt.gitorious.org/qt/qt/blobs/4.8/src/gui/widgets/qabstractspinbox.cpp#line1195
        self.quadview.statusBar.timeSpinBox.installEventFilter( _timerEater )

        def setTime(t):
            if t == self.editor.posModel.time:
                return
            self.editor.posModel.time = t
        self.quadview.statusBar.timeSpinBox.valueChanged.connect(setTime)
        def getTime(newT):
            self.quadview.statusBar.timeSpinBox.setValue(newT)
        self.editor.posModel.timeChanged.connect(getTime) 

        def toggleSliceIntersection(state):
            self.editor.navCtrl.indicateSliceIntersection = (state == Qt.Checked)
        self.quadview.statusBar.positionCheckBox.stateChanged.connect(toggleSliceIntersection)

        self.editor.posModel.cursorPositionChanged.connect(self._updateInfoLabels)

        def onShapeChanged():
            singletonDims = filter( lambda (i,dim): dim == 1, enumerate(self.editor.posModel.shape5D[1:4]) )
            if len(singletonDims) == 1:
                # Maximize the slicing view for this axis
                axis = singletonDims[0][0]
                self.quadview.ensureMaximized(axis)
                self.hudsShown[axis] = self.editor.imageViews[axis].hudVisible()
                self.editor.imageViews[axis].setHudVisible(False)
                self.quadViewStatusBar.showXYCoordinates()
                
                self.quadview.statusBar.positionCheckBox.setVisible(False)
            else:
                self.quadViewStatusBar.showXYZCoordinates()
                for i in range(3):
                    self.editor.imageViews[i].setHudVisible(self.hudsShown[i])
                self.quadview.statusBar.positionCheckBox.setVisible(True)
        
            self._setupVolumeExtent()

        self.editor.shapeChanged.connect(onShapeChanged)
        
        self.updateGeometry()
        self.update()
        self.quadview.update()

        # shortcuts
        self._initShortcuts()

    def _toggleDebugPatches(self,show):
        self.editor.showDebugPatches = show

    def _fitToScreen(self):
        shape = self.editor.posModel.shape
        for i, v in enumerate(self.editor.imageViews):
            s = list(copy.copy(shape))
            del s[i]
            v.changeViewPort(v.scene().data2scene.mapRect(QRectF(0,0,*s)))  
            
    def _fitImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].fitImage()
            
    def _restoreImageToOriginalSize(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()
                
    def _rubberBandZoom(self):
        if self.editor._lastImageViewFocus is not None:
            if not self.editor.imageViews[self.editor._lastImageViewFocus]._isRubberBandZoom:
                self.editor.imageViews[self.editor._lastImageViewFocus]._isRubberBandZoom = True
                self.editor.imageViews[self.editor._lastImageViewFocus]._cursorBackup = self.editor.imageViews[self.editor._lastImageViewFocus].cursor()
                self.editor.imageViews[self.editor._lastImageViewFocus].setCursor(Qt.CrossCursor)
            else:
                self.editor.imageViews[self.editor._lastImageViewFocus]._isRubberBandZoom = False
                self.editor.imageViews[self.editor._lastImageViewFocus].setCursor(self.editor.imageViews[self.editor._lastImageViewFocus]._cursorBackup)
            
    
    def _toggleHUDs(self, checked):
        for v in self.editor.imageViews:
            v.setHudVisible(checked)
            
    def _toggleSelectedHud(self, checked):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].setHudVisible(checked)
            
    def _centerAllImages(self):
        for v in self.editor.imageViews:
            v.centerImage()
            
    def _centerImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].centerImage()

    def _shortcutHelper(self, keySequence, group, description, parent, function, context = None, enabled = None, widget=None):
        shortcut = QShortcut(QKeySequence(keySequence), parent, member=function, ambiguousMember=function)
        if context != None:
            shortcut.setContext(context)
        if enabled != None:
            shortcut.setEnabled(True)

        ShortcutManager().register( group, description, shortcut, widget )
        return shortcut, group, description

    def _initShortcuts(self):
        self.shortcuts = []

        # TODO: Fix this dependency on ImageView/HUD internals
        self.shortcuts.append(self._shortcutHelper("x", "Navigation", "Minimize/Maximize x-Window", self, self.quadview.switchXMinMax, Qt.ApplicationShortcut, True, widget=self.editor.imageViews[0].hud.buttons['maximize']))
        self.shortcuts.append(self._shortcutHelper("y", "Navigation", "Minimize/Maximize y-Window", self, self.quadview.switchYMinMax, Qt.ApplicationShortcut, True, widget=self.editor.imageViews[1].hud.buttons['maximize']))
        self.shortcuts.append(self._shortcutHelper("z", "Navigation", "Minimize/Maximize z-Window", self, self.quadview.switchZMinMax, Qt.ApplicationShortcut, True, widget=self.editor.imageViews[2].hud.buttons['maximize']))
        
        
        for i, v in enumerate(self.editor.imageViews):
            self.shortcuts.append(self._shortcutHelper("+", "Navigation", "Zoom in", v,  v.zoomIn, Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("-", "Navigation", "Zoom out", v, v.zoomOut, Qt.WidgetShortcut))
            
            self.shortcuts.append(self._shortcutHelper("c", "Navigation", "Center image", v,  v.centerImage, Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("h", "Navigation", "Toggle hud", v,  v.toggleHud, Qt.WidgetShortcut))
            
            # FIXME: The nextChannel/previousChannel functions don't work right now.
            #self.shortcuts.append(self._shortcutHelper("q", "Navigation", "Switch to next channel",     v, self.editor.nextChannel,     Qt.WidgetShortcut))
            #self.shortcuts.append(self._shortcutHelper("a", "Navigation", "Switch to previous channel", v, self.editor.previousChannel, Qt.WidgetShortcut))
            
            def sliceDelta(axis, delta):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] += delta
                newPos[axis] = max(0, newPos[axis]) 
                newPos[axis] = min(self.editor.posModel.shape[axis]-1, newPos[axis]) 
                self.editor.posModel.slicingPos = newPos

            def jumpToFirstSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = 0
                self.editor.posModel.slicingPos = newPos
                
            def jumpToLastSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = self.editor.posModel.shape[axis]-1
                self.editor.posModel.slicingPos = newPos
            
            # TODO: Fix this dependency on ImageView/HUD internals
            self.shortcuts.append(self._shortcutHelper("Ctrl+Up",   "Navigation", "Slice up",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut, widget=v.hud.buttons['slice'].upLabel))
            self.shortcuts.append(self._shortcutHelper("Ctrl+Down", "Navigation", "Slice down", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut, widget=v.hud.buttons['slice'].downLabel))
            
#            self.shortcuts.append(self._shortcutHelper("p", "Navigation", "Slice up (alternate shortcut)",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut))
#            self.shortcuts.append(self._shortcutHelper("o", "Navigation", "Slice down (alternate shortcut)", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut))
            
            self.shortcuts.append(self._shortcutHelper("Ctrl+Shift+Up",   "Navigation", "10 slices up",   v, partial(sliceDelta, i, 10),  Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("Ctrl+Shift+Down", "Navigation", "10 slices down", v, partial(sliceDelta, i, -10), Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("Shift+Up",   "Navigation", "Jump to first slice",   v, partial(jumpToFirstSlice, i),  Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("Shift+Down", "Navigation", "Jump to last slice", v, partial(jumpToLastSlice, i), Qt.WidgetShortcut))

            

    def _updateInfoLabels(self, pos):
        self.quadViewStatusBar.setMouseCoords(*pos)

    def eventFilter(self, watched, event):
        # If the user performs a ctrl+scroll on the splitter itself,
        # scroll all views.
        if event.type() == QEvent.Wheel and (event.modifiers() == Qt.ControlModifier):
            for view in self.editor.imageViews:
                if event.delta() > 0:
                    view.zoomIn()
                else:
                    view.zoomOut()
            return True
        return False
    
    def getViewMenu(self, debug_mode=False):
        """
        Return a QMenu with a set of actions for our editor.
        """
        if self._viewMenu is None:
            self._initViewMenu()
        for action in self._debugActions:
            action.setEnabled( debug_mode )
            action.setVisible( debug_mode )
        return self._viewMenu

    def _initViewMenu(self):
        self._viewMenu = QMenu("View", parent=self)
        self._viewMenu.setObjectName( "view_menu" )
        self._debugActions = []
        
        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionFitToScreen = self._viewMenu.addAction( "&Zoom to &fit" )
        self._viewMenu.actionFitToScreen.triggered.connect(self._fitToScreen)

        def toggleHud():
            hide = not self.editor.imageViews[0]._hud.isVisible()
            for v in self.editor.imageViews:
                v.setHudVisible(hide)
        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionToggleAllHuds = self._viewMenu.addAction( "Toggle huds" )
        self._viewMenu.actionToggleAllHuds.triggered.connect(toggleHud)

        def resetAllAxes():
            for s in self.editor.imageScenes:
                s.resetAxes()
        self._viewMenu.addAction( "Reset all axes" ).triggered.connect(resetAllAxes)

        def centerAllImages():
            for v in self.editor.imageViews:
                v.centerImage()
        self._viewMenu.addAction( "Center images" ).triggered.connect(centerAllImages)

        def toggleDebugPatches(show):
            self.editor.showDebugPatches = show
        actionShowTiling = self._viewMenu.addAction( "Show Tiling" )
        actionShowTiling.setCheckable(True)
        actionShowTiling.toggled.connect(toggleDebugPatches)
        qsd = QShortcut( QKeySequence("Ctrl+D"), self, member=actionShowTiling.toggle, context=Qt.WidgetShortcut )
        ShortcutManager().register("Navigation","Show tiling",qsd)
        self._debugActions.append( actionShowTiling )

        def setCacheSize( cache_size ):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget( QLabel("Cached Slices Per View:") )

            cache_size = [self.editor.cacheSize]
            def parseCacheSize( strSize ):
                # TODO: Use a QValidator to make sure the user always gives a number
                try:
                    cache_size[0] = int(strSize)
                except:
                    pass

            edit = QLineEdit( str(cache_size[0]), parent=dlg )
            edit.textChanged.connect( parseCacheSize )
            layout.addWidget( edit )
            okButton = QPushButton( "OK", parent=dlg )
            okButton.clicked.connect( dlg.accept )
            layout.addWidget( okButton )
            dlg.setLayout( layout )
            dlg.setModal(True)
            dlg.exec_()
            self.editor.cacheSize = cache_size[0]
        self._viewMenu.addAction( "Set layer cache size" ).triggered.connect(setCacheSize)

        def enablePrefetching( enable ):
            for scene in self.editor.imageScenes:
                scene.setPrefetchingEnabled( enable )
        actionUsePrefetching = self._viewMenu.addAction( "Use prefetching" )
        actionUsePrefetching.setCheckable(True)
        actionUsePrefetching.toggled.connect(enablePrefetching)

        def blockGuiForRendering():
            for v in self.editor.imageViews:
                v.scene().joinRenderingAllTiles()
                v.repaint()
            QApplication.processEvents()
        actionBlockGui = self._viewMenu.addAction( "Block for rendering" )
        actionBlockGui.triggered.connect(blockGuiForRendering)
        qsw = QShortcut( QKeySequence("Ctrl+B"), self, member=actionBlockGui.trigger, context=Qt.WidgetShortcut )
        ShortcutManager().register( "Navigation", "Block gui for rendering", qsw )
        self._debugActions.append( actionBlockGui )

        # ------ Separator ------
        self._viewMenu.addAction("").setSeparator(True)

        # Text only
        actionOnlyForSelectedView = self._viewMenu.addAction( "Only for selected view" )
        actionOnlyForSelectedView.setIconVisibleInMenu(True)
        font = actionOnlyForSelectedView.font()
        font.setItalic(True)
        font.setBold(True)
        actionOnlyForSelectedView.setFont(font)
        def setCurrentAxisIcon():
            """Update the icon that shows the currently selected axis."""
            actionOnlyForSelectedView.setIcon(QIcon(self.editor.imageViews[self.editor._lastImageViewFocus]._hud.axisLabel.pixmap()))
        self.editor.newImageView2DFocus.connect(setCurrentAxisIcon)
        setCurrentAxisIcon()
        
        actionFitImage = self._viewMenu.addAction( "Fit image" )
        actionFitImage.triggered.connect(self._fitImage)
        qsa = QShortcut( QKeySequence("K"), self, member=actionFitImage.trigger, context=Qt.WidgetShortcut )
        ShortcutManager().register( "Navigation", "Fit image on screen", qsa)

        def toggleSelectedHud():
            self.editor.imageViews[self.editor._lastImageViewFocus].toggleHud()
        actionToggleSelectedHud = self._viewMenu.addAction( "Toggle hud" )
        actionToggleSelectedHud.triggered.connect(toggleSelectedHud)

        def resetAxes():
            self.editor.imageScenes[self.editor._lastImageViewFocus].resetAxes()
        self._viewMenu.addAction( "Reset axes" ).triggered.connect(resetAxes)

        def centerImage():
            self.editor.imageViews[self.editor._lastImageViewFocus].centerImage()
        actionCenterImage = self._viewMenu.addAction( "Center image" )
        actionCenterImage.triggered.connect(centerImage)
        qsc = QShortcut( QKeySequence("C"), self, member=actionCenterImage.trigger, context=Qt.WidgetShortcut )
        ShortcutManager().register("Navigation","Center image",qsc)

        def restoreImageToOriginalSize():
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()
        actionResetZoom = self._viewMenu.addAction( "Reset zoom" )
        actionResetZoom.triggered.connect(restoreImageToOriginalSize)
        qsw = QShortcut( QKeySequence("W"), self, member=actionResetZoom.trigger, context=Qt.WidgetShortcut )
        ShortcutManager().register("Navigation","Reset zoom",qsw)        

        def updateHudActions():
            dataShape = self.editor.dataShape
            # if the image is 2D, do not show the HUD action (issue #190)
            is2D = numpy.sum(numpy.asarray(dataShape[1:4]) == 1) == 1
            actionToggleSelectedHud.setVisible(not is2D)
            self._viewMenu.actionToggleAllHuds.setVisible(not is2D)
        self.editor.shapeChanged.connect( updateHudActions )
Example #23
0
class VolumeEditorWidget(QWidget):
    def __init__( self, parent=None, editor=None ):
        super(VolumeEditorWidget, self).__init__(parent=parent)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setFocusPolicy(Qt.StrongFocus)
        
        self.editor = None
        if editor!=None:
            self.init(editor)

        self._viewMenu = None

        self.allZoomToFit = QAction(QIcon(":/icons/icons/view-fullscreen.png"), "Zoom to &Fit", self)
        self.allZoomToFit.triggered.connect(self._fitToScreen)

        self.allToggleHUD = QAction(QIcon(), "Show &HUDs", self)
        self.allToggleHUD.setCheckable(True)
        self.allToggleHUD.setChecked(True)
        self.allToggleHUD.toggled.connect(self._toggleHUDs)

        self.allCenter = QAction(QIcon(), "&Center views", self)
        self.allCenter.triggered.connect(self._centerAllImages)

        self.selectedCenter = QAction(QIcon(), "C&enter view", self)
        self.selectedCenter.triggered.connect(self._centerImage)

        self.selectedZoomToFit = QAction(QIcon(":/icons/icons/view-fullscreen.png"), "Zoom to Fit", self)
        self.selectedZoomToFit.triggered.connect(self._fitImage)

        self.selectedZoomToOriginal = QAction(QIcon(), "Reset Zoom", self)
        self.selectedZoomToOriginal.triggered.connect(self._restoreImageToOriginalSize)

        self.rubberBandZoom = QAction(QIcon(), "Rubberband Zoom", self)
        self.rubberBandZoom.triggered.connect(self._rubberBandZoom)

        self.toggleSelectedHUD = QAction(QIcon(), "Show HUD", self)
        self.toggleSelectedHUD.setCheckable(True)
        self.toggleSelectedHUD.setChecked(True)
        self.toggleSelectedHUD.toggled.connect(self._toggleSelectedHud)


    def _setupVolumeExtent( self ):
        '''Setup min/max values of position/coordinate control elements.

        Position/coordinate information is read from the volumeEditor's positionModel.

        '''
        maxTime = self.editor.posModel.shape5D[0] - 1
        self.quadview.statusBar.timeLabel.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setRange(0,maxTime)
        self.quadview.statusBar.timeSpinBox.setSuffix("/{}".format( maxTime ) )
        self.quadview.statusBar.hideTimeSlider(maxTime == 0)

        cropMidPos = [(b+a)/2 for [a,b] in self.editor.cropModel._crop_extents]
        for i in range(3):
            self.editor.imageViews[i].hud.setMaximum(self.editor.posModel.volumeExtent(i)-1)
            self.editor.navCtrl.changeSliceAbsolute(cropMidPos[i],i)
        self.editor.navCtrl.changeTime(self.editor.cropModel._crop_times[0])


    def init(self, volumina):
        self.editor = volumina
        
        self.hudsShown = [True]*3
        
        def onViewFocused():
            axis = self.editor._lastImageViewFocus;
            self.toggleSelectedHUD.setChecked( self.editor.imageViews[axis]._hud.isVisible() )
        self.editor.newImageView2DFocus.connect(onViewFocused)

        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        
        self.setLayout(self.layout)
        
        # setup quadview
        axisLabels = ["X", "Y", "Z"]
        axisColors = [QColor("#dc143c"), QColor("green"), QColor("blue")]
        for i, v in enumerate(self.editor.imageViews):
            v.hud = ImageView2DHud(v)
            #connect interpreter
            v.hud.createImageView2DHud(axisLabels[i], 0, axisColors[i], QColor("white"))
            v.hud.sliceSelector.valueChanged.connect(partial(self.editor.navCtrl.changeSliceAbsolute, axis=i))

        self.quadview = QuadView(self, self.editor.imageViews[2],
                                 self.editor.imageViews[0], self.editor.imageViews[1],
                                 self.editor.view3d)
        self.quadview.installEventFilter(self)
        self.quadViewStatusBar = QuadStatusBar()
        self.quadViewStatusBar.createQuadViewStatusBar(
            QColor("#dc143c"),
            QColor("white"),
            QColor("green"),
            QColor("white"),
            QColor("blue"),
            QColor("white"))
        self.quadview.addStatusBar(self.quadViewStatusBar)
        self.layout.addWidget(self.quadview)
        
        # Here we subscribe to the dirtyChanged() signal from all slicing views, 
        #  and show the status bar "busy indicator" if any view is dirty.
        # Caveat: To avoid a flickering indicator for quick updates, we use a 
        #         timer that prevents the indicator from showing for a bit. 
        def updateDirtyStatus(fromTimer=False):
            # We only care about views that are both VISIBLE and DIRTY.
            dirties = map( lambda v: v.scene().dirty, self.editor.imageViews)
            visibilities = map( lambda v: v.isVisible(), self.editor.imageViews)
            visible_dirtiness = numpy.logical_and(visibilities, dirties)
            
            if not any(visible_dirtiness):
                # Not dirty: Hide immediately
                self.quadViewStatusBar.busyIndicator.setVisible(False)
            else:
                if fromTimer:
                    # The timer finished and we're still dirty:
                    # Time to show the busy indicator.
                    self.quadViewStatusBar.busyIndicator.setVisible(True)
                elif not self.quadViewStatusBar.busyIndicator.isVisible() and not self._dirtyTimer.isActive():
                    # We're dirty, but delay for a bit before showing the busy indicator.
                    self._dirtyTimer.start(750)

        self._dirtyTimer = QTimer()
        self._dirtyTimer.setSingleShot(True)
        self._dirtyTimer.timeout.connect( partial(updateDirtyStatus, fromTimer=True) )
        for i, view in enumerate(self.editor.imageViews):
            view.scene().dirtyChanged.connect( updateDirtyStatus )

        # If the user changes the position in the quad-view status bar (at the bottom),
        # Update the position of the whole editor.
        def setPositionFromQuadBar( x,y,z ):
            self.editor.posModel.slicingPos = (x,y,z)
            self.editor.posModel.cursorPos = (x,y,z)
            self.editor.navCtrl.panSlicingViews( (x,y,z), [0,1,2] )
        self.quadViewStatusBar.positionChanged.connect( setPositionFromQuadBar )

        ## Why do we have to prevent TimerEvents reaching the SpinBoxes?
        #
        # Sometimes clicking a SpinBox once caused the value to increase by
        # two. This is why:
        #
        # When a MouseClicked event is received by the SpinBox it fires a timerevent to control
        # the repeated increase of the value as long as the mouse button is pressed. The timer
        # is killed when it receives a MouseRelease event. If a slot connected to the valueChanged
        # signal of the SpinBox takes to long to process the signal the mouse release
        # and timer events get queued up and sometimes the timer event reaches the widget before
        # the mouse release event. That's why it increases the value by another step. To prevent
        # this we are blocking the timer events at the cost of no autorepeat anymore.
        #
        # See also:
        # http://lists.trolltech.com/qt-interest/2002-04/thread00137-0.html
        # http://www.qtcentre.org/threads/43078-QSpinBox-Timer-Issue
        # http://qt.gitorious.org/qt/qt/blobs/4.8/src/gui/widgets/qabstractspinbox.cpp#line1195
        self.quadview.statusBar.timeSpinBox.installEventFilter( _timerEater )

        def setTime(t):
            if t == self.editor.posModel.time:
                return
            self.editor.posModel.time = t
        self.quadview.statusBar.timeSpinBox.delayedValueChanged.connect(setTime)
        def setTimeSpinBox(newT):
            self.quadview.statusBar.timeSpinBox.setValue(newT)
        self.editor.posModel.timeChanged.connect(setTimeSpinBox)

        def toggleSliceIntersection(state):
            self.editor.navCtrl.indicateSliceIntersection = (state == Qt.Checked)
        self.quadview.statusBar.positionCheckBox.stateChanged.connect(toggleSliceIntersection)

        self.editor.posModel.cursorPositionChanged.connect(self._updateInfoLabels)

        def onShapeChanged():
            # By default, 3D HUD buttons are visible,
            #  but we'll turn them off below if the dataset is 2D.
            for axis in [0,1,2]:
                self.editor.imageViews[axis].hud.set3DButtonsVisible(True)

            singletonDims = filter( lambda (i,dim): dim == 1, enumerate(self.editor.posModel.shape5D[1:4]) )
            if len(singletonDims) == 1:
                # Maximize the slicing view for this axis
                axis = singletonDims[0][0]
                self.quadview.ensureMaximized(axis)
                self.hudsShown[axis] = self.editor.imageViews[axis].hudVisible()
                self.editor.imageViews[axis].hud.set3DButtonsVisible(False)
                self.quadViewStatusBar.showXYCoordinates()
                
                self.quadview.statusBar.positionCheckBox.setVisible(False)
            else:
                self.quadViewStatusBar.showXYZCoordinates()
                for i in range(3):
                    self.editor.imageViews[i].setHudVisible(self.hudsShown[i])
                self.quadview.statusBar.positionCheckBox.setVisible(True)

            if self.editor.cropModel._crop_extents[0][0]  == None or self.editor.cropModel.cropZero():
                self.quadViewStatusBar.updateShape5D(self.editor.posModel.shape5D)
            else:
                cropMin = (self.editor.posModel.time,self.editor.cropModel._crop_extents[0][0],self.editor.cropModel._crop_extents[1][0],self.editor.cropModel._crop_extents[2][0],0)
                self.quadViewStatusBar.updateShape5Dcropped(cropMin,self.editor.posModel.shape5D)

            self._setupVolumeExtent()

        self.editor.shapeChanged.connect(onShapeChanged)

        self.updateGeometry()
        self.update()
        self.quadview.update()
        if hasattr(self.editor.view3d, 'bUndock'):
            self.editor.view3d.bUndock.clicked.connect(partial(self.quadview.on_dock, self.quadview.dock2_ofSplitHorizontal2))

        # shortcuts
        self._initShortcuts()

    def _toggleDebugPatches(self,show):
        self.editor.showDebugPatches = show

    def _fitToScreen(self):
        shape = self.editor.posModel.shape
        for i, v in enumerate(self.editor.imageViews):
            s = list(copy.copy(shape))
            del s[i]
            v.changeViewPort(v.scene().data2scene.mapRect(QRectF(0,0,*s)))  
            
    def _fitImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].fitImage()
            
    def _restoreImageToOriginalSize(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()
                
    def _rubberBandZoom(self):
        if self.editor._lastImageViewFocus is not None:
            if not self.editor.imageViews[self.editor._lastImageViewFocus]._isRubberBandZoom:
                self.editor.imageViews[self.editor._lastImageViewFocus]._isRubberBandZoom = True
                self.editor.imageViews[self.editor._lastImageViewFocus]._cursorBackup = self.editor.imageViews[self.editor._lastImageViewFocus].cursor()
                self.editor.imageViews[self.editor._lastImageViewFocus].setCursor(Qt.CrossCursor)
            else:
                self.editor.imageViews[self.editor._lastImageViewFocus]._isRubberBandZoom = False
                self.editor.imageViews[self.editor._lastImageViewFocus].setCursor(self.editor.imageViews[self.editor._lastImageViewFocus]._cursorBackup)
            
    
    def _toggleHUDs(self, checked):
        for v in self.editor.imageViews:
            v.setHudVisible(checked)
            
    def _toggleSelectedHud(self, checked):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].setHudVisible(checked)
            
    def _centerAllImages(self):
        for v in self.editor.imageViews:
            v.centerImage()
            
    def _centerImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].centerImage()

    def _initShortcuts(self):
        # TODO: Fix this dependency on ImageView/HUD internals
        mgr = ShortcutManager()
        ActionInfo = ShortcutManager.ActionInfo
        mgr.register("x", ActionInfo( "Navigation", 
                                      "Minimize/Maximize x-Window", 
                                      "Minimize/Maximize x-Window", 
                                      self.quadview.switchXMinMax,
                                      self.editor.imageViews[0].hud.buttons['maximize'],
                                      self.editor.imageViews[0].hud.buttons['maximize'] ) )

        mgr.register("y", ActionInfo( "Navigation", 
                                      "Minimize/Maximize y-Window", 
                                      "Minimize/Maximize y-Window", 
                                      self.quadview.switchYMinMax,
                                      self.editor.imageViews[1].hud.buttons['maximize'],
                                      self.editor.imageViews[1].hud.buttons['maximize'] ) )

        mgr.register("z", ActionInfo( "Navigation", 
                                      "Minimize/Maximize z-Window", 
                                      "Minimize/Maximize z-Window", 
                                      self.quadview.switchZMinMax,
                                      self.editor.imageViews[2].hud.buttons['maximize'],
                                      self.editor.imageViews[2].hud.buttons['maximize'] ) )

        for i, v in enumerate(self.editor.imageViews):
            mgr.register("+", ActionInfo( "Navigation", 
                                          "Zoom in", 
                                          "Zoom in", 
                                          v.zoomIn,
                                          v,
                                          None) )
            mgr.register("-", ActionInfo( "Navigation", 
                                          "Zoom out", 
                                          "Zoom out", 
                                          v.zoomOut,
                                          v,
                                          None) )

            mgr.register("c", ActionInfo( "Navigation", 
                                          "Center image", 
                                          "Center image", 
                                          v.centerImage,
                                          v,
                                          None) )

            mgr.register("h", ActionInfo( "Navigation", 
                                          "Toggle hud", 
                                          "Toggle hud", 
                                          v.toggleHud,
                                          v,
                                          None) )

            # FIXME: The nextChannel/previousChannel functions don't work right now.
            #self._shortcutHelper("q", "Navigation", "Switch to next channel",     v, self.editor.nextChannel,     Qt.WidgetShortcut))
            #self._shortcutHelper("a", "Navigation", "Switch to previous channel", v, self.editor.previousChannel, Qt.WidgetShortcut))
            
            def sliceDelta(axis, delta):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] += delta
                newPos[axis] = max(0, newPos[axis]) 
                newPos[axis] = min(self.editor.posModel.shape[axis]-1, newPos[axis]) 
                self.editor.posModel.slicingPos = newPos

            def jumpToFirstSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = 0
                self.editor.posModel.slicingPos = newPos
                
            def jumpToLastSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = self.editor.posModel.shape[axis]-1
                self.editor.posModel.slicingPos = newPos
            
            # TODO: Fix this dependency on ImageView/HUD internals
            mgr.register("Ctrl+Up", ActionInfo( "Navigation", 
                                                "Slice up", 
                                                "Slice up", 
                                                partial(sliceDelta, i, 1),
                                                v,
                                                v.hud.buttons['slice'].upLabel) )

            mgr.register("Ctrl+Down", ActionInfo( "Navigation", 
                                                  "Slice up", 
                                                  "Slice up", 
                                                  partial(sliceDelta, i, -1),
                                                  v,
                                                  v.hud.buttons['slice'].downLabel) )

#            self._shortcutHelper("p", "Navigation", "Slice up (alternate shortcut)",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut)
#            self._shortcutHelper("o", "Navigation", "Slice down (alternate shortcut)", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut)
            
            mgr.register("Ctrl+Shift+Up", ActionInfo( "Navigation", 
                                                      "10 slices up", 
                                                      "10 slices up", 
                                                      partial(sliceDelta, i, 10),
                                                      v,
                                                      None) )

            mgr.register("Ctrl+Shift+Down", ActionInfo( "Navigation", 
                                                        "10 slices down", 
                                                        "10 slices down", 
                                                        partial(sliceDelta, i, -10),
                                                        v,
                                                        None) )

            mgr.register("Shift+Up", ActionInfo( "Navigation", 
                                                 "Jump to first slice", 
                                                 "Jump to first slice", 
                                                 partial(jumpToFirstSlice, i),
                                                 v,
                                                 None) )

            mgr.register("Shift+Down", ActionInfo( "Navigation", 
                                                   "Jump to last slice", 
                                                   "Jump to last slice", 
                                                   partial(jumpToLastSlice, i),
                                                   v,
                                                   None) )

    def _updateInfoLabels(self, pos):
        self.quadViewStatusBar.setMouseCoords(*pos)

    def eventFilter(self, watched, event):
        # If the user performs a ctrl+scroll on the splitter itself,
        # scroll all views.
        if event.type() == QEvent.Wheel and (event.modifiers() == Qt.ControlModifier):
            for view in self.editor.imageViews:
                if event.delta() > 0:
                    view.zoomIn()
                else:
                    view.zoomOut()
            return True
        return False
    
    def getViewMenu(self, debug_mode=False):
        """
        Return a QMenu with a set of actions for our editor.
        """
        if self._viewMenu is None:
            self._initViewMenu()
        for action in self._debugActions:
            action.setEnabled( debug_mode )
            action.setVisible( debug_mode )
        return self._viewMenu

    def _initViewMenu(self):
        self._viewMenu = QMenu("View", parent=self)
        self._viewMenu.setObjectName( "view_menu" )
        self._debugActions = []
        
        ActionInfo = ShortcutManager.ActionInfo
        
        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionFitToScreen = self._viewMenu.addAction( "&Zoom to &fit" )
        self._viewMenu.actionFitToScreen.triggered.connect(self._fitToScreen)

        def toggleHud():
            hide = not self.editor.imageViews[0]._hud.isVisible()
            for v in self.editor.imageViews:
                v.setHudVisible(hide)
        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionToggleAllHuds = self._viewMenu.addAction( "Toggle huds" )
        self._viewMenu.actionToggleAllHuds.triggered.connect(toggleHud)

        def resetAllAxes():
            for s in self.editor.imageScenes:
                s.resetAxes()
        self._viewMenu.addAction( "Reset all axes" ).triggered.connect(resetAllAxes)

        def centerAllImages():
            for v in self.editor.imageViews:
                v.centerImage()
        self._viewMenu.addAction( "Center images" ).triggered.connect(centerAllImages)

        def toggleDebugPatches(show):
            self.editor.showDebugPatches = show
        actionShowTiling = self._viewMenu.addAction( "Show Tiling" )
        actionShowTiling.setCheckable(True)
        actionShowTiling.toggled.connect(toggleDebugPatches)
        ShortcutManager().register( "Ctrl+D", ActionInfo( 
                                                   "Navigation",
                                                   "Show tiling",
                                                   "Show tiling",
                                                   actionShowTiling.toggle,
                                                   self,
                                                   None ) )
        self._debugActions.append( actionShowTiling )

        def setCacheSize( cache_size ):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget( QLabel("Cached Slices Per View:") )

            spinBox = QSpinBox( parent=dlg )
            spinBox.setRange( 0, 1000 )
            spinBox.setValue( self.editor.cacheSize )
            layout.addWidget( spinBox )
            okButton = QPushButton( "OK", parent=dlg )
            okButton.clicked.connect( dlg.accept )
            layout.addWidget( okButton )
            dlg.setLayout( layout )
            dlg.setModal(True)
            if dlg.exec_() == QDialog.Accepted:
                self.editor.cacheSize = spinBox.value()
        self._viewMenu.addAction( "Set layer cache size" ).triggered.connect(setCacheSize)

        '''
        #disabled for ilastik 1.0
        def enablePrefetching( enable ):
            for scene in self.editor.imageScenes:
                scene.setPrefetchingEnabled( enable )
        actionUsePrefetching = self._viewMenu.addAction( "Use prefetching" )
        actionUsePrefetching.setCheckable(True)
        actionUsePrefetching.toggled.connect(enablePrefetching)
        '''

        def blockGuiForRendering():
            for v in self.editor.imageViews:
                v.scene().joinRenderingAllTiles()
                v.repaint()
            QApplication.processEvents()
        actionBlockGui = self._viewMenu.addAction( "Block for rendering" )
        actionBlockGui.triggered.connect(blockGuiForRendering)
        ShortcutManager().register("Ctrl+B", ActionInfo( 
                                                  "Navigation", 
                                                  "Block gui for rendering",
                                                  "Block gui for rendering",
                                                  actionBlockGui.trigger,
                                                  self,
                                                  None ) )
        self._debugActions.append( actionBlockGui )

        # ------ Separator ------
        self._viewMenu.addAction("").setSeparator(True)

        # Text only
        actionOnlyForSelectedView = self._viewMenu.addAction( "Only for selected view" )
        actionOnlyForSelectedView.setIconVisibleInMenu(True)
        font = actionOnlyForSelectedView.font()
        font.setItalic(True)
        font.setBold(True)
        actionOnlyForSelectedView.setFont(font)
        def setCurrentAxisIcon():
            """Update the icon that shows the currently selected axis."""
            actionOnlyForSelectedView.setIcon(QIcon(self.editor.imageViews[self.editor._lastImageViewFocus]._hud.axisLabel.pixmap()))
        self.editor.newImageView2DFocus.connect(setCurrentAxisIcon)
        setCurrentAxisIcon()
        
        actionFitImage = self._viewMenu.addAction( "Fit image" )
        actionFitImage.triggered.connect(self._fitImage)
        ShortcutManager().register( "K", ActionInfo( "Navigation", 
                                                      "Fit image on screen", 
                                                      "Fit image on screen",
                                                      actionFitImage.trigger,
                                                      self,
                                                      None ) )

        def toggleSelectedHud():
            self.editor.imageViews[self.editor._lastImageViewFocus].toggleHud()
        actionToggleSelectedHud = self._viewMenu.addAction( "Toggle hud" )
        actionToggleSelectedHud.triggered.connect(toggleSelectedHud)

        def resetAxes():
            self.editor.imageScenes[self.editor._lastImageViewFocus].resetAxes()
        self._viewMenu.addAction( "Reset axes" ).triggered.connect(resetAxes)

        def centerImage():
            self.editor.imageViews[self.editor._lastImageViewFocus].centerImage()
        actionCenterImage = self._viewMenu.addAction( "Center image" )
        actionCenterImage.triggered.connect(centerImage)
        ShortcutManager().register( "C", ActionInfo( "Navigation", 
                                                      "Center image", 
                                                      "Center image", 
                                                      actionCenterImage.trigger,
                                                      self,
                                                      None ) )

        def restoreImageToOriginalSize():
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()
        actionResetZoom = self._viewMenu.addAction( "Reset zoom" )
        actionResetZoom.triggered.connect(restoreImageToOriginalSize)
        ShortcutManager().register( "W", ActionInfo( "Navigation", 
                                                      "Reset zoom", 
                                                      "Reset zoom", 
                                                      actionResetZoom.trigger,
                                                      self,
                                                      None ) )

        def updateHudActions():
            dataShape = self.editor.dataShape
            # if the image is 2D, do not show the HUD action (issue #190)
            is2D = numpy.sum(numpy.asarray(dataShape[1:4]) == 1) == 1
            actionToggleSelectedHud.setVisible(not is2D)
            self._viewMenu.actionToggleAllHuds.setVisible(not is2D)
        self.editor.shapeChanged.connect( updateHudActions )
Example #24
0
class pat_toolbar:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        Args:
            iface (QgsInterface): 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.
        """

        # 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', 'pat_plugin_{}.qm'.format(locale))

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

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

        self.actions = []

        # Look for the existing menu
        self.menuPrecAg = self.iface.mainWindow().findChild(QMenu, 'm{}Menu'.format(PLUGIN_SHORT))

        # If the menu does not exist, create it!
        if not self.menuPrecAg:
            self.menuPrecAg = QMenu('{}'.format(PLUGIN_SHORT), self.iface.mainWindow().menuBar())
            self.menuPrecAg.setObjectName('m{}Menu'.format(PLUGIN_SHORT))
            actions = self.iface.mainWindow().menuBar().actions()
            lastAction = actions[-1]
            self.iface.mainWindow().menuBar().insertMenu(lastAction, self.menuPrecAg)

        # create a toolbar
        self.toolbar = self.iface.addToolBar(u'{} Toolbar'.format(PLUGIN_SHORT))
        self.toolbar.setObjectName(u'm{}ToolBar'.format(PLUGIN_SHORT))

        # Load Defaults settings for First time...
        for eaKey in ['BASE_IN_FOLDER', 'BASE_OUT_FOLDER']:
            sFolder = read_setting(PLUGIN_NAME + '/' + eaKey)
            if sFolder is None or not os.path.exists(sFolder):
                sFolder = os.path.join(os.path.expanduser('~'), PLUGIN_NAME)

                if not os.path.exists(sFolder):
                    os.mkdir(sFolder)

                write_setting(PLUGIN_NAME + '/' + eaKey, os.path.join(os.path.expanduser('~'), PLUGIN_NAME))

        self.DEBUG = config.get_debug_mode()
        self.vesper_queue = []
        self.vesper_queue_showing = False
        self.processVesper = None
        self.vesper_exe = check_vesper_dependency(iface)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

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

        We implement this ourselves since we do not inherit QObject.

        Args:
            message (str, QString): String for translation.

        Returns:
            QString: Translated version of message.
        """

        return QCoreApplication.translate('pat', message)

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

                Args:
                    icon_path (str): Path to the icon for this action. Can be a resource
                         path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
                    text (str): Text that should be shown in menu items for this action.
                    callback (function): Function to be called when the action is triggered.
                    enabled_flag (bool): A flag indicating if the action should be enabled
                             by default. Defaults to True.
                    add_to_menu (bool): Flag indicating whether the action should also
                            be added to the menu. Defaults to True.
                    add_to_toolbar (bool): Flag indicating whether the action should also
                            be added to the toolbar. Defaults to True.
                    tool_tip (str):  Optional text to show in a popup when mouse pointer
                            hovers over the action.
                    status_tip (str):  Optional text to show in the status bar when mouse pointer
                            hovers over the action.
                    whats_this (QWidget): Parent widget for the new action. Defaults None.
                    parent (): Optional text to show in the status bar when the
                            mouse pointer hovers over the action.
                Returns:
                    QAction: The action that was created. Note that the action is also
                            added to self.actions list.
        """

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

        if tool_tip is not None:
            action.setToolTip(tool_tip)

        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.menuPrecAg.addAction(action)

        self.actions.append(action)

        return action

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

        '''Create new menu item
            source:https://gis.stackexchange.com/questions/169869/adding-multiple-plugins-to-custom-pluginMenu-in-qgis/169880#169880
                  https://gis.stackexchange.com/questions/127150/how-to-customize-the-qgis-gui-using-python '''

        # Finally, add your action to the menu and toolbar
        self.add_action(
            icon_path=':/plugins/pat/icons/icon_blockGrid.svg',
            text=self.tr(u'Create block grid'),
            tool_tip=self.tr(u'Create raster and VESPER grids for block polygons.'),
            status_tip=self.tr(u'Create raster and VESPER grids for block polygons.'),
            callback=self.run_blockGrid,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_cleanTrimPoints.svg',
            text=self.tr(u'Clean, trim and normalise data points'),
            tool_tip=self.tr(u'Clean, trim and normalise data points'),
            status_tip=self.tr(u'Clean, trim and normalise data points'),
            callback=self.run_cleanTrimPoints,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_vesperKriging.svg',
            text=self.tr(u'Run kriging using VESPER'),
            tool_tip=self.tr(u'Run kriging using VESPER'),
            status_tip=self.tr(u'Run kriging using VESPER'),
            callback=self.run_preVesper,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_importVesperKriging.svg',
            text=self.tr(u'Import VESPER results'),
            tool_tip=self.tr(u'Import VESPER results'),
            status_tip=self.tr(u'Import VESPER results'),
            add_to_toolbar=False,
            callback=self.run_postVesper,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_pointTrailToPolygon.svg',
            text=self.tr(u'Create polygons from on-the-go GPS point trail'),
            tool_tip=self.tr(u'Create polygons from on-the-go GPS point trail'),
            status_tip=self.tr(u'Create polygons from on-the-go GPS point trail'),
            add_to_toolbar=False,
            callback=self.run_pointTrailToPolygon,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_rescaleNormalise.svg',
            text=self.tr(u'Rescale or normalise raster'),
            tool_tip=self.tr(u'Rescale or normalise raster'),
            status_tip=self.tr(u'Rescale or normalise raster'),
            add_to_toolbar=False,
            callback=self.run_rescaleNormalise,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_randomPixel.svg',
            text=self.tr(u'Generate random pixel selection'),
            tool_tip=self.tr(u'Generate random pixel selection'),
            status_tip=self.tr(u'Generate random pixel selection'),
            add_to_toolbar=True,
            callback=self.run_generateRandomPixels,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_gridExtract.svg',
            text=self.tr(u'Extract raster pixel statistics for points'),
            tool_tip=self.tr(u'Extract raster pixel statistics for points'),
            status_tip=self.tr(u'Extract raster pixel statistics for points'),
            add_to_toolbar=True,
            callback=self.run_gridExtract,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_calcImgIndices.svg',
            text=self.tr(u'Calculate image indices for blocks'),
            tool_tip=self.tr(u'Calculate image indices for blocks'),
            status_tip=self.tr(u'Calculate image indices for blocks'),
            add_to_toolbar=True,
            callback=self.run_calculateImageIndices,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_resampleToBlock.svg',
            text=self.tr(u'Resample image band to blocks'),
            tool_tip=self.tr(u'Resample image band to blocks'),
            status_tip=self.tr(u'Resample image band to blocks'),
            add_to_toolbar=True,
            callback=self.run_resampleImage2Block,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_kMeansCluster.svg',
            text=self.tr(u'Create zones with k-means clustering'),
            tool_tip=self.tr(u'Create zones with k-means clustering'),
            status_tip=self.tr(u'Create zones with k-means clustering'),
            add_to_toolbar=True,
            callback=self.run_kMeansClustering,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_stripTrialPoints.svg',
            text=self.tr(u'Create strip trial points'),
            tool_tip=self.tr(u'Create strip trial points'),
            status_tip=self.tr(u'Create strip trial points'),
            add_to_toolbar=True,
            callback=self.run_stripTrialPoints,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_t-test.svg',
            text=self.tr(u'Run strip trial t-test analysis'),
            tool_tip=self.tr(u'Run strip trial t-test analysis'),
            status_tip=self.tr(u'Run strip trial t-test analysis'),
            add_to_toolbar=True,
            callback=self.run_tTestAnalysis,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_wholeOfBlockExp.svg',
            text=self.tr(u'Whole-of-block analysis'),
            tool_tip=self.tr(u'Whole-of-block analysis using co-kriging'),
            status_tip=self.tr(u'Whole-of-block analysis using co-kriging'),
            add_to_toolbar=True,
            callback=self.run_wholeOfBlockAnalysis,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_persistor.svg',
            text=self.tr(u'Persistor'),
            tool_tip=self.tr(u'Persistence over years'),
            status_tip=self.tr(u'Persistence over years'),
            add_to_toolbar=True,
            callback=self.run_persistor,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_rasterSymbology.svg',
            text=self.tr(u'Apply Raster Symbology'),
            tool_tip=self.tr(u'Apply Raster Symbology'),
            status_tip=self.tr(u'Apply Raster Symbology'),
            add_to_toolbar=True,
            callback=self.run_rasterSymbology,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_help.svg',
            text=self.tr(u'Help'),
            tool_tip=self.tr(u'Help'),
            status_tip=self.tr(u'Help'),
            callback=self.run_help,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_settings.svg',
            text=self.tr(u'Settings'),
            tool_tip=self.tr(u'Settings'),
            add_to_toolbar=False,
            status_tip=self.tr(u'Settings'),
            callback=self.run_settings,
            parent=self.iface.mainWindow())

        self.add_action(
            icon_path=':/plugins/pat/icons/icon_about.svg',
            text=self.tr(u'About'),
            tool_tip=self.tr(u'About'),
            status_tip=self.tr(u'About'),
            add_to_toolbar=False,
            callback=self.run_about,
            parent=self.iface.mainWindow())

    @staticmethod
    def clear_modules():
        """Unload pyprecag functions and try to return QGIS.
        source: inasafe plugin
        """
        # next lets force remove any pyprecag related modules
        modules = []
        for module in sys.modules:
            if 'pyprecag' in module:
                LOGGER.debug('Removing: %s' % module)
                modules.append(module)

        for module in modules:
            del (sys.modules[module])

        # Lets also clean up all the path additions that were made
        package_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        LOGGER.debug('Path to remove: %s' % package_path)
        # We use a list comprehension to ensure duplicate entries are removed
        LOGGER.debug(sys.path)
        sys.path = [y for y in sys.path if package_path not in y]
        LOGGER.debug(sys.path)

    def unload(self):
        """Removes the plugin menu/toolbar item and icon from QGIS GUI and clean up temp folder"""

        if len(self.vesper_queue) > 0:
            replyQuit = QMessageBox.information(self.iface.mainWindow(),
                                                "Quit QGIS", "Quitting QGIS with {} tasks in the "
                                                "VESPER queue.\n\t{}".format(len(self.vesper_queue),
                                                '\n\t'.join([ea['control_file'] for ea in self.vesper_queue])),
                                                QMessageBox.Ok)

        stop_logging('pyprecag')

        layermap = QgsMapLayerRegistry.instance().mapLayers()
        RemoveLayers = []
        for name, layer in layermap.iteritems():
            if TEMPDIR in layer.source():
                RemoveLayers.append(layer.id())

        if len(RemoveLayers) > 0:
            QgsMapLayerRegistry.instance().removeMapLayers(RemoveLayers)

        # remove the PrecisionAg Temp Folder.
        try:
            if not self.DEBUG and os.path.exists(TEMPDIR):
                shutil.rmtree(TEMPDIR)

        except Exception as err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            mess = str(traceback.format_exc())
            print(mess)

        self.menuPrecAg.clear()
        for action in self.actions:
            self.iface.removePluginMenu(u'{}Menu'.format(PLUGIN_SHORT), action)
            self.iface.removeToolBarIcon(action)

        # remove the toolbar
        del self.toolbar
        del self.menuPrecAg
        self.clear_modules()

    def queueAddTo(self, vesp_dict):
        """ Add a control file to the VESPER queue"""

        if next((x for x in self.vesper_queue if x['control_file'] == vesp_dict["control_file"])
                , None) is not None:

            self.iface.messageBar().pushMessage('Control file is already in the VESPER queue. {}'.format(
                vesp_dict['control_file']),level=QgsMessageBar.WARNING, duration=15)

            self.queueDisplay()

        else:
            self.vesper_queue.append(vesp_dict)
            message = 'Added control file to VESPER queue. The queue now contains {} tasks'.format(
                len(self.vesper_queue))
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.INFO, duration=15)

    def queueDisplay(self):
        """display the VESPER queue in the python console"""

        # open the python console
        try:
            pythonConsolePanel = self.iface.mainWindow().findChild(QDockWidget, 'PythonConsole')
            if not pythonConsolePanel.isVisible():
                self.iface.actionShowPythonDialog().trigger()
        except:
            # the above will bail if sitting on RecentProjects empty view.
            self.iface.actionShowPythonDialog().trigger()
            pythonConsolePanel = self.iface.mainWindow().findChild(QDockWidget, 'PythonConsole')

        ctrl_width = len(max([os.path.basename(ea['control_file']) for ea in self.vesper_queue], key=len))
        epsg_width = len(max([str(ea['epsg']) for ea in self.vesper_queue], key=len))

        header = '{:3}\t{:<{cw}}\t{:5}\t{:>{ew}} {}'.format(
            '#', 'Control File', 'Import', 'EPSG', 'Folder', cw=ctrl_width + 10, ew=epsg_width + 10)

        print('\n' + '-' * len(header))
        print(header)
        print('-' * len(header))
        for i, ea in enumerate(self.vesper_queue):
            print('{:3}\t{:<{cw}}\t{:5}\t{:>{ew}}\t{}'.format(
                i + 1, os.path.basename(ea['control_file']), str(bool(ea['epsg'] > 0)), ea['epsg'],
                os.path.dirname(ea['control_file']), cw=ctrl_width + 10, ew=epsg_width + 10))

        print('\n')

    def queueClear(self):
        """Clear the VESPER queue of all pending jobs"""
        # clear all but the one running.
        if self.processVesper is None:
            self.vesper_queue = []
            self.queueStatusBarHide()
        else:
            self.vesper_queue = self.vesper_queue[:1]
            self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue)))

        self.queueDisplay()

    def queueStatusBarShow(self):
        """Add to QGIS status bar buttons to show and clear the VESPER queue"""
        # source: https://gis.stackexchange.com/a/153170
        # https://github.com/ActiveState/code/blob/master/recipes/Python/578692_QGstartscript_Change_display/recipe-578692.py

        if not self.vesper_queue_showing:  # it is not initiated
            self.iface.mainWindow().statusBar().setSizeGripEnabled(False)
            self.lblVesperQueue = QLabel()
            self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue)))
            self.iface.mainWindow().statusBar().insertPermanentWidget(1, self.lblVesperQueue)

            self.btnShowQueue = QToolButton()  # QToolButton() takes up less room
            self.btnShowQueue.setToolButtonStyle(Qt.ToolButtonTextOnly)
            self.btnShowQueue.setText("Show")
            self.btnShowQueue.clicked.connect(self.queueDisplay)
            self.iface.mainWindow().statusBar().insertPermanentWidget(2, self.btnShowQueue)

            self.btnClearQueue = QToolButton()  # QPushButton()
            self.btnClearQueue.setToolButtonStyle(Qt.ToolButtonTextOnly)
            self.btnClearQueue.setText("Clear")
            self.btnClearQueue.pressed.connect(self.queueClear)
            self.iface.mainWindow().statusBar().insertPermanentWidget(3, self.btnClearQueue)
            self.vesper_queue_showing = True

    def queueStatusBarHide(self):
        """Remove VESPER queue information and buttons from the status bar"""
        for obj in [self.btnClearQueue, self.btnShowQueue, self.lblVesperQueue]:
            self.iface.mainWindow().statusBar().removeWidget(obj)
            del obj

        self.vesper_queue_showing = False

    def processRunVesper(self):
        """Run the next task in the VESPER queue"""

        # Queueing: http://www.qtforum.org/article/32172/qprocess-how-to-run-multiple-processes-in-a-loop.html

        self.vesper_run_time = time.time()
        if self.processVesper is None:
            self.processVesper = QProcess()
            # set a duration variable
            self.processVesper.started.connect(self.processStartedVesper)
            # sets a task for when finished.
            self.processVesper.finished.connect(self.processFinishedVesper)

        self.queueStatusBarShow()

        ctrl_file = self.vesper_queue[0]['control_file']
        self.processVesper.setWorkingDirectory(os.path.dirname(ctrl_file))

        # run and catch when finished: https://gist.github.com/justinfx/5174795     1)QProcess
        QTimer.singleShot(100, partial(self.processVesper.start, self.vesper_exe, [ctrl_file]))

    def processStartedVesper(self):  # connected to process.started slot
        self.vesper_run_time = time.time()

    def processFinishedVesper(self, exitCode, exitStatus):  # connected to process.finished slot
        """When VESPER is complete, import the results to TIFF and QGIS"""
        currentTask = self.vesper_queue[0]

        if exitCode == 0 and exitStatus == QProcess.NormalExit:
            self.processVesper.close()
            self.processVesper = None

            if currentTask['epsg'] > 0:
                try:
                    out_PredTif, out_SETif, out_CITxt = vesper_text_to_raster(currentTask['control_file'],
                                                                              currentTask['epsg'])

                    raster_sym = RASTER_SYMBOLOGY['Yield']

                    removeFileFromQGIS(out_PredTif)
                    rasterLyr = addRasterFileToQGIS(out_PredTif, atTop=False)
                    raster_apply_classified_renderer(rasterLyr,
                                    rend_type=raster_sym['type'],
                                    num_classes=raster_sym['num_classes'],
                                    color_ramp=raster_sym['colour_ramp'])

                    removeFileFromQGIS(out_SETif)
                    addRasterFileToQGIS(out_SETif, atTop=False)

                except Exception as err:
                    message = "Could not import from VESPER to raster TIFF possibly due to a " \
                              "VESPER error.\n{}".format(os.path.basename(currentTask['control_file']))

                    LOGGER.error(message)

            message = "Completed VESPER kriging for {}\t Duration H:M:SS - {dur}".format(
                        os.path.basename(currentTask['control_file']),
                        dur=datetime.timedelta(seconds=time.time() - self.vesper_run_time))
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.INFO, duration=15)
            LOGGER.info(message)

        else:
            message = "Error occurred with VESPER kriging for {}".format(currentTask['control_file'])
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.CRITICAL, duration=0)
            LOGGER.error(message)

        self.vesper_queue = self.vesper_queue[1:]  # remove the recently finished one which will always be at position 0

        self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue)))

        if len(self.vesper_queue) > 0:
            self.vesper_run_time = time.time()
            self.processRunVesper()

        else:
            self.vesper_queue = []
            self.vesper_run_time = ''
            self.queueStatusBarHide()

        return

    def run_persistor(self):
        """Run method for the Persistor dialog"""

        if parse_version(pyprecag.__version__) < parse_version('0.2.0'):
            self.iface.messageBar().pushMessage("Persistor is not supported in "
                                                "pyprecag {}. Upgrade to version 0.3.0+".format(
                pyprecag.__version__), level=QgsMessageBar.WARNING, duration=15)
            return

        dlgPersistor = PersistorDialog(self.iface)

        # Show the dialog
        dlgPersistor.show()

        if dlgPersistor.exec_():
            message = 'Persistor completed successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            # LOGGER.info(message)

        # Close Dialog
        dlgPersistor.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_wholeOfBlockAnalysis(self):
        """Run method for the fit to block grid dialog"""
        # https://gis.stackexchange.com/a/160146

        result = check_R_dependency()
        if result is not True:
            self.iface.messageBar().pushMessage("R configuration", result,
                                                level=QgsMessageBar.WARNING, duration=15)
            return

        proc_alg_mess = ProcessingAlgMessages(self.iface)
        QgsMessageLog.instance().messageReceived.connect(proc_alg_mess.processingCatcher)

        # Then get the algorithm you're interested in (for instance, Join Attributes):
        alg = Processing.getAlgorithm("r:wholeofblockanalysis")
        if alg is None:
            self.iface.messageBar().pushMessage("Whole-of-block analysis algorithm could not"
                                                " be found", level=QgsMessageBar.CRITICAL)
            return
        # Instantiate the commander window and open the algorithm's interface
        cw = CommanderWindow(self.iface.mainWindow(), self.iface.mapCanvas())
        if alg is not None:
            cw.runAlgorithm(alg)

        # if proc_alg_mess.alg_name == '' then cancel was clicked

        if proc_alg_mess.error:
            self.iface.messageBar().pushMessage("Whole-of-block analysis", proc_alg_mess.error_msg,
                                                level=QgsMessageBar.CRITICAL, duration=0)
        elif proc_alg_mess.alg_name != '':
            data_column = proc_alg_mess.parameters['Data_Column']

            # load rasters into qgis as grouped layers.
            for key, val in proc_alg_mess.output_files.items():

                grplyr = os.path.join('Whole-of-block {}'.format(data_column),  val['title'])

                for ea_file in val['files']:
                    removeFileFromQGIS(ea_file)
                    raster_layer = addRasterFileToQGIS(ea_file, group_layer_name=grplyr, atTop=False)
                    if key in ['p_val']:
                        raster_apply_unique_value_renderer(raster_layer)

            self.iface.messageBar().pushMessage("Whole-of-block analysis Completed Successfully!",
                                                level=QgsMessageBar.INFO, duration=15)

        del proc_alg_mess

    def run_stripTrialPoints(self):

        if parse_version(pyprecag.__version__) < parse_version('0.2.0'):
            self.iface.messageBar().pushMessage(
                "Create strip trial points tool is not supported in pyprecag {}. "
                "Upgrade to version 0.2.0+".format(pyprecag.__version__),
                level=QgsMessageBar.WARNING, duration=15)
            return

        """Run method for the Strip trial points dialog"""
        dlgStripTrialPoints = StripTrialPointsDialog(self.iface)

        # Show the dialog
        dlgStripTrialPoints.show()

        if dlgStripTrialPoints.exec_():
            message = 'Strip trial points created successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            # LOGGER.info(message)

        # Close Dialog
        dlgStripTrialPoints.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_tTestAnalysis(self):
        if parse_version(pyprecag.__version__) < parse_version('0.3.0'):
            self.iface.messageBar().pushMessage("Create t-test analysis tool is not supported in "
                                                "pyprecag {}. Upgrade to version 0.3.0+".format(
                pyprecag.__version__), level=QgsMessageBar.WARNING, duration=15)
            return

        """Run method for the Strip trial points dialog"""
        dlg_tTestAnalysis = tTestAnalysisDialog(self.iface)

        # Show the dialog
        dlg_tTestAnalysis.show()

        if dlg_tTestAnalysis.exec_():
            output_folder = dlg_tTestAnalysis.lneOutputFolder.text()
            import webbrowser
            try:
                from urllib import pathname2url         # Python 2.x
            except:
                from urllib.request import pathname2url # Python 3.x

            def open_folder():
                url = 'file:{}'.format(pathname2url(os.path.abspath(output_folder)))
                webbrowser.open(url)

            message = 'Strip trial t-test analysis completed!'

            # Add hyperlink to messagebar - this works but it places the text on the right, not left.
            # variation of QGIS-master\python\plugins\db_manager\db_tree.py
            # msgLabel = QLabel(self.tr('{0} <a href="{1}">{1}</a>'.format(message, output_folder)), self.iface.messageBar())
            # msgLabel.linkActivated.connect(open_folder)
            # self.iface.messageBar().pushWidget(msgLabel,level=QgsMessageBar.SUCCESS, duration=15)

            # so use a button instead
            widget = self.iface.messageBar().createMessage('', message)
            button = QPushButton(widget)
            button.setText('Open Folder')
            button.pressed.connect(open_folder)
            widget.layout().addWidget(button)
            self.iface.messageBar().pushWidget(widget, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlg_tTestAnalysis.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_kMeansClustering(self):
        """Run method for the Calculate Image Indices dialog"""
        dlgKMeansCluster = KMeansClusterDialog(self.iface)

        # Show the dialog
        dlgKMeansCluster.show()

        if dlgKMeansCluster.exec_():
            message = 'Zones with k-means clusters completed successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            # LOGGER.info(message)

        # Close Dialog
        dlgKMeansCluster.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_calculateImageIndices(self):
        """Run method for the Calculate Image Indices dialog"""
        dlgCalcImgIndices = CalculateImageIndicesDialog(self.iface)

        # Show the dialog
        dlgCalcImgIndices.show()

        if dlgCalcImgIndices.exec_():
            message = 'Image indices calculated successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgCalcImgIndices.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_resampleImage2Block(self):
        """Run method for the Resample image to block grid dialog"""
        dlgResample2Block = ResampleImageToBlockDialog(self.iface)

        # Show the dialog
        dlgResample2Block.show()

        if dlgResample2Block.exec_():
            message = 'Resample to block grid completed Successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgResample2Block.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_gridExtract(self):
        """Run method for the Grid Extract dialog"""
        dlgGridExtract = GridExtractDialog(self.iface)

        # Show the dialog
        dlgGridExtract.show()

        if dlgGridExtract.exec_():
            output_file = dlgGridExtract.lneSaveCSVFile.text()

            import webbrowser
            try:
                from urllib import pathname2url  # Python 2.x
            except:
                from urllib.request import pathname2url  # Python 3.x

            def open_folder():
                url = 'file:{}'.format(pathname2url(os.path.abspath(output_file)))
                webbrowser.open(url)

            message = 'Raster statistics for points extracted successfully !'
            #add a button to open the file outside qgis
            widget = self.iface.messageBar().createMessage('', message)
            button = QPushButton(widget)
            button.setText('Open File')
            button.pressed.connect(open_folder)
            widget.layout().addWidget(button)
            self.iface.messageBar().pushWidget(widget, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgGridExtract.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_generateRandomPixels(self):
        """Run method for the Generate random pixels dialog"""
        dlgGenRandomPixel = RandomPixelSelectionDialog(self.iface)

        # Show the dialog
        dlgGenRandomPixel.show()

        if dlgGenRandomPixel.exec_():
            message = 'Random pixel selection completed successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgGenRandomPixel.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_rescaleNormalise(self):
        """Run method for the rescale/normalise dialog"""
        dlgRescaleNorm = RescaleNormaliseDialog(self.iface)

        # Show the dialog
        dlgRescaleNorm.show()

        if dlgRescaleNorm.exec_():
            message = 'Rescale/Normalise completed successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgRescaleNorm.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_preVesper(self):
        """Run method for preVesper dialog"""

        dlgPreVesper = PreVesperDialog(self.iface)

        # show the dialog
        dlgPreVesper.show()

        if dlgPreVesper.exec_():
            if dlgPreVesper.gbRunVesper.isChecked():
                self.queueAddTo(dlgPreVesper.vesp_dict)
                self.processRunVesper()
                if len(self.vesper_queue) > 0:
                    self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue)))

        # Close Dialog
        dlgPreVesper.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_postVesper(self):
        """Run method for importing VESPER results dialog"""
        dlgPostVesper = PostVesperDialog(self.iface)

        # show the dialog
        dlgPostVesper.show()

        if dlgPostVesper.exec_():
            if dlgPostVesper.chkRunVesper.isChecked():

                self.queueAddTo(dlgPostVesper.vesp_dict)
                # if this is the first in the queue then start the processing.
                self.processRunVesper()

                if len(self.vesper_queue) > 0:
                    self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue)))

        # Close Dialog
        dlgPostVesper.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_cleanTrimPoints(self):
        """Run method for cleanTrimPoints dialog"""
        dlgCleanTrimPoints = CleanTrimPointsDialog(self.iface)

        # show the dialog
        dlgCleanTrimPoints.show()

        if dlgCleanTrimPoints.exec_():
            output_folder = os.path.dirname(dlgCleanTrimPoints.lneSaveCSVFile.text())
            import webbrowser
            try:
                from urllib import pathname2url  # Python 2.x
            except:
                from urllib.request import pathname2url  # Python 3.x

            def open_folder():
                url = 'file:{}'.format(pathname2url(os.path.abspath(output_folder)))
                webbrowser.open(url)

            message = 'Cleaned and trimmed points successfully !'

            widget = self.iface.messageBar().createMessage('', message)
            button = QPushButton(widget)
            button.setText('Open Folder')
            button.pressed.connect(open_folder)
            widget.layout().addWidget(button)

            self.iface.messageBar().pushWidget(widget, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgCleanTrimPoints.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_blockGrid(self):
        """Run method for the block grid dialog"""
        dlgBlockGrid = BlockGridDialog(self.iface)

        # Show the dialog
        dlgBlockGrid.show()

        if dlgBlockGrid.exec_():
            message = 'Block grid completed successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgBlockGrid.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()


    def run_pointTrailToPolygon(self):
        """Run method for pointTrailToPolygon dialog"""
        dlgPointTrailToPolygon = PointTrailToPolygonDialog(self.iface)

        # show the dialog
        dlgPointTrailToPolygon.show()

        if dlgPointTrailToPolygon.exec_():
            message = 'On-the-go point trail to polygon completed successfully !'
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15)
            LOGGER.info(message)

        # Close Dialog
        dlgPointTrailToPolygon.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_rasterSymbology(self):
        """Run method for the Raster Symbology dialog"""
        dlgRasterSymbology = RasterSymbologyDialog(self.iface)

        # Show the dialog
        dlgRasterSymbology.show()

        if dlgRasterSymbology.exec_():
            pass

        # Close Dialog
        dlgRasterSymbology.deleteLater()

        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_help(self):
        """Open the help PDF"""
        webbrowser.open_new('file:///' + os.path.join(PLUGIN_DIR, 'PAT_User_Manual.pdf#pagemode=bookmarks'))

    def run_about(self):
        """Run method for the about dialog"""
        dlgAbout = AboutDialog()
        if dlgAbout.exec_():
            pass

        dlgAbout.deleteLater()
        # Refresh QGIS
        QCoreApplication.processEvents()

    def run_settings(self):
        """Run method for the about dialog"""
        dlgSettings = SettingsDialog()
        if dlgSettings.exec_():
            self.vesper_exe = dlgSettings.vesper_exe
            self.DEBUG = config.get_debug_mode()

        dlgSettings.deleteLater()
Example #25
0
class FreeseerApp(QMainWindowWithDpi):

    def __init__(self, config):
        super(FreeseerApp, self).__init__()
        self.config = config
        self.icon = QIcon()
        self.icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(self.icon)

        self.aboutDialog = AboutDialog()
        self.aboutDialog.setModal(True)

        self.logDialog = LogDialog()

        #
        # Translator
        #
        self.app = QApplication.instance()
        self.current_language = None
        self.uiTranslator = QTranslator()
        self.uiTranslator.load(":/languages/tr_en_US.qm")
        self.app.installTranslator(self.uiTranslator)
        self.langActionGroup = QActionGroup(self)
        self.langActionGroup.setExclusive(True)
        QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8'))
        self.connect(self.langActionGroup, SIGNAL('triggered(QAction *)'), self.translate)
        # --- Translator

        #
        # Setup Menubar
        #
        self.menubar = self.menuBar()

        self.menubar.setGeometry(self.qrect_with_dpi(0, 0, 500, 50))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        self.menuLanguage = QMenu(self.menubar)
        self.menuLanguage.setObjectName(_fromUtf8("menuLanguage"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName(_fromUtf8("menuHelp"))

        exitIcon = QIcon.fromTheme("application-exit")
        self.actionExit = QAction(self)
        self.actionExit.setShortcut("Ctrl+Q")
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setIcon(exitIcon)

        helpIcon = QIcon.fromTheme("help-contents")
        self.actionOnlineHelp = QAction(self)
        self.actionOnlineHelp.setObjectName(_fromUtf8("actionOnlineHelp"))
        self.actionOnlineHelp.setIcon(helpIcon)

        self.actionAbout = QAction(self)
        self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
        self.actionAbout.setIcon(self.icon)

        self.actionLog = QAction(self)
        self.actionLog.setObjectName(_fromUtf8("actionLog"))
        self.actionLog.setShortcut("Ctrl+L")

        # Actions
        self.menuFile.addAction(self.actionExit)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addAction(self.actionLog)
        self.menuHelp.addAction(self.actionOnlineHelp)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuLanguage.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.setupLanguageMenu()
        # --- End Menubar

        self.connect(self.actionExit, SIGNAL('triggered()'), self.close)
        self.connect(self.actionAbout, SIGNAL('triggered()'), self.aboutDialog.show)
        self.connect(self.actionLog, SIGNAL('triggered()'), self.logDialog.show)
        self.connect(self.actionOnlineHelp, SIGNAL('triggered()'), self.openOnlineHelp)

        self.retranslateFreeseerApp()
        self.aboutDialog.aboutWidget.retranslate("en_US")

    def openOnlineHelp(self):
        """Opens a link to the Freeseer Online Help"""
        url = QUrl("http://freeseer.readthedocs.org")
        QDesktopServices.openUrl(url)

    def translate(self, action):
        """Translates the GUI via menu action.

        When a language is selected from the language menu, this function is
        called and the language to be changed to is retrieved.
        """
        self.current_language = str(action.data().toString()).strip("tr_").rstrip(".qm")

        log.info("Switching language to: %s" % action.text())
        self.uiTranslator.load(":/languages/tr_%s.qm" % self.current_language)
        self.app.installTranslator(self.uiTranslator)

        self.retranslateFreeseerApp()
        self.aboutDialog.aboutWidget.retranslate(self.current_language)
        self.retranslate()
        self.logDialog.retranslate()

    def retranslate(self):
        """
        Reimplement this function to provide translations to your app.
        """
        pass

    def retranslateFreeseerApp(self):
        #
        # Menubar
        #
        self.menuFile.setTitle(self.app.translate("FreeseerApp", "&File"))
        self.menuLanguage.setTitle(self.app.translate("FreeseerApp", "&Language"))
        self.menuHelp.setTitle(self.app.translate("FreeseerApp", "&Help"))

        self.actionExit.setText(self.app.translate("FreeseerApp", "&Quit"))
        self.actionAbout.setText(self.app.translate("FreeseerApp", "&About"))
        self.actionLog.setText(self.app.translate("FreeseerApp", "View &Log"))
        self.actionOnlineHelp.setText(self.app.translate("FreeseerApp", "Online Documentation"))
        # --- Menubar

    def setupLanguageMenu(self):
        self.languages = QDir(":/languages").entryList()

        if self.current_language is None:
            self.current_language = QLocale.system().name()  # Retrieve Current Locale from the operating system.
            log.debug("Detected user's locale as %s" % self.current_language)

        for language in self.languages:
            translator = QTranslator()  # Create a translator to translate Language Display Text.
            translator.load(":/languages/%s" % language)
            language_display_text = translator.translate("Translation", "Language Display Text")

            languageAction = QAction(self)
            languageAction.setCheckable(True)
            languageAction.setText(language_display_text)
            languageAction.setData(language)
            self.menuLanguage.addAction(languageAction)
            self.langActionGroup.addAction(languageAction)
class Kortforsyningen:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.settings = KFSettings()
        
        path = QFileInfo(os.path.realpath(__file__)).path()
        kf_path = path + '/kf/'
        if not os.path.exists(kf_path):
            os.makedirs(kf_path)
            
        self.settings.addSetting('cache_path', 'string', 'global', kf_path)
        self.settings.addSetting('kf_qlr_url', 'string', 'global', CONFIG_FILE_URL)

        self.local_about_file = kf_path + 'about.html'

        # Categories
        self.categories = []
        self.nodes_by_index = {}
        self.node_count = 0

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

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

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

        self.networkManager = QNetworkAccessManager()

    def initGui(self):
        self.config = Config(self.settings, self.networkManager)
        self.config.con_loaded.connect(self.createMenu)
        self.config.kf_con_error.connect(self.show_kf_error)
        self.config.kf_settings_warning.connect(self.show_kf_settings_warning)
        self.config.load()
        
    def show_kf_error(self, error_message):
        log_message(error_message)
        message = u'Check connection and click menu Kortforsyningen->Settings->OK'
        self.iface.messageBar().pushMessage(error_message, message, level=QgsMessageBar.WARNING, duration=10)

    def show_kf_settings_warning(self):
            widget = self.iface.messageBar().createMessage(
                self.tr('Kortforsyningen'), self.tr(u'Username/Password not set or wrong. Click menu Kortforsyningen->Settings')
            )
            settings_btn = QPushButton(widget)
            settings_btn.setText(self.tr("Settings"))
            settings_btn.pressed.connect(self.settings_dialog)
            widget.layout().addWidget(settings_btn)
            self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING, duration=10)

    def createMenu(self):
        self.categories = self.config.get_categories()
        self.category_lists = self.config.get_category_lists()
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/Kortforsyningen/settings-cog.png'
        icon_path_info = ':/plugins/Kortforsyningen/icon_about.png'

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName(self.tr('Kortforsyningen'))
        self.menu.setTitle(self.tr('Kortforsyningen'))
        
        searchable_layers = []

        # Add menu object for each theme
        self.category_menus = []
        kf_helper = lambda _id: lambda: self.open_kf_node(_id)
        local_helper = lambda _id: lambda: self.open_local_node(_id)
        
        for category_list in self.category_lists:
            list_categorymenus = []
            for category in category_list:
                category_menu = QMenu()
                category_menu.setTitle(category['name'])
                for selectable in category['selectables']:
                    q_action = QAction(
                        selectable['name'], self.iface.mainWindow()
                    )
                    if selectable['source'] == 'kf':
                        q_action.triggered.connect(
                            kf_helper(selectable['id'])
                        )
                    else:
                        q_action.triggered.connect(
                            local_helper(selectable['id'])
                        )
                    category_menu.addAction(q_action)
                    searchable_layers.append(
                        {
                            'title': selectable['name'],
                            'category': category['name'],
                            'action': q_action
                        }
                    )
                list_categorymenus.append(category_menu)
                self.category_menus.append(category_menu)
            for category_menukuf in list_categorymenus:
                self.menu.addMenu(category_menukuf)
            self.menu.addSeparator()
        self.septimasearchprovider = MySeptimaSearchProvider(self, searchable_layers)

        # Add settings
        self.settings_menu = QAction(
            QIcon(icon_path),
            self.tr('Settings'),
            self.iface.mainWindow()
        )
        self.settings_menu.setObjectName(self.tr('Settings'))
        self.settings_menu.triggered.connect(self.settings_dialog)
        self.menu.addAction(self.settings_menu)

        # Add about
        self.about_menu = QAction(
            QIcon(icon_path_info),
            self.tr('About the plugin'),
            self.iface.mainWindow()
        )
        self.about_menu.setObjectName(self.tr('About the plugin'))
        self.about_menu.triggered.connect(self.about_dialog)
        self.menu.addAction(self.about_menu)

        menu_bar = self.iface.mainWindow().menuBar()
        menu_bar.insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.menu
        )
        
    def open_local_node(self, id):
        node = self.config.get_local_maplayer_node(id)
        self.open_node(node, id)

    def open_kf_node(self, id):
        node = self.config.get_kf_maplayer_node(id)
        layer = self.open_node(node, id)

    def open_node(self, node, id):
        QgsProject.instance().read(node)
        layer = QgsMapLayerRegistry.instance().mapLayer(id)
        if layer:
            self.iface.legendInterface().refreshLayerSymbology(layer)
            #self.iface.legendInterface().moveLayer(layer, 0)
            self.iface.legendInterface().refreshLayerSymbology(layer)
            return layer
        else:
            return None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Kortforsyningen', message)

    def settings_dialog(self):
        dlg = KFSettingsDialog(self.settings)
        dlg.setWidgetsFromValues()
        dlg.show()
        result = dlg.exec_()

        if result == 1:
            del dlg
            self.reloadMenu()

    def about_dialog(self):
        if 'KFAboutDialog' in globals():
            dlg = KFAboutDialog()
            dlg.webView.setUrl(QUrl(ABOUT_FILE_URL))
            dlg.webView.urlChanged
            dlg.show()
            result = dlg.exec_()

            if result == 1:
                del dlg
        else:
            dlg = KFAlternativeAboutDialog()
            dlg.buttonBox.accepted.connect(dlg.accept)
            dlg.buttonBox.rejected.connect(dlg.reject)
            dlg.textBrowser.setHtml(self.tr('<p>QGIS is having trouble showing the content of this dialog. Would you like to open it in an external browser window?</p>'))
            dlg.show()
            result = dlg.exec_()

            if result:
                webbrowser.open(ABOUT_FILE_URL)

    def unload(self):
        # Remove settings if user not asked to keep them
        if self.settings.value('remember_settings') is False:
            self.settings.setValue('username', '')
            self.settings.setValue('password', '')
        self.clearMenu();
        
    def reloadMenu(self):
        self.clearMenu()
        self.config.load()
        #self.createMenu()
    
    def clearMenu(self):
        # Remove the submenus
        for submenu in self.category_menus:
            if submenu:
                submenu.deleteLater()
        # remove the menu bar item
        if self.menu:
            self.menu.deleteLater()
Example #27
0
class DsgTools:
    """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',
            'DsgTools_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference

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

        self.dsgTools = None
        self.menuBar = self.iface.mainWindow().menuBar()

        #QDockWidgets
        self.complexWindow = None
        self.codeList = CodeList(iface)
        #self.attributesViewer = AttributesViewer(iface)
        self.validationToolbox = None
        self.contourDock = None
        self.fieldDock = None
        self.militaryDock = None
        self.rasterInfoDock = None

        self.processManager = ProcessManager(iface)

        self.BDGExTools = BDGExTools()
        
        self.styleManagerTool = StyleManagerTool(iface)
        self.copyPasteTool = CopyPasteTool(iface)
        self.acquisition = Acquisition(iface)
        self.freeHandAcquisiton = FreeHandMain(iface)
        self.flipLineTool = FlipLine(iface.mapCanvas(), iface)

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


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the InaSAFE toolbar.
        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str
        :param text: Text that should be shown in menu items for this action.
        :type text: str
        :param callback: Function to be called when the action is triggered.
        :type callback: function
        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool
        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool
        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool
        :param status_tip: Optional text to 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 addMenu(self, parent, name, title, icon_path):
        """
        Adds a QMenu
        """
        child = QMenu(parent)
        child.setObjectName(name)
        child.setTitle(self.tr(title))
        child.setIcon(QIcon(icon_path))
        parent.addMenu(child)
        return child

    def createToolButton(self, parent, text):
        """
        Creates a tool button (pop up menu)
        """
        button = QToolButton(parent)
        button.setObjectName(text)
        button.setToolButtonStyle(Qt.ToolButtonIconOnly)
        button.setPopupMode(QToolButton.MenuButtonPopup)
        parent.addWidget(button)
        return button

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

        self.dsgTools = QMenu(self.iface.mainWindow())
        self.dsgTools.setObjectName(u'DsgTools')
        self.dsgTools.setTitle(self.tr('DSG Tools'))
        self.fieldToolbox = None
        self.menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.dsgTools)


        #Sub menus
        server = self.addMenu(self.dsgTools, u'server', self.tr('Server Catalog'),':/plugins/DsgTools/icons/server.png')
        database = self.addMenu(self.dsgTools, u'database', self.tr('Database Tools'),':/plugins/DsgTools/icons/database.png')
        layers = self.addMenu(self.dsgTools, u'layers', self.tr('Layer Tools'),':/plugins/DsgTools/icons/layers.png')
        bdgex = self.addMenu(self.dsgTools, u'bdgex', self.tr('BDGEx'),':/plugins/DsgTools/icons/eb.png')
        productiontools = self.addMenu(self.dsgTools, u'productiontools', self.tr('Production Tools'),':/plugins/DsgTools/icons/productiontools.png')
        topocharts = self.addMenu(bdgex, u'topocharts', self.tr('Topographic Charts'),':/plugins/DsgTools/icons/eb.png')
        coverageLyr = self.addMenu(bdgex, u'coverageLyr', self.tr('Coverage Layers'),':/plugins/DsgTools/icons/eb.png')
        indexes = self.addMenu(bdgex, u'indexes', self.tr('Product Indexes'),':/plugins/DsgTools/icons/eb.png')
        rasterIndex = self.addMenu(indexes, u'rasterindex', self.tr('Topographic Charts'),':/plugins/DsgTools/icons/eb.png')
        vectorIndex = self.addMenu(indexes, u'vectorindex', self.tr('Vectorial Charts'),':/plugins/DsgTools/icons/eb.png')

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:250,000'),
            callback=self.load250kLayer,
            parent=topocharts,
            add_to_menu=False,
            add_to_toolbar=False)
        topocharts.addAction(action)
        
        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:100,000'),
            callback=self.load100kLayer,
            parent=topocharts,
            add_to_menu=False,
            add_to_toolbar=False)
        topocharts.addAction(action)
        
        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:50,000'),
            callback=self.load50kLayer,
            parent=topocharts,
            add_to_menu=False,
            add_to_toolbar=False)
        topocharts.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:25,000'),
            callback=self.load25kLayer,
            parent=topocharts,
            add_to_menu=False,
            add_to_toolbar=False)
        topocharts.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Landsat 7'),
            callback=self.loadLandsatLayer,
            parent=coverageLyr,
            add_to_menu=False,
            add_to_toolbar=False)
        coverageLyr.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('RapidEye'),
            callback=self.loadRapidEyeLayer,
            parent=coverageLyr,
            add_to_menu=False,
            add_to_toolbar=False)
        coverageLyr.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:250,000'),
            callback=self.load250kRasterIndex,
            parent=rasterIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        rasterIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:100,000'),
            callback=self.load100kRasterIndex,
            parent=rasterIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        rasterIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:50,000'),
            callback=self.load50kRasterIndex,
            parent=rasterIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        rasterIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:25,000'),
            callback=self.load25kRasterIndex,
            parent=rasterIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        rasterIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:250,000'),
            callback=self.load250kVectorIndex,
            parent=vectorIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        vectorIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:100,000'),
            callback=self.load100kVectorIndex,
            parent=vectorIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        vectorIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:50,000'),
            callback=self.load50kVectorIndex,
            parent=vectorIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        vectorIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/eb.png'
        action = self.add_action(
            icon_path,
            text=self.tr('1:25,000'),
            callback=self.load25kVectorIndex,
            parent=vectorIndex,
            add_to_menu=False,
            add_to_toolbar=False)
        vectorIndex.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/server.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Configure Servers'),
            callback=self.viewServers,
            parent=server,
            add_to_menu=False,
            add_to_toolbar=False)
        server.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/server.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Manage Databases from Server'),
            callback=self.batchDbManager,
            parent=server,
            add_to_menu=False,
            add_to_toolbar=False)
        server.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/histogram.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Image tools'),
            callback=self.showImageProcessor,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/inventory.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Inventory tools'),
            callback=self.showInventoryTool,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/install.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Models and Scripts Installer'),
            callback=self.installModelsAndScripts,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/install.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Convert Database'),
            callback=self.showConvertDatabase,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/custom_tools.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Options'),
            callback=self.showOptions,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)
        Options().firstTimeConfig()

        icon_path = ':/plugins/DsgTools/icons/dsg.png'
        action = self.add_action(
            icon_path,
            text=self.tr('About'),
            callback=self.showAbout,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/bug.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Report bug / Suggest features'),
            callback=self.showBugTracker,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/help.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Help'),
            callback=self.showHelp,
            parent=self.dsgTools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.dsgTools.addAction(action)

        #QToolButtons
        self.databaseButton = self.createToolButton(self.toolbar, u'DatabaseTools')
        self.layerButton = self.createToolButton(self.toolbar, u'LayerTools')
        self.productionButton = self.createToolButton(self.toolbar, u'ProductionTools')

        icon_path = ':/plugins/DsgTools/icons/postgis.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Create PostGIS'),
            callback=self.createPostGISDatabase,
            parent=database,
            add_to_menu=False,
            add_to_toolbar=False)
        database.addAction(action)
        self.databaseButton.addAction(action)
        self.databaseButton.setDefaultAction(action)

        icon_path = ':/plugins/DsgTools/icons/spatialite.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Create Spatialite'),
            callback=self.createSpatialiteDatabase,
            parent=database,
            add_to_menu=False,
            add_to_toolbar=False)
        database.addAction(action)
        self.databaseButton.addAction(action) 
        
        icon_path = ':/plugins/DsgTools/icons/batchDatabase.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Batch Database Creation'),
            callback=self.batchDatabaseCreation,
            parent=database,
            add_to_menu=False,
            add_to_toolbar=False)
        database.addAction(action)
        self.databaseButton.addAction(action) 

        icon_path = ':/plugins/DsgTools/icons/validationtools.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Perform database validation'),
            callback=self.showValidationToolbox,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.productionButton.addAction(action)
        self.productionButton.setDefaultAction(action)

        icon_path = ':/plugins/DsgTools/icons/fieldToolbox.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Feature (Re)classification Tool'),
            callback=self.showFieldToolbox,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.productionButton.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/frame.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Create Frame'),
            callback=self.createFrame,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.productionButton.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/complex.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Build Complex Structures'),
            callback=self.showComplexDock,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.productionButton.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/calccontour.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Assign Contour Values'),
            callback=self.showCalcContour,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.productionButton.addAction(action)
        #enable shortcut config
        self.iface.registerMainWindowAction(action, '')

        #removed until bugs are removed
        # icon_path = ':/plugins/DsgTools/icons/attributeSelector.png'
        # action = self.add_action(
        #     icon_path,
        #     text=self.tr('Copy and Paste Attribute Set'),
        #     callback=self.copyPasteTool.copyPaste,
        #     parent=productiontools,
        #     add_to_menu=False,
        #     add_to_toolbar=False)
        # productiontools.addAction(action)
        # self.productionButton.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/codelist.png'
        action = self.add_action(
            icon_path,
            text=self.tr('View Code List Codes and Values'),
            callback=self.showCodeList,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.productionButton.addAction(action)
    
        icon_path = ':/plugins/DsgTools/icons/category.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Load Layers'),
            callback=self.loadLayersFromServer,
            parent=layers,
            add_to_menu=False,
            add_to_toolbar=False)
        layers.addAction(action)
        self.layerButton.addAction(action)
        self.layerButton.setDefaultAction(action)

        icon_path = ':/plugins/DsgTools/icons/centroid.png'
        action = self.add_action(
            icon_path,
            text=self.tr('Load Auxiliar Structure'),
            callback=self.loadAuxStruct,
            parent=layers,
            add_to_menu=False,
            add_to_toolbar=False)
        layers.addAction(action)
        self.layerButton.addAction(action)

        icon_path = ':/plugins/DsgTools/icons/genericSelect.png'
        action = self.add_action(
            icon_path,
            text=self.tr('DSGTools: Generic Selector'),
            callback=self.copyPasteTool.selectMulti,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.toolbar.addAction(action)
        self.copyPasteTool.setSelectorAction(action)
        #enable shortcut config
        self.iface.registerMainWindowAction(action, '')
        action.setToolTip(self.tr("DSGTools: Generic Selector\nLeft Click: select feature's layer and put it on edit mode\nRight Click: Open feature's form\nControl+Left Click: add/remove feature from selection\nShift+Left Click+drag and drop: select all features that intersects rubberband."))
        
        icon_path = ':/plugins/DsgTools/icons/flipLineTool.png'
        action = self.add_action(
            icon_path,
            text=self.tr('DSGTools: Flip Line Tool'),
            callback=self.flipLineTool.startFlipLineTool,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.toolbar.addAction(action)
        self.flipLineTool.setAction(action)
        self.flipLineTool.setToolEnabled(self.iface.mapCanvas().currentLayer())
        #enable shortcut config
        self.iface.registerMainWindowAction(action, '')
        action.setToolTip(self.tr("DSGTools: Flip Line Tool\nTool to invert selected lines acquisition diretioning."))

        icon_path = ':/plugins/DsgTools/icons/home.png'
        action = self.add_action(
            icon_path,
            text=self.tr('DSGTools: Right Degree Angle Digitizing'),
            callback=self.acquisition.acquisitionNinetyDegrees,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.toolbar.addAction(action)
        self.acquisition.setPolygonAction(action)
        #enable shortcut config
        self.iface.registerMainWindowAction(action, '')
        action.setToolTip(self.tr("DSGTools: Right Degree Angle Digitizing\nControl modifier: disables tool while control is pressed."))

        icon_path = ':/plugins/DsgTools/icons/circle.png'
        action = self.add_action(
            icon_path,
            text=self.tr('DSGTools: Circle Digitizing'),
            callback=self.acquisition.acquisitionCircle,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        productiontools.addAction(action)
        self.toolbar.addAction(action)
        self.acquisition.setCircleAction(action)
        #enable shortcut config
        self.iface.registerMainWindowAction(action, '')

        self.acquisition.checkToDeactivate(self.iface.mapCanvas().currentLayer())

        icon_path = ':/plugins/DsgTools/icons/free_hand.png'
        action = self.add_action(
            icon_path,
            text=self.tr('DSGTools: Free Hand Acquisition'),
            callback=self.freeHandAcquisiton.run,
            parent=productiontools,
            add_to_menu=False,
            add_to_toolbar=False)
        self.freeHandAcquisiton.setAction(action)
        action.setEnabled(False)
        productiontools.addAction(action)
        self.toolbar.addAction(action)
        #enable shortcut config
        self.iface.registerMainWindowAction(action, '')
        self.inspectFeatures = InspectFeatures(self.iface, parent = productiontools)
        self.minimumAreaTool = MinimumAreaTool(self.iface, parent = productiontools)
        self.dsgRasterInfoTool = DsgRasterInfoTool(self.iface, parent = productiontools)
        self.toolbar.addWidget(self.minimumAreaTool)
        self.toolbar.addWidget(self.inspectFeatures)
        # self.inspectFeatures.enableShortcuts()
        # self.iface.registerMainWindowAction(self.inspectFeatures.action, '')
        self.toolbar.addWidget(self.styleManagerTool)
        self.toolbar.addWidget(self.dsgRasterInfoTool)

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

        if self.dsgTools is not None:
            self.menuBar.removeAction(self.dsgTools.menuAction())
        del self.dsgTools
        del self.toolbar

    def run(self):
        """
        Run method that performs all the real work
        """
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass

    def showAbout(self):
        """
        Shows the about dialog
        """
        dlg = AboutDialog()
        dlg.exec_()

    def showOptions(self):
        """
        Shows the options
        """
        dlg = Options()
        dlg.show()
        result = dlg.exec_()
        if result:
            pass

    def showHelp(self):
        """
        Shows the help
        """
        self.iface.openURL("https://github.com/dsgoficial/DsgTools/wiki", False)

    def showBugTracker(self):
        """
        Shows the bug tracker
        """
        self.iface.openURL("https://github.com/dsgoficial/DsgTools/issues", False)

    def showConvertDatabase(self):
        """
        Show sthe convert database dialog
        """
        dlg = ConvertDatabase()
        dlg.show()
        result = dlg.exec_()
        if result:
            pass
        
    def showImageProcessor(self):
        """
        Shows the processing tools dialog
        """
        dlg = ProcessingTools(self.iface)
        result = dlg.exec_()
        if result == 1:
            (filesList, rasterType, minOutValue, maxOutValue, outDir, percent, epsg) = dlg.getParameters()
            #creating the separate process
            self.processManager.createDpiProcess(filesList, rasterType, minOutValue, maxOutValue, outDir, percent, epsg)

    def showInventoryTool(self):
        """
        Shows the inventory tools dialog
        """
        dlg = InventoryTools(self.iface)
        result = dlg.exec_()
        if result == 1:
            (parentFolder, outputFile, makeCopy, destinationFolder, formatsList, isWhitelist, isOnlyGeo) = dlg.getParameters()
            #creating the separate process
            self.processManager.createInventoryProcess(parentFolder, outputFile, makeCopy, destinationFolder, formatsList, isWhitelist, isOnlyGeo)
            
    def useGenericSelector(self):
        """
        Shows the countour dock
        """
        if self.contourDock:
            self.iface.removeDockWidget(self.contourDock)
        else:
            self.contourDock = CalcContour(self.iface)
        self.contourDock.activateTool()
        self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.contourDock)
    
    def showCalcContour(self):
        """
        Shows the countour dock
        """
        if self.contourDock:
            self.iface.removeDockWidget(self.contourDock)
        else:
            self.contourDock = CalcContour(self.iface)
        self.contourDock.activateTool()
        self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.contourDock)
    
    def showCodeList(self):
        """
        Shows the Code list Dock
        """
        if self.codeList:
            self.iface.removeDockWidget(self.codeList)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.codeList)

    def showFieldToolbox(self):
        """
        Shows the reclassification tool box dock
        """
        if self.fieldDock:
            self.iface.removeDockWidget(self.fieldToolbox)
        else:
            self.fieldToolbox = FieldToolbox(self.iface)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.fieldToolbox)
    
    def showValidationToolbox(self):
        """
        Shows the Validation Dock
        """
        if self.validationToolbox:
            self.iface.removeDockWidget(self.validationToolbox)
        else:
            self.validationToolbox = ValidationToolbox(self.iface)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.validationToolbox)
    
    def showRasterInfoDock(self):
        """
        Shows the Raster Info dock
        """
        if self.rasterInfoDock:
            self.iface.removeDockWidget(self.rasterInfoDock)
        else:
            self.rasterInfoDock = DsgRasterInfoTool(self.iface)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.rasterInfoDock)

    def showComplexDock(self):
        """
        Shows the Manage Complex features Dock
        """
        if self.complexWindow:
            self.iface.removeDockWidget(self.complexWindow)
        else:
            self.complexWindow = ComplexWindow(self.iface)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.complexWindow)
            
    def installModelsAndScripts(self):
        """
        Shows the model and scripts installer dialog
        """
        dlg = ModelsAndScriptsInstaller()
        result = dlg.exec_()
        if result == 1:
            pass

    def createSpatialiteDatabase(self):
        """
        Shows the create spatialite dialog
        """
        try:
            self.databaseButton.setDefaultAction(self.toolbar.sender())
        except:
            pass
        dlg = CriaSpatialiteDialog()
        result = dlg.exec_()
        if result:
            pass
    
    def batchDatabaseCreation(self):
        """
        Shows the batch database creation dialog
        """
        try:
            self.databaseButton.setDefaultAction(self.toolbar.sender())
        except:
            pass
        dlg = BatchDbCreator()
        result = dlg.exec_()
        if result:
            pass

    def createPostGISDatabase(self):
        """
        Shows the create postgis dialog
        """
        try:
            self.databaseButton.setDefaultAction(self.toolbar.sender())
        except:
            pass
        dlg = PostgisDBTool(self.iface)
        result = dlg.exec_()
        if result == 1:
            (dbName, abstractDb , version, epsg) = dlg.getParameters()
            #creating the separate process
            self.processManager.createPostgisDatabaseProcess(dbName,abstractDb, version, epsg)


    def loadAuxStruct(self):
        """
        Shows the load line-centroid configuration dialog
        """
        try:
            self.layerButton.setDefaultAction(self.toolbar.sender())
        except:
            pass
        dlg = LoadAuxStruct(self.iface)
        dlg.show()
        result = dlg.exec_()
        if result:
            pass
    
    def loadLayersFromServer(self):
        """
        Shows the dialog that loads layers from server
        """
        dlg = LoadLayersFromServer(self.iface)
        dlg.show()
        result = dlg.exec_()
        if result:
            pass

    def createFrame(self):
        """
        Shows the create frame dialog
        """
        try:
            self.layerButton.setDefaultAction(self.toolbar.sender())
        except:
            pass
        dlg = CreateInomDialog(self.iface)
        dlg.show()
        result = dlg.exec_()
        if result:
            pass

    def viewServers(self):
        """
        Shows the view servers dialog
        """
        dlg = ViewServers(self.iface)
        dlg.show()
        result = dlg.exec_()
        if result:
            pass
    
    def exploreDB(self):
        """
        Shows the explore database dialog
        """
        dlg = ExploreDb()
        dlg.show()
        result = dlg.exec_()
        if result:
            pass

    def batchDbManager(self):
        """
        Shows the database manager dialog
        """
        dlg = BatchDbManager()
        dlg.show()
        result = dlg.exec_()
        if result:
            pass

    def loadRapidEyeLayer(self):
        """
        Loads rapideye layer
        """
        urlWithParams = self.BDGExTools.getTileCache('RapidEye')
        if not urlWithParams:
            return
        self.iface.addRasterLayer(urlWithParams, 'RapidEye','wms')

    def loadLandsatLayer(self):
        """
        Loads landsat layer
        """
        urlWithParams = self.BDGExTools.getTileCache('Landsat7')
        if not urlWithParams:
            return
        self.iface.addRasterLayer(urlWithParams, 'Landsat7', 'wms')

    def load250kLayer(self):
        """
        Loads landsat layer
        """
        urlWithParams = self.BDGExTools.getTileCache('1:250k')
        if not urlWithParams:
            return
        self.iface.addRasterLayer(urlWithParams, '1:250k', 'wms')
    
    def load100kLayer(self):
        """
        Loads 100k layer
        """
        urlWithParams = self.BDGExTools.getTileCache('1:100k')
        if not urlWithParams:
            return
        self.iface.addRasterLayer(urlWithParams, '1:100k', 'wms')

    def load50kLayer(self):
        """
        Loads 50k layer
        """
        urlWithParams = self.BDGExTools.getTileCache('1:50k')
        if not urlWithParams:
            return
        self.iface.addRasterLayer(urlWithParams, '1:50k', 'wms')

    def load25kLayer(self):
        """
        Loads 25k layer
        """
        urlWithParams = self.BDGExTools.getTileCache('1:25k')
        if not urlWithParams:
            return
        self.iface.addRasterLayer(urlWithParams, '1:25k', 'wms')

    def load250kRasterIndex(self):
        """
        Loads 250k raster index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F250_WGS84_MATRICIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:250k Available Raster Charts'), 'wms')

    def load100kRasterIndex(self):
        """
        Loads 100k raster index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F100_WGS84_MATRICIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:100k Available Raster Charts'), 'wms')

    def load50kRasterIndex(self):
        """
        Loads 50 raster index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F50_WGS84_MATRICIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:50k Available Raster Charts'), 'wms')

    def load25kRasterIndex(self):
        """
        Loads 25k raster index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F25_WGS84_MATRICIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:25k Available Raster Charts'), 'wms')

    def load250kVectorIndex(self):
        """
        Loads 250k vector index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F250_WGS84_VETORIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:250k Available Vectorial Charts'), 'wms')

    def load100kVectorIndex(self):
        """
        Loads 100k vector index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F100_WGS84_VETORIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:100k Available Vectorial Charts'), 'wms')

    def load50kVectorIndex(self):
        """
        Loads 50k vector index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F50_WGS84_VETORIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:50k Available Vectorial Charts'), 'wms')

    def load25kVectorIndex(self):
        """
        Loads 25k vector index layer
        """
        urlWithParams = 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=F25_WGS84_VETORIAL&styles=&url=http://www.geoportal.eb.mil.br/teogc42/terraogcwms.cgi?version=1.1.0'
        self.iface.addRasterLayer(urlWithParams, self.tr('1:25k Available Vectorial Charts'),'wms')
Example #28
0
class GdalTools:
    def __init__(self, iface):
        if not valid:
            return

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

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

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

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

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

    def initGui(self):
        if not valid:
            return
        if int(self.QgisVersion) < 1:
            QMessageBox.warning(
                self.iface.getMainWindow(), "Gdal Tools",
                QCoreApplication.translate("GdalTools",
                                           "QGIS version detected: ") +
                unicode(self.QgisVersion) + ".xx\n" +
                QCoreApplication.translate(
                    "GdalTools",
                    "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled."
                ))
            return None

        from tools.GdalTools_utils import GdalConfig, LayerRegistry
        self.GdalVersionNum = GdalConfig.versionNum()
        LayerRegistry.setIface(self.iface)

        # find the Raster menu
        rasterMenu = None
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()

        rasterText = QCoreApplication.translate("QgisApp", "&Raster")

        for a in actions:
            if a.menu() is not None and a.menu().title() == rasterText:
                rasterMenu = a.menu()
                break

        if rasterMenu is None:
            # no Raster menu, create and insert it before the Help menu
            self.menu = QMenu(rasterText, self.iface.mainWindow())
            lastAction = actions[len(actions) - 1]
            menu_bar.insertMenu(lastAction, self.menu)
        else:
            self.menu = rasterMenu
            self.menu.addSeparator()

        # projections menu (Warp (Reproject), Assign projection)
        self.projectionsMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Projections"),
            self.iface.mainWindow())
        self.projectionsMenu.setObjectName("projectionsMenu")

        self.warp = QAction(
            QIcon(":/icons/warp.png"),
            QCoreApplication.translate("GdalTools", "Warp (Reproject)..."),
            self.iface.mainWindow())
        self.warp.setObjectName("warp")
        self.warp.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Warp an image into a new coordinate system"))
        QObject.connect(self.warp, SIGNAL("triggered()"), self.doWarp)

        self.projection = QAction(
            QIcon(":icons/projection-add.png"),
            QCoreApplication.translate("GdalTools", "Assign Projection..."),
            self.iface.mainWindow())
        self.projection.setObjectName("projection")
        self.projection.setStatusTip(
            QCoreApplication.translate("GdalTools",
                                       "Add projection info to the raster"))
        QObject.connect(self.projection, SIGNAL("triggered()"),
                        self.doProjection)

        self.extractProj = QAction(
            QIcon(":icons/projection-export.png"),
            QCoreApplication.translate("GdalTools", "Extract Projection..."),
            self.iface.mainWindow())
        self.extractProj.setObjectName("extractProj")
        self.extractProj.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Extract projection information from raster(s)"))
        QObject.connect(self.extractProj, SIGNAL("triggered()"),
                        self.doExtractProj)

        self.projectionsMenu.addActions(
            [self.warp, self.projection, self.extractProj])

        # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB)
        self.conversionMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Conversion"),
            self.iface.mainWindow())
        self.conversionMenu.setObjectName("conversionMenu")

        if self.GdalVersionNum >= 1300:
            self.rasterize = QAction(
                QIcon(":/icons/rasterize.png"),
                QCoreApplication.translate("GdalTools",
                                           "Rasterize (Vector to Raster)..."),
                self.iface.mainWindow())
            self.rasterize.setObjectName("rasterize")
            self.rasterize.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Burns vector geometries into a raster"))
            QObject.connect(self.rasterize, SIGNAL("triggered()"),
                            self.doRasterize)
            self.conversionMenu.addAction(self.rasterize)

        if self.GdalVersionNum >= 1600:
            self.polygonize = QAction(
                QIcon(":/icons/polygonize.png"),
                QCoreApplication.translate("GdalTools",
                                           "Polygonize (Raster to Vector)..."),
                self.iface.mainWindow())
            self.polygonize.setObjectName("polygonize")
            self.polygonize.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools",
                    "Produces a polygon feature layer from a raster"))
            QObject.connect(self.polygonize, SIGNAL("triggered()"),
                            self.doPolygonize)
            self.conversionMenu.addAction(self.polygonize)

        self.translate = QAction(
            QIcon(":/icons/translate.png"),
            QCoreApplication.translate("GdalTools",
                                       "Translate (Convert Format)..."),
            self.iface.mainWindow())
        self.translate.setObjectName("translate")
        self.translate.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Converts raster data between different formats"))
        QObject.connect(self.translate, SIGNAL("triggered()"),
                        self.doTranslate)

        self.paletted = QAction(
            QIcon(":icons/24-to-8-bits.png"),
            QCoreApplication.translate("GdalTools", "RGB to PCT..."),
            self.iface.mainWindow())
        self.paletted.setObjectName("paletted")
        self.paletted.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Convert a 24bit RGB image to 8bit paletted"))
        QObject.connect(self.paletted, SIGNAL("triggered()"), self.doPaletted)

        self.rgb = QAction(
            QIcon(":icons/8-to-24-bits.png"),
            QCoreApplication.translate("GdalTools", "PCT to RGB..."),
            self.iface.mainWindow())
        self.rgb.setObjectName("rgb")
        self.rgb.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Convert an 8bit paletted image to 24bit RGB"))
        QObject.connect(self.rgb, SIGNAL("triggered()"), self.doRGB)

        self.conversionMenu.addActions(
            [self.translate, self.paletted, self.rgb])

        # extraction menu (Clipper, Contour)
        self.extractionMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Extraction"),
            self.iface.mainWindow())
        self.extractionMenu.setObjectName("extractionMenu")

        if self.GdalVersionNum >= 1600:
            self.contour = QAction(
                QIcon(":/icons/contour.png"),
                QCoreApplication.translate("GdalTools", "Contour..."),
                self.iface.mainWindow())
            self.contour.setObjectName("contour")
            self.contour.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Builds vector contour lines from a DEM"))
            QObject.connect(self.contour, SIGNAL("triggered()"),
                            self.doContour)
            self.extractionMenu.addAction(self.contour)

        self.clipper = QAction(
            QIcon(":icons/raster-clip.png"),
            QCoreApplication.translate("GdalTools", "Clipper..."),
            self.iface.mainWindow())
        self.clipper.setObjectName("clipper")
        #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") )
        QObject.connect(self.clipper, SIGNAL("triggered()"), self.doClipper)

        self.extractionMenu.addActions([self.clipper])

        # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve)
        self.analysisMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Analysis"),
            self.iface.mainWindow())
        self.analysisMenu.setObjectName("analysisMenu")

        if self.GdalVersionNum >= 1600:
            self.sieve = QAction(
                QIcon(":/icons/sieve.png"),
                QCoreApplication.translate("GdalTools", "Sieve..."),
                self.iface.mainWindow())
            self.sieve.setObjectName("sieve")
            self.sieve.setStatusTip(
                QCoreApplication.translate("GdalTools",
                                           "Removes small raster polygons"))
            QObject.connect(self.sieve, SIGNAL("triggered()"), self.doSieve)
            self.analysisMenu.addAction(self.sieve)

        if self.GdalVersionNum >= 1500:
            self.nearBlack = QAction(
                QIcon(":/icons/nearblack.png"),
                QCoreApplication.translate("GdalTools", "Near Black..."),
                self.iface.mainWindow())
            self.nearBlack.setObjectName("nearBlack")
            self.nearBlack.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools",
                    "Convert nearly black/white borders to exact value"))
            QObject.connect(self.nearBlack, SIGNAL("triggered()"),
                            self.doNearBlack)
            self.analysisMenu.addAction(self.nearBlack)

        if self.GdalVersionNum >= 1700:
            self.fillNodata = QAction(
                QIcon(":/icons/fillnodata.png"),
                QCoreApplication.translate("GdalTools", "Fill nodata..."),
                self.iface.mainWindow())
            self.fillNodata.setObjectName("fillNodata")
            self.fillNodata.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools",
                    "Fill raster regions by interpolation from edges"))
            QObject.connect(self.fillNodata, SIGNAL("triggered()"),
                            self.doFillNodata)
            self.analysisMenu.addAction(self.fillNodata)

        if self.GdalVersionNum >= 1600:
            self.proximity = QAction(
                QIcon(":/icons/proximity.png"),
                QCoreApplication.translate("GdalTools",
                                           "Proximity (Raster Distance)..."),
                self.iface.mainWindow())
            self.proximity.setObjectName("proximity")
            self.proximity.setStatusTip(
                QCoreApplication.translate("GdalTools",
                                           "Produces a raster proximity map"))
            QObject.connect(self.proximity, SIGNAL("triggered()"),
                            self.doProximity)
            self.analysisMenu.addAction(self.proximity)

        if self.GdalVersionNum >= 1500:
            self.grid = QAction(
                QIcon(":/icons/grid.png"),
                QCoreApplication.translate("GdalTools",
                                           "Grid (Interpolation)..."),
                self.iface.mainWindow())
            self.grid.setObjectName("grid")
            self.grid.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Create raster from the scattered data"))
            QObject.connect(self.grid, SIGNAL("triggered()"), self.doGrid)
            self.analysisMenu.addAction(self.grid)

        if self.GdalVersionNum >= 1700:
            self.dem = QAction(
                QIcon(":icons/dem.png"),
                QCoreApplication.translate("GdalTools",
                                           "DEM (Terrain Models)..."),
                self.iface.mainWindow())
            self.dem.setObjectName("dem")
            self.dem.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Tool to analyze and visualize DEMs"))
            QObject.connect(self.dem, SIGNAL("triggered()"), self.doDEM)
            self.analysisMenu.addAction(self.dem)

        #self.analysisMenu.addActions( [  ] )

        # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog))
        self.miscellaneousMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Miscellaneous"),
            self.iface.mainWindow())
        self.miscellaneousMenu.setObjectName("miscellaneousMenu")

        if self.GdalVersionNum >= 1600:
            self.buildVRT = QAction(
                QIcon(":/icons/vrt.png"),
                QCoreApplication.translate(
                    "GdalTools", "Build Virtual Raster (Catalog)..."),
                self.iface.mainWindow())
            self.buildVRT.setObjectName("buildVRT")
            self.buildVRT.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Builds a VRT from a list of datasets"))
            QObject.connect(self.buildVRT, SIGNAL("triggered()"),
                            self.doBuildVRT)
            self.miscellaneousMenu.addAction(self.buildVRT)

        self.merge = QAction(
            QIcon(":/icons/merge.png"),
            QCoreApplication.translate("GdalTools", "Merge..."),
            self.iface.mainWindow())
        self.merge.setObjectName("merge")
        self.merge.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Build a quick mosaic from a set of images"))
        QObject.connect(self.merge, SIGNAL("triggered()"), self.doMerge)

        self.info = QAction(
            QIcon(":/icons/raster-info.png"),
            QCoreApplication.translate("GdalTools", "Information..."),
            self.iface.mainWindow())
        self.info.setObjectName("info")
        self.info.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Lists information about raster dataset"))
        QObject.connect(self.info, SIGNAL("triggered()"), self.doInfo)

        self.overview = QAction(
            QIcon(":icons/raster-overview.png"),
            QCoreApplication.translate("GdalTools",
                                       "Build Overviews (Pyramids)..."),
            self.iface.mainWindow())
        self.overview.setObjectName("overview")
        self.overview.setStatusTip(
            QCoreApplication.translate("GdalTools",
                                       "Builds or rebuilds overview images"))
        QObject.connect(self.overview, SIGNAL("triggered()"), self.doOverview)

        self.tileindex = QAction(
            QIcon(":icons/tiles.png"),
            QCoreApplication.translate("GdalTools", "Tile Index..."),
            self.iface.mainWindow())
        self.tileindex.setObjectName("tileindex")
        self.tileindex.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Build a shapefile as a raster tileindex"))
        QObject.connect(self.tileindex, SIGNAL("triggered()"),
                        self.doTileIndex)

        self.miscellaneousMenu.addActions(
            [self.merge, self.info, self.overview, self.tileindex])

        self.menu.addMenu(self.projectionsMenu)
        self.menu.addMenu(self.conversionMenu)
        self.menu.addMenu(self.extractionMenu)

        if not self.analysisMenu.isEmpty():
            self.menu.addMenu(self.analysisMenu)

        self.menu.addMenu(self.miscellaneousMenu)

        self.settings = QAction(
            QCoreApplication.translate("GdalTools", "GdalTools Settings..."),
            self.iface.mainWindow())
        self.settings.setObjectName("settings")
        self.settings.setStatusTip(
            QCoreApplication.translate("GdalTools",
                                       "Various settings for Gdal Tools"))
        QObject.connect(self.settings, SIGNAL("triggered()"), self.doSettings)
        self.menu.addAction(self.settings)

    def unload(self):
        if not valid:
            return
        pass

    def doBuildVRT(self):
        from tools.doBuildVRT import GdalToolsDialog as BuildVRT
        d = BuildVRT(self.iface)
        self.runToolDialog(d)

    def doContour(self):
        from tools.doContour import GdalToolsDialog as Contour
        d = Contour(self.iface)
        self.runToolDialog(d)

    def doRasterize(self):
        from tools.doRasterize import GdalToolsDialog as Rasterize
        d = Rasterize(self.iface)
        self.runToolDialog(d)

    def doPolygonize(self):
        from tools.doPolygonize import GdalToolsDialog as Polygonize
        d = Polygonize(self.iface)
        self.runToolDialog(d)

    def doMerge(self):
        from tools.doMerge import GdalToolsDialog as Merge
        d = Merge(self.iface)
        self.runToolDialog(d)

    def doSieve(self):
        from tools.doSieve import GdalToolsDialog as Sieve
        d = Sieve(self.iface)
        self.runToolDialog(d)

    def doProximity(self):
        from tools.doProximity import GdalToolsDialog as Proximity
        d = Proximity(self.iface)
        self.runToolDialog(d)

    def doNearBlack(self):
        from tools.doNearBlack import GdalToolsDialog as NearBlack
        d = NearBlack(self.iface)
        self.runToolDialog(d)

    def doFillNodata(self):
        from tools.doFillNodata import GdalToolsDialog as FillNodata
        d = FillNodata(self.iface)
        self.runToolDialog(d)

    def doWarp(self):
        from tools.doWarp import GdalToolsDialog as Warp
        d = Warp(self.iface)
        self.runToolDialog(d)

    def doGrid(self):
        from tools.doGrid import GdalToolsDialog as Grid
        d = Grid(self.iface)
        self.runToolDialog(d)

    def doTranslate(self):
        from tools.doTranslate import GdalToolsDialog as Translate
        d = Translate(self.iface)
        self.runToolDialog(d)

    def doInfo(self):
        from tools.doInfo import GdalToolsDialog as Info
        d = Info(self.iface)
        self.runToolDialog(d)

    def doProjection(self):
        from tools.doProjection import GdalToolsDialog as Projection
        d = Projection(self.iface)
        self.runToolDialog(d)

    def doOverview(self):
        from tools.doOverview import GdalToolsDialog as Overview
        d = Overview(self.iface)
        self.runToolDialog(d)

    def doClipper(self):
        from tools.doClipper import GdalToolsDialog as Clipper
        d = Clipper(self.iface)
        self.runToolDialog(d)

    def doPaletted(self):
        from tools.doRgbPct import GdalToolsDialog as RgbPct
        d = RgbPct(self.iface)
        self.runToolDialog(d)

    def doRGB(self):
        from tools.doPctRgb import GdalToolsDialog as PctRgb
        d = PctRgb(self.iface)
        self.runToolDialog(d)

    def doTileIndex(self):
        from tools.doTileIndex import GdalToolsDialog as TileIndex
        d = TileIndex(self.iface)
        self.runToolDialog(d)

    def doExtractProj(self):
        from tools.doExtractProj import GdalToolsDialog as ExtractProj
        d = ExtractProj(self.iface)
        d.exec_()

    def doDEM(self):
        from tools.doDEM import GdalToolsDialog as DEM
        d = DEM(self.iface)
        self.runToolDialog(d)

    def runToolDialog(self, dlg):
        dlg.show_()
        dlg.exec_()
        del dlg

    def doSettings(self):
        from tools.doSettings import GdalToolsSettingsDialog as Settings
        d = Settings(self.iface)
        d.exec_()
Example #29
0
class fToolsPlugin:
    def __init__(self, iface):
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

    def getThemeIcon(self, icon):
        settings = QSettings()
        pluginPath = os.path.dirname(__file__)
        themePath = "icons" + QDir.separator() + settings.value(
            "/Themes", "default") + QDir.separator() + icon
        defaultPath = "icons" + QDir.separator() + "default" + QDir.separator(
        ) + icon
        if QFile.exists(pluginPath + QDir.separator() + themePath):
            return QIcon(":" + themePath)
        elif QFile.exists(pluginPath + QDir.separator() + defaultPath):
            return QIcon(":" + defaultPath)
        else:
            return QIcon()

    def updateThemeIcons(self, theme):
        self.analysisMenu.setIcon(QIcon(self.getThemeIcon("analysis.png")))
        self.distMatrix.setIcon(QIcon(self.getThemeIcon("matrix.png")))
        self.sumLines.setIcon(QIcon(self.getThemeIcon("sum_lines.png")))
        self.pointsPoly.setIcon(QIcon(self.getThemeIcon("sum_points.png")))
        self.compStats.setIcon(QIcon(
            self.getThemeIcon("basic_statistics.png")))
        self.listUnique.setIcon(QIcon(self.getThemeIcon("unique.png")))
        self.nearestNeigh.setIcon(QIcon(self.getThemeIcon("neighbour.png")))
        self.meanCoords.setIcon(QIcon(self.getThemeIcon("mean.png")))
        self.intLines.setIcon(QIcon(self.getThemeIcon("intersections.png")))

        self.researchMenu.setIcon(QIcon(self.getThemeIcon("sampling.png")))
        self.randSel.setIcon(QIcon(self.getThemeIcon("random_selection.png")))
        self.randSub.setIcon(QIcon(self.getThemeIcon("sub_selection.png")))
        self.randPoints.setIcon(QIcon(self.getThemeIcon("random_points.png")))
        self.regPoints.setIcon(QIcon(self.getThemeIcon("regular_points.png")))
        self.vectGrid.setIcon(QIcon(self.getThemeIcon("vector_grid.png")))
        self.selectLocation.setIcon(
            QIcon(self.getThemeIcon("select_location.png")))
        self.layerExtent.setIcon(QIcon(self.getThemeIcon("layer_extent.png")))

        self.geoMenu.setIcon(QIcon(self.getThemeIcon("geoprocessing.png")))
        self.minConvex.setIcon(QIcon(self.getThemeIcon("convex_hull.png")))
        self.dynaBuffer.setIcon(QIcon(self.getThemeIcon("buffer.png")))
        self.intersect.setIcon(QIcon(self.getThemeIcon("intersect.png")))
        self.union.setIcon(QIcon(self.getThemeIcon("union.png")))
        self.symDifference.setIcon(
            QIcon(self.getThemeIcon("sym_difference.png")))
        self.clip.setIcon(QIcon(self.getThemeIcon("clip.png")))
        self.dissolve.setIcon(QIcon(self.getThemeIcon("dissolve.png")))
        self.erase.setIcon(QIcon(self.getThemeIcon("difference.png")))
        self.eliminate.setIcon(QIcon(self.getThemeIcon("eliminate.png")))

        self.conversionMenu.setIcon(QIcon(self.getThemeIcon("geometry.png")))
        self.compGeo.setIcon(QIcon(self.getThemeIcon("export_geometry.png")))
        self.checkGeom.setIcon(QIcon(self.getThemeIcon("check_geometry.png")))
        self.centroids.setIcon(QIcon(self.getThemeIcon("centroids.png")))
        self.delaunay.setIcon(QIcon(self.getThemeIcon("delaunay.png")))
        self.voronoi.setIcon(QIcon(self.getThemeIcon("voronoi.png")))
        self.extNodes.setIcon(QIcon(self.getThemeIcon("extract_nodes.png")))
        self.simplify.setIcon(QIcon(self.getThemeIcon("simplify.png")))
        self.densify.setIcon(QIcon(self.getThemeIcon("densify.png")))
        self.multiToSingle.setIcon(
            QIcon(self.getThemeIcon("multi_to_single.png")))
        self.singleToMulti.setIcon(
            QIcon(self.getThemeIcon("single_to_multi.png")))
        self.polysToLines.setIcon(QIcon(self.getThemeIcon("to_lines.png")))
        self.linesToPolys.setIcon(QIcon(self.getThemeIcon("to_lines.png")))

        self.dataManageMenu.setIcon(QIcon(self.getThemeIcon("management.png")))
        self.define.setIcon(QIcon(self.getThemeIcon("define_projection.png")))
        self.spatJoin.setIcon(QIcon(self.getThemeIcon("join_location.png")))
        self.splitVect.setIcon(QIcon(self.getThemeIcon("split_layer.png")))
        self.mergeShapes.setIcon(QIcon(self.getThemeIcon("merge_shapes.png")))
        self.spatialIndex.setIcon(QIcon(
            self.getThemeIcon("spatial_index.png")))

    def initGui(self):
        if int(self.QgisVersion) < 1:
            QMessageBox.warning(
                self.iface.getMainWindow(), "fTools",
                QCoreApplication.translate("fTools", "QGIS version detected: ")
                + unicode(self.QgisVersion) + ".xx\n" +
                QCoreApplication.translate(
                    "fTools",
                    "This version of fTools requires at least QGIS version 1.0.0\nPlugin will not be enabled."
                ))
            return None
        QObject.connect(self.iface, SIGNAL("currentThemeChanged (QString)"),
                        self.updateThemeIcons)

        self.analysisMenu = QMenu(
            QCoreApplication.translate("fTools", "&Analysis Tools"))
        self.analysisMenu.setObjectName("analysisMenu")
        self.distMatrix = QAction(
            QCoreApplication.translate("fTools", "Distance Matrix..."),
            self.iface.mainWindow())
        self.distMatrix.setObjectName("distMatrix")
        self.sumLines = QAction(
            QCoreApplication.translate("fTools", "Sum Line Lengths..."),
            self.iface.mainWindow())
        self.sumLines.setObjectName("sumLines")
        self.pointsPoly = QAction(
            QCoreApplication.translate("fTools", "Points in Polygon..."),
            self.iface.mainWindow())
        self.pointsPoly.setObjectName("pointsPoly")
        self.compStats = QAction(
            QCoreApplication.translate("fTools", "Basic Statistics..."),
            self.iface.mainWindow())
        self.compStats.setObjectName("compStats")
        self.listUnique = QAction(
            QCoreApplication.translate("fTools", "List Unique Values..."),
            self.iface.mainWindow())
        self.listUnique.setObjectName("listUnique")
        self.nearestNeigh = QAction(
            QCoreApplication.translate("fTools",
                                       "Nearest Neighbour Analysis..."),
            self.iface.mainWindow())
        self.nearestNeigh.setObjectName("nearestNeigh")
        self.meanCoords = QAction(
            QCoreApplication.translate("fTools", "Mean Coordinate(s)..."),
            self.iface.mainWindow())
        self.meanCoords.setObjectName("meanCoords")
        self.intLines = QAction(
            QCoreApplication.translate("fTools", "Line Intersections..."),
            self.iface.mainWindow())
        self.intLines.setObjectName("intLines")
        self.analysisMenu.addActions([
            self.distMatrix, self.sumLines, self.pointsPoly, self.listUnique,
            self.compStats, self.nearestNeigh, self.meanCoords, self.intLines
        ])

        self.researchMenu = QMenu(
            QCoreApplication.translate("fTools", "&Research Tools"))
        self.researchMenu.setObjectName("researchMenu")
        self.randSel = QAction(
            QCoreApplication.translate("fTools", "Random Selection..."),
            self.iface.mainWindow())
        self.randSel.setObjectName("randSel")
        self.randSub = QAction(
            QCoreApplication.translate("fTools",
                                       "Random Selection Within Subsets..."),
            self.iface.mainWindow())
        self.randSub.setObjectName("randSub")
        self.randPoints = QAction(
            QCoreApplication.translate("fTools", "Random Points..."),
            self.iface.mainWindow())
        self.randPoints.setObjectName("randPoints")
        self.regPoints = QAction(
            QCoreApplication.translate("fTools", "Regular Points..."),
            self.iface.mainWindow())
        self.regPoints.setObjectName("regPoints")
        self.vectGrid = QAction(
            QCoreApplication.translate("fTools", "Vector Grid..."),
            self.iface.mainWindow())
        self.vectGrid.setObjectName("vectGrid")
        self.selectLocation = QAction(
            QCoreApplication.translate("fTools", "Select by Location..."),
            self.iface.mainWindow())
        self.selectLocation.setObjectName("selectLocation")
        self.layerExtent = QAction(
            QCoreApplication.translate("fTools",
                                       "Polygon from Layer Extent..."),
            self.iface.mainWindow())
        self.layerExtent.setObjectName("layerExtent")
        self.researchMenu.addActions([
            self.randSel, self.randSub, self.randPoints, self.regPoints,
            self.vectGrid, self.selectLocation, self.layerExtent
        ])

        self.geoMenu = QMenu(
            QCoreApplication.translate("fTools", "&Geoprocessing Tools"))
        self.geoMenu.setObjectName("geoMenu")
        self.minConvex = QAction(
            QCoreApplication.translate("fTools", "Convex Hull(s)..."),
            self.iface.mainWindow())
        self.minConvex.setObjectName("minConvex")
        self.dynaBuffer = QAction(
            QCoreApplication.translate("fTools", "Buffer(s)..."),
            self.iface.mainWindow())
        self.dynaBuffer.setObjectName("dynaBuffer")
        self.intersect = QAction(
            QCoreApplication.translate("fTools", "Intersect..."),
            self.iface.mainWindow())
        self.intersect.setObjectName("intersect")
        self.union = QAction(QCoreApplication.translate("fTools", "Union..."),
                             self.iface.mainWindow())
        self.union.setObjectName("union")
        self.symDifference = QAction(
            QCoreApplication.translate("fTools", "Symetrical Difference..."),
            self.iface.mainWindow())
        self.symDifference.setObjectName("symDifference")
        self.clip = QAction(QCoreApplication.translate("fTools", "Clip..."),
                            self.iface.mainWindow())
        self.clip.setObjectName("clip")
        self.dissolve = QAction(
            QCoreApplication.translate("fTools", "Dissolve..."),
            self.iface.mainWindow())
        self.dissolve.setObjectName("dissolve")
        self.erase = QAction(
            QCoreApplication.translate("fTools", "Difference..."),
            self.iface.mainWindow())
        self.erase.setObjectName("erase")
        self.eliminate = QAction(
            QCoreApplication.translate("fTools",
                                       "Eliminate Sliver Polygons..."),
            self.iface.mainWindow())
        self.eliminate.setObjectName("eliminate")
        self.geoMenu.addActions([
            self.minConvex, self.dynaBuffer, self.intersect, self.union,
            self.symDifference, self.clip, self.erase, self.dissolve,
            self.eliminate
        ])

        self.conversionMenu = QMenu(
            QCoreApplication.translate("fTools", "G&eometry Tools"))
        self.conversionMenu.setObjectName("conversionMenu")
        self.compGeo = QAction(
            QCoreApplication.translate("fTools",
                                       "Export/Add Geometry Columns..."),
            self.iface.mainWindow())
        self.compGeo.setObjectName("compGeo")
        self.checkGeom = QAction(
            QCoreApplication.translate("fTools", "Check Geometry Validity..."),
            self.iface.mainWindow())
        self.checkGeom.setObjectName("checkGeom")
        self.centroids = QAction(
            QCoreApplication.translate("fTools", "Polygon Centroids..."),
            self.iface.mainWindow())
        self.centroids.setObjectName("centroids")
        self.delaunay = QAction(
            QCoreApplication.translate("fTools", "Delaunay Triangulation..."),
            self.iface.mainWindow())
        self.delaunay.setObjectName("delaunay")
        self.voronoi = QAction(
            QCoreApplication.translate("fTools", "Voronoi Polygons..."),
            self.iface.mainWindow())
        self.voronoi.setObjectName("voronoi")
        self.extNodes = QAction(
            QCoreApplication.translate("fTools", "Extract Nodes..."),
            self.iface.mainWindow())
        self.extNodes.setObjectName("extNodes")
        self.simplify = QAction(
            QCoreApplication.translate("fTools", "Simplify Geometries..."),
            self.iface.mainWindow())
        self.simplify.setObjectName("simplify")
        self.densify = QAction(
            QCoreApplication.translate("fTools", "Densify Geometries..."),
            self.iface.mainWindow())
        self.densify.setObjectName("densify")
        self.multiToSingle = QAction(
            QCoreApplication.translate("fTools",
                                       "Multipart to Singleparts..."),
            self.iface.mainWindow())
        self.multiToSingle.setObjectName("multiToSingle")
        self.singleToMulti = QAction(
            QCoreApplication.translate("fTools",
                                       "Singleparts to Multipart..."),
            self.iface.mainWindow())
        self.singleToMulti.setObjectName("singleToMulti")
        self.polysToLines = QAction(
            QCoreApplication.translate("fTools", "Polygons to Lines..."),
            self.iface.mainWindow())
        self.polysToLines.setObjectName("polysToLines")
        self.linesToPolys = QAction(
            QCoreApplication.translate("fTools", "Lines to Polygons..."),
            self.iface.mainWindow())
        self.linesToPolys.setObjectName("linesToPolys")
        self.conversionMenu.addActions([
            self.checkGeom, self.compGeo, self.centroids, self.delaunay,
            self.voronoi, self.simplify, self.densify, self.multiToSingle,
            self.singleToMulti, self.polysToLines, self.linesToPolys,
            self.extNodes
        ])

        self.dataManageMenu = QMenu(
            QCoreApplication.translate("fTools", "&Data Management Tools"))
        self.dataManageMenu.setObjectName("dataManageMenu")
        self.define = QAction(
            QCoreApplication.translate("fTools",
                                       "Define Current Projection..."),
            self.iface.mainWindow())
        self.define.setObjectName("define")
        self.spatJoin = QAction(
            QCoreApplication.translate("fTools",
                                       "Join Attributes by Location..."),
            self.iface.mainWindow())
        self.spatJoin.setObjectName("spatJoin")
        self.splitVect = QAction(
            QCoreApplication.translate("fTools", "Split Vector Layer..."),
            self.iface.mainWindow())
        self.splitVect.setObjectName("splitVect")
        self.mergeShapes = QAction(
            QCoreApplication.translate("fTools", "Merge Shapefiles to One..."),
            self.iface.mainWindow())
        self.mergeShapes.setObjectName("mergeShapes")
        self.spatialIndex = QAction(
            QCoreApplication.translate("fTools", "Create Spatial Index..."),
            self.iface.mainWindow())
        self.spatialIndex.setObjectName("spatialIndex")
        self.dataManageMenu.addActions([
            self.define, self.spatJoin, self.splitVect, self.mergeShapes,
            self.spatialIndex
        ])

        self.updateThemeIcons("theme")

        self.menu = self.iface.vectorMenu()
        self.menu.addMenu(self.analysisMenu)
        self.menu.addMenu(self.researchMenu)
        self.menu.addMenu(self.geoMenu)
        self.menu.addMenu(self.conversionMenu)
        self.menu.addMenu(self.dataManageMenu)

        QObject.connect(self.distMatrix, SIGNAL("triggered()"),
                        self.dodistMatrix)
        QObject.connect(self.sumLines, SIGNAL("triggered()"), self.dosumLines)
        QObject.connect(self.pointsPoly, SIGNAL("triggered()"),
                        self.dopointsPoly)
        QObject.connect(self.compStats, SIGNAL("triggered()"),
                        self.docompStats)
        QObject.connect(self.listUnique, SIGNAL("triggered()"),
                        self.dolistUnique)
        QObject.connect(self.nearestNeigh, SIGNAL("triggered()"),
                        self.donearestNeigh)
        QObject.connect(self.meanCoords, SIGNAL("triggered()"),
                        self.domeanCoords)
        QObject.connect(self.intLines, SIGNAL("triggered()"), self.dointLines)

        QObject.connect(self.randSel, SIGNAL("triggered()"), self.dorandSel)
        QObject.connect(self.randSub, SIGNAL("triggered()"), self.dorandSub)
        QObject.connect(self.randPoints, SIGNAL("triggered()"),
                        self.dorandPoints)
        QObject.connect(self.regPoints, SIGNAL("triggered()"),
                        self.doregPoints)
        QObject.connect(self.vectGrid, SIGNAL("triggered()"), self.dovectGrid)
        QObject.connect(self.selectLocation, SIGNAL("triggered()"),
                        self.doselectLocation)
        QObject.connect(self.layerExtent, SIGNAL("triggered()"), self.doextent)

        QObject.connect(self.minConvex, SIGNAL("triggered()"),
                        self.dominConvex)
        QObject.connect(self.intersect, SIGNAL("triggered()"),
                        self.dointersect)
        QObject.connect(self.dissolve, SIGNAL("triggered()"), self.dodissolve)
        QObject.connect(self.symDifference, SIGNAL("triggered()"),
                        self.dosymdifference)
        QObject.connect(self.erase, SIGNAL("triggered()"), self.doerase)
        QObject.connect(self.union, SIGNAL("triggered()"), self.dounion)
        QObject.connect(self.clip, SIGNAL("triggered()"), self.doclip)
        QObject.connect(self.dynaBuffer, SIGNAL("triggered()"),
                        self.dodynaBuffer)
        QObject.connect(self.eliminate, SIGNAL("triggered()"),
                        self.doEliminate)

        QObject.connect(self.multiToSingle, SIGNAL("triggered()"),
                        self.domultiToSingle)
        QObject.connect(self.singleToMulti, SIGNAL("triggered()"),
                        self.dosingleToMulti)
        QObject.connect(self.checkGeom, SIGNAL("triggered()"),
                        self.docheckGeom)
        QObject.connect(self.simplify, SIGNAL("triggered()"), self.doSimplify)
        QObject.connect(self.densify, SIGNAL("triggered()"), self.doDensify)
        QObject.connect(self.centroids, SIGNAL("triggered()"),
                        self.docentroids)
        QObject.connect(self.delaunay, SIGNAL("triggered()"), self.dodelaunay)
        QObject.connect(self.voronoi, SIGNAL("triggered()"), self.dovoronoi)
        QObject.connect(self.polysToLines, SIGNAL("triggered()"),
                        self.dopolysToLines)
        QObject.connect(self.linesToPolys, SIGNAL("triggered()"),
                        self.dolinesToPolys)
        QObject.connect(self.compGeo, SIGNAL("triggered()"), self.docompGeo)
        QObject.connect(self.extNodes, SIGNAL("triggered()"), self.doextNodes)

        QObject.connect(self.define, SIGNAL("triggered()"), self.dodefine)
        QObject.connect(self.spatJoin, SIGNAL("triggered()"), self.dospatJoin)
        QObject.connect(self.splitVect, SIGNAL("triggered()"),
                        self.dosplitVect)
        QObject.connect(self.mergeShapes, SIGNAL("triggered()"),
                        self.doMergeShapes)
        QObject.connect(self.spatialIndex, SIGNAL("triggered()"),
                        self.doSpatIndex)

    def unload(self):
        self.menu.removeAction(self.analysisMenu.menuAction())
        self.menu.removeAction(self.researchMenu.menuAction())
        self.menu.removeAction(self.geoMenu.menuAction())
        self.menu.removeAction(self.conversionMenu.menuAction())
        self.menu.removeAction(self.dataManageMenu.menuAction())

    def doSimplify(self):
        d = doSimplify.Dialog(self.iface, 1)
        d.show()
        d.exec_()

    def doDensify(self):
        d = doSimplify.Dialog(self.iface, 2)
        d.show()
        d.exec_()

    def dopolysToLines(self):
        d = doGeometry.GeometryDialog(self.iface, 4)
        d.exec_()

    def dolinesToPolys(self):
        d = doGeometry.GeometryDialog(self.iface, 11)
        d.exec_()

    def docheckGeom(self):
        d = doValidate.ValidateDialog(self.iface)
        d.show()
        d.exec_()

    def domultiToSingle(self):
        d = doGeometry.GeometryDialog(self.iface, 2)
        d.exec_()

    def dosingleToMulti(self):
        d = doGeometry.GeometryDialog(self.iface, 1)
        d.exec_()

    def doselectLocation(self):
        d = doSelectByLocation.Dialog(self.iface)
        d.exec_()

    def domeanCoords(self):
        d = doMeanCoords.Dialog(self.iface, 1)
        d.exec_()

    def dominConvex(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 2)
        d.exec_()

    def dodynaBuffer(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 1)
        d.exec_()

    def dointersect(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 5)
        d.exec_()

    def dodissolve(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 4)
        d.exec_()

    def doerase(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 3)
        d.exec_()

    def dosymdifference(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 7)
        d.exec_()

    def dounion(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 6)
        d.exec_()

    def doclip(self):
        d = doGeoprocessing.GeoprocessingDialog(self.iface, 8)
        d.exec_()

    def donearestNeigh(self):
        d = doVisual.VisualDialog(self.iface, 4)
        d.exec_()

    def dodistMatrix(self):
        d = doPointDistance.Dialog(self.iface)
        d.exec_()

    def docentroids(self):
        d = doGeometry.GeometryDialog(self.iface, 7)
        d.exec_()

    def dodelaunay(self):
        d = doGeometry.GeometryDialog(self.iface, 8)
        d.exec_()

    def dovoronoi(self):
        d = doGeometry.GeometryDialog(self.iface, 10)
        d.exec_()

    def doextent(self):
        d = doGeometry.GeometryDialog(self.iface, 9)
        d.exec_()

    def dosumLines(self):
        d = doSumLines.Dialog(self.iface)
        d.exec_()

    def dopointsPoly(self):
        d = doPointsInPolygon.Dialog(self.iface)
        d.show()
        d.exec_()

    def dorandSel(self):
        d = doRandom.Dialog(self.iface)
        d.exec_()

    def dorandSub(self):
        d = doSubsetSelect.Dialog(self.iface)
        d.exec_()

    def dorandPoints(self):
        d = doRandPoints.Dialog(self.iface)
        d.exec_()

    def doregPoints(self):
        d = doRegPoints.Dialog(self.iface)
        d.exec_()

    def dovectGrid(self):
        d = doVectorGrid.Dialog(self.iface)
        d.exec_()

    def doextNodes(self):
        d = doGeometry.GeometryDialog(self.iface, 3)
        d.exec_()

    def dointLines(self):
        d = doIntersectLines.Dialog(self.iface)
        d.exec_()

    def dosplitVect(self):
        d = doVectorSplit.Dialog(self.iface)
        d.show()
        d.exec_()

    def docompGeo(self):
        d = doGeometry.GeometryDialog(self.iface, 5)
        d.exec_()

    def dolistUnique(self):
        d = doVisual.VisualDialog(self.iface, 2)
        d.exec_()

    def docompStats(self):
        d = doVisual.VisualDialog(self.iface, 3)
        d.exec_()

    def dodefine(self):
        d = doDefineProj.Dialog(self.iface)
        d.exec_()

    def dospatJoin(self):
        d = doSpatialJoin.Dialog(self.iface)
        d.exec_()

    def doMergeShapes(self):
        d = doMergeShapes.Dialog(self.iface)
        d.show()
        d.exec_()

    def doSpatIndex(self):
        d = doSpatialIndex.Dialog(self.iface)
        d.show()
        d.exec_()

    def doEliminate(self):
        d = doEliminate.Dialog(self.iface)
        d.exec_()
Example #30
0
class RECS:
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'RECS_HOME_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.initdlg = InitTaskDialog()
        self.selectdlg = SelectTaskDialog()
        self.loginDlg = LogInDialog()
        self.taskMgrDlg = TaskManagerDialog()
        self.taskInfoDlg = taskInfo()
        self.taskFeaturesDlg = taskFeatures()
        #self.loadmapDlg=LoadMapDialog()
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Task')
        self.logIn()
        self.selectTask()
        self.actions = []

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

        # layer.editingStarted.connect(editLayer() )

        # TODO: We are going to let the user set this up in a future iteration
        #self.toolbar = self.iface.addToolBar(u'SelectTask')
        #self.toolbar.setObjectName(u'SelectTask')

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Tasks', message)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            # self.menu = QMenu( "&Task", self.iface.mainWindow().menuBar() )
            action = self.iface.mainWindow().menuBar().actions()
            lastAction = action[-1]
            self.iface.addPluginToMenu(self.menu, lastAction)

        self.actions.append(lastAction)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        """ Task menu setting """
        self.menu = QMenu(self.iface.mainWindow())
        self.menu.setObjectName("task_menu_object")
        self.menu.setTitle("Task")
        """ Task """
        self.action_tasks = QAction(QIcon('::/plugins/RECS/aacadisicon.png'),
                                    "Tasks", self.iface.mainWindow())
        self.action_tasks.setObjectName("Task_action_object")
        self.action_tasks.setWhatsThis("Task Initialized")
        #QtCore.QObject.connect(self.action_tasks, SIGNAL("triggered()"), self.tasks)
        """ Initializing Task """
        self.action_init_task = QAction(
            QIcon('::/plugins/RECS/aacadisicon.png'), "Initialize ",
            self.iface.mainWindow())
        self.action_init_task.setObjectName("Task_action_object")
        self.action_init_task.setWhatsThis("Task Initialize")
        QtCore.QObject.connect(self.action_init_task, SIGNAL("triggered()"),
                               self.initTask)
        """ Select Task """
        self.action_select_task = QAction(
            QIcon(':/plugins/RECS/aacadisicon.png'), "Select Task",
            self.iface.mainWindow())
        self.action_select_task.setObjectName("Task_Select_object")
        self.action_select_task.setWhatsThis("Select Task")
        QtCore.QObject.connect(self.action_select_task, SIGNAL("triggered()"),
                               self.selectTask)
        """ Reload Task """
        self.action_reload_task = QAction(
            QIcon(':/plugins/RECS/aacadisicon.png'), "Reload Task",
            self.iface.mainWindow())
        self.action_reload_task.setObjectName("Task_Reload_object")
        self.action_reload_task.setWhatsThis("Reload Task")
        QtCore.QObject.connect(self.action_reload_task, SIGNAL("triggered()"),
                               self.taskManager)
        """ Edit Task """
        self.action_edit_task = QAction(
            QIcon(':/plugins/RECS/aacadisicon.png'), "Edit Task",
            self.iface.mainWindow())
        self.action_edit_task.setObjectName("Task_Edit_object")
        self.action_edit_task.setWhatsThis("Edit Task")
        QtCore.QObject.connect(self.action_edit_task, SIGNAL("triggered()"),
                               self.editLayer)
        """ Finish Task """
        self.action_finish_task = QAction(
            QIcon(':/plugins/RECS/aacadisicon.png'), "Finish Task",
            self.iface.mainWindow())
        self.action_finish_task.setObjectName("Task_Finish_object")
        self.action_finish_task.setWhatsThis("Edit Task")
        QtCore.QObject.connect(self.action_finish_task, SIGNAL("triggered()"),
                               self.finishEditngLayer)
        """ Add action to the menu list """
        #self.menuTask.addAction(self.action_tasks)

        self.menu.addAction(self.action_init_task)
        self.menu.addAction(self.action_select_task)
        self.menu.addAction(self.action_reload_task)
        self.menu.addAction(self.action_edit_task)
        self.menu.addAction(self.action_finish_task)
        """ Add menu to the menubar """
        menubar = self.iface.mainWindow().menuBar()
        menubar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),
                           self.menu)
        """ Add icon to the toolbar """
        #self.iface.addPluginToMenu(u"&load Map", self.action_loadmap)
        #self.iface.addToolBarIcon(self.action_init_task)

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

    def initTask(self):

        layers = self.iface.legendInterface().layers()
        #layer_list = []
        for layer in layers:
            #layer_list.append(layer.name())
            if layer.name() == 'PARCEL':
                self.iface.setActiveLayer(layer)
        self.initdlg.show()
        #layer_list=list(set(layer_list))
        #self.initdlg.comboBox.addItems(layer_list)
        self.initdlg.setFixedSize(self.initdlg.size())
        result = self.initdlg.exec_()
        if result:
            pass

    def selectTask(self):
        self.selectdlg.show()
        self.selectdlg.setFixedSize(self.selectdlg.size())

        self.selectdlg.loadLayer()
        self.selectdlg.populate()
        result = self.selectdlg.exec_()
        if result:
            # self.selectdlg.close()
            pass

    def showTaskInfo(self):
        self.taskInfoDlg.show()
        t_id = self.taskMgrDlg.retTaskID()
        self.taskInfoDlg.getAttribData(t_id)
        #self.taskInfoDlg.populate()
    def taskManager(self):

        if self.taskMgrDlg.isVisible():
            self.taskMgrDlg.loadTaskClicked()
            # self.taskMgrDlg.close()
            # self.apdockwidget.close()
        else:
            self.taskMgrDlg.show()
            self.apdockwidget = QDockWidget("Task Manager",
                                            self.iface.mainWindow())
            self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint)
            self.apdockwidget.setWidget(self.taskMgrDlg)
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget)
            self.taskMgrDlg.populate()
            self.taskFeatures()

        # rows = self.taskMgrDlg.taskListTable.rowCount()
        # createdByList=[]
        #
        #
        # for row in range(0,rows):
        #     createdByItems=self.taskMgrDlg.taskListTable.item(row,1)
        #     createdByList.append(createdByItems.text())
        #
        #
        # createdByList=list(set(createdByList))
        # self.taskMgrDlg.createByComboBox.addItems(createdByList)
        # self.taskMgrDlg.createByComboBox.setCurrentIndex(createdByList.index())
        self.menu = QtGui.QMenu()
        #newTask=self.menu.addAction("New Task",self.newTask,"")
        newTask = self.menu.addAction("New Task", self.newTaskEvent)
        loadTask = self.menu.addAction("Load Task", self.loadTaskEvent)
        cancelTask = self.menu.addAction("Cancel Task", self.cancelTaskEvent)
        showTaskArea = self.menu.addAction("Show Task Area",
                                           self.showTaskAreaEvent)
        noTask = self.menu.addAction("No Task", self.noTaskEvent)
        showTaskInfo = self.menu.addAction("Show Task Info",
                                           self.showTaskInfoEvent)
        updateFeature = self.menu.addAction("Update Features",
                                            self.updateFeatureEvent)

        self.taskMgrDlg.taskListTable.addAction(newTask)
        self.taskMgrDlg.taskListTable.addAction(loadTask)
        self.taskMgrDlg.taskListTable.addAction(cancelTask)
        self.taskMgrDlg.taskListTable.addAction(showTaskArea)
        self.taskMgrDlg.taskListTable.addAction(noTask)
        self.taskMgrDlg.taskListTable.addAction(showTaskInfo)
        self.taskMgrDlg.taskListTable.addAction(updateFeature)
        self.taskMgrDlg.taskListTable.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.taskMgrDlg.taskListTable.customContextMenuRequested.connect(
            self.contextMenuEvent)
        result = self.taskMgrDlg.exec_()
        if result:
            self.taskMgrDlg.populate()
        #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange
    def contextMenuEvent(self, point):
        self.menu.exec_(self.taskMgrDlg.taskListTable.mapToGlobal(point))

    def newTaskEvent(self):
        self.initTask()

    def loadTaskEvent(self):
        self.taskMgrDlg.loadTaskClicked()
        t_id = self.taskMgrDlg.retTaskID()
        self.taskFeaturesDlg.populate(t_id)

    def cancelTaskEvent(self):
        self.taskMgrDlg.cancelTask()

    def showTaskAreaEvent(self):
        self.taskMgrDlg.showTaskAreaClicked()

    def noTaskEvent(self):
        print "noTask Called"

    def showTaskInfoEvent(self):
        self.showTaskInfo()

    def updateFeatureEvent(self):
        print "updateFeature"

    def logIn(self):

        self.loginDlg.show()
        self.loginDlg.setWindowFlags(Qt.FramelessWindowHint)
        result = self.loginDlg.exec_()
        if result:
            pass

    def loadLayer(self):
        self.mlr = None
        # QgsMapLayerRegistry.instance().removeAllMapLayers()
        self.mlr = QgsMapLayerRegistry.instance()
        uri = QgsDataSourceURI()
        uri.setConnection("172.20.0.71", "5432", "ncrprs_db", "postgres",
                          "123456")
        uri.setDataSource("recs", "t_parcel", "parcelgeometry", "")
        vlayer = QgsVectorLayer(uri.uri(), "Parcel", "postgres")
        if vlayer.isValid():
            self.mlr.addMapLayer(vlayer)
        else:
            QMessageBox.information(
                None, "Unable to Laod Data",
                "Unable to Load Layers from the Database!")
            return None

    def editLayer(self):
        global taskLayer
        global featCount
        layers = self.iface.legendInterface().layers()
        for layer in layers:
            if layer.name() == 'TaskLayer':
                taskLayer = layer
                taskLayerID = layer.id()
                self.iface.setActiveLayer(taskLayer)
        featCount = taskLayer.featureCount()
        print featCount
        taskLayer.startEditing()
        QgsProject.instance().setSnapSettingsForLayer(taskLayerID, True, 2, 1,
                                                      20, True)

    def finishEditngLayer(self):
        """
        change the edits to GML again to detect the changes

        """
        print featCount
        taskLayer_shape = iface.activeLayer()
        QgsVectorFileWriter.writeAsVectorFormat(taskLayer_shape,
                                                "Z:\\GMLEdited\\temp.gml",
                                                "utf-8", None, "GML")

        #QgsMapLayerRegistry.instance().removeAllMapLayers()
        iface.addVectorLayer("Z:\\GMLEdited\\temp.gml", "EditedTaskLayer",
                             "ogr")
        """
        Compare the two gml geometries
        """

        doc_edited = xml.dom.minidom.parse("Z:\\GMLEdited\\temp.gml")
        doc_origion = xml.dom.minidom.parse("Z:\\GMLFile\\ogrGML.gml")
        editedParcel = doc_edited.getElementsByTagName("gml:featureMember")
        epLength = editedParcel.length
        print epLength
        obj = GeometryEdit()
        if epLength > featCount:
            obj.split(doc_edited, doc_origion)
            print "split"
        elif epLength < featCount:
            obj.merge(doc_edited, doc_origion)
            print "merge"
        else:
            obj.updateGeom()
            print "update"

    def taskFeatures(self):
        self.taskFeaturesDlg.show()
        self.apdockwidget = QDockWidget("Features Of Current Task",
                                        self.iface.mainWindow())
        self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint)
        self.apdockwidget.setWidget(self.taskFeaturesDlg)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget)

        self.menu_feature = QtGui.QMenu()
        #newTask=self.menu.addAction("New Task",self.newTask,"")
        editAttr = self.menu_feature.addAction("Edit", self.editEvent)
        self.taskFeaturesDlg.currentTaskTable.addAction(editAttr)
        self.taskFeaturesDlg.currentTaskTable.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.taskFeaturesDlg.currentTaskTable.customContextMenuRequested.connect(
            self.contextMenuEvent2)

        #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange
    def contextMenuEvent2(self, point):
        self.menu_feature.exec_(
            self.taskFeaturesDlg.currentTaskTable.mapToGlobal(point))

    def editEvent(self):
        self.showTaskInfo()
Example #31
0
class ProcessingPlugin:
    def __init__(self, iface):
        self.iface = iface

    def initGui(self):
        Processing.initialize()

        self.commander = None
        self.toolbox = ProcessingToolbox()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        Processing.addAlgListListener(self.toolbox)

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName('processing')
        self.menu.setTitle(self.tr('Pro&cessing'))

        self.toolboxAction = self.toolbox.toggleViewAction()
        self.toolboxAction.setObjectName('toolboxAction')
        self.toolboxAction.setIcon(
            QIcon(os.path.join(cmd_folder, 'images', 'alg.png')))
        self.toolboxAction.setText(self.tr('&Toolbox'))
        self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T')
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'model.png')),
            self.tr('Graphical &Modeler...'), self.iface.mainWindow())
        self.modelerAction.setObjectName('modelerAction')
        self.modelerAction.triggered.connect(self.openModeler)
        self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M')
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'history.gif')),
            self.tr('&History...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H')
        self.menu.addAction(self.historyAction)

        self.configAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'config.png')),
            self.tr('&Options...'), self.iface.mainWindow())
        self.configAction.setObjectName('configAction')
        self.configAction.triggered.connect(self.openConfig)
        self.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C')
        self.menu.addAction(self.configAction)

        self.resultsAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'results.png')),
            self.tr('&Results Viewer...'), self.iface.mainWindow())
        self.resultsAction.setObjectName('resultsAction')
        self.resultsAction.triggered.connect(self.openResults)
        self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R')
        self.menu.addAction(self.resultsAction)

        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),
                           self.menu)

        self.commanderAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'commander.png')),
            self.tr('&Commander'), self.iface.mainWindow())
        self.commanderAction.setObjectName('commanderAction')
        self.commanderAction.triggered.connect(self.openCommander)
        self.menu.addAction(self.commanderAction)
        self.iface.registerMainWindowAction(self.commanderAction,
                                            self.tr('Ctrl+Alt+M'))

    def unload(self):
        self.toolbox.setVisible(False)
        self.menu.deleteLater()

        # delete temporary output files
        folder = tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.commanderAction)

    def openCommander(self):
        if self.commander is None:
            self.commander = CommanderWindow(self.iface.mainWindow(),
                                             self.iface.mapCanvas())
            Processing.addAlgListListener(self.commander)
        self.commander.prepareGui()
        self.commander.show()

    def openToolbox(self):
        if self.toolbox.isVisible():
            self.toolbox.hide()
        else:
            self.toolbox.show()

    def openModeler(self):
        dlg = ModelerDialog()
        dlg.show()
        dlg.exec_()
        if dlg.update:
            self.toolbox.updateProvider('model')

    def openResults(self):
        dlg = ResultsDialog()
        dlg.show()
        dlg.exec_()

    def openHistory(self):
        dlg = HistoryDialog()
        dlg.exec_()

    def openConfig(self):
        dlg = ConfigDialog(self.toolbox)
        dlg.exec_()

    def tr(self, message):
        return QCoreApplication.translate('ProcessingPlugin', message)
Example #32
0
class VolumeEditorWidget(QWidget):
    def __init__(self, parent=None, editor=None):
        super(VolumeEditorWidget, self).__init__(parent=parent)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setFocusPolicy(Qt.StrongFocus)

        self.editor = None
        if editor != None:
            self.init(editor)

        self._viewMenu = None

        self.allZoomToFit = QAction(QIcon(":/icons/icons/view-fullscreen.png"),
                                    "Zoom to &Fit", self)
        self.allZoomToFit.triggered.connect(self._fitToScreen)

        self.allToggleHUD = QAction(QIcon(), "Show &HUDs", self)
        self.allToggleHUD.setCheckable(True)
        self.allToggleHUD.setChecked(True)
        self.allToggleHUD.toggled.connect(self._toggleHUDs)

        self.allCenter = QAction(QIcon(), "&Center views", self)
        self.allCenter.triggered.connect(self._centerAllImages)

        self.selectedCenter = QAction(QIcon(), "C&enter view", self)
        self.selectedCenter.triggered.connect(self._centerImage)

        self.selectedZoomToFit = QAction(
            QIcon(":/icons/icons/view-fullscreen.png"), "Zoom to Fit", self)
        self.selectedZoomToFit.triggered.connect(self._fitImage)

        self.selectedZoomToOriginal = QAction(QIcon(), "Reset Zoom", self)
        self.selectedZoomToOriginal.triggered.connect(
            self._restoreImageToOriginalSize)

        self.rubberBandZoom = QAction(QIcon(), "Rubberband Zoom", self)
        self.rubberBandZoom.triggered.connect(self._rubberBandZoom)

        self.toggleSelectedHUD = QAction(QIcon(), "Show HUD", self)
        self.toggleSelectedHUD.setCheckable(True)
        self.toggleSelectedHUD.setChecked(True)
        self.toggleSelectedHUD.toggled.connect(self._toggleSelectedHud)

    def _setupVolumeExtent(self):
        '''Setup min/max values of position/coordinate control elements.

        Position/coordinate information is read from the volumeEditor's positionModel.

        '''
        maxTime = self.editor.posModel.shape5D[0] - 1
        self.quadview.statusBar.timeLabel.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setHidden(maxTime == 0)
        self.quadview.statusBar.timeSpinBox.setRange(0, maxTime)
        self.quadview.statusBar.timeSpinBox.setSuffix("/{}".format(maxTime))

        for i in range(3):
            self.editor.imageViews[i].hud.setMaximum(
                self.editor.posModel.volumeExtent(i) - 1)

    def init(self, volumina):
        self.editor = volumina

        self.hudsShown = [True] * 3

        def onViewFocused():
            axis = self.editor._lastImageViewFocus
            self.toggleSelectedHUD.setChecked(
                self.editor.imageViews[axis]._hud.isVisible())

        self.editor.newImageView2DFocus.connect(onViewFocused)

        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.setLayout(self.layout)

        # setup quadview
        axisLabels = ["X", "Y", "Z"]
        axisColors = [QColor("#dc143c"), QColor("green"), QColor("blue")]
        for i, v in enumerate(self.editor.imageViews):
            v.hud = ImageView2DHud(v)
            #connect interpreter
            v.hud.createImageView2DHud(axisLabels[i], 0, axisColors[i],
                                       QColor("white"))
            v.hud.sliceSelector.valueChanged.connect(
                partial(self.editor.navCtrl.changeSliceAbsolute, axis=i))

        self.quadview = QuadView(self, self.editor.imageViews[2],
                                 self.editor.imageViews[0],
                                 self.editor.imageViews[1], self.editor.view3d)
        self.quadview.installEventFilter(self)
        self.quadViewStatusBar = QuadStatusBar()
        self.quadViewStatusBar.createQuadViewStatusBar(QColor("#dc143c"),
                                                       QColor("white"),
                                                       QColor("green"),
                                                       QColor("white"),
                                                       QColor("blue"),
                                                       QColor("white"))
        self.quadview.addStatusBar(self.quadViewStatusBar)
        self.layout.addWidget(self.quadview)

        ## Why do we have to prevent TimerEvents reaching the SpinBoxes?
        #
        # Sometimes clicking a SpinBox once caused the value to increase by
        # two. This is why:
        #
        # When a MouseClicked event is received by the SpinBox it fires a timerevent to control
        # the repeated increase of the value as long as the mouse button is pressed. The timer
        # is killed when it receives a MouseRelease event. If a slot connected to the valueChanged
        # signal of the SpinBox takes to long to process the signal the mouse release
        # and timer events get queued up and sometimes the timer event reaches the widget before
        # the mouse release event. That's why it increases the value by another step. To prevent
        # this we are blocking the timer events at the cost of no autorepeat anymore.
        #
        # See also:
        # http://lists.trolltech.com/qt-interest/2002-04/thread00137-0.html
        # http://www.qtcentre.org/threads/43078-QSpinBox-Timer-Issue
        # http://qt.gitorious.org/qt/qt/blobs/4.8/src/gui/widgets/qabstractspinbox.cpp#line1195
        self.quadview.statusBar.timeSpinBox.installEventFilter(_timerEater)

        def setTime(t):
            if t == self.editor.posModel.time:
                return
            self.editor.posModel.time = t

        self.quadview.statusBar.timeSpinBox.valueChanged.connect(setTime)

        def getTime(newT):
            self.quadview.statusBar.timeSpinBox.setValue(newT)

        self.editor.posModel.timeChanged.connect(getTime)

        def toggleSliceIntersection(state):
            self.editor.navCtrl.indicateSliceIntersection = (
                state == Qt.Checked)

        self.quadview.statusBar.positionCheckBox.stateChanged.connect(
            toggleSliceIntersection)

        self.editor.posModel.cursorPositionChanged.connect(
            self._updateInfoLabels)

        def onShapeChanged():
            singletonDims = filter(
                lambda (i, dim): dim == 1,
                enumerate(self.editor.posModel.shape5D[1:4]))
            if len(singletonDims) == 1:
                # Maximize the slicing view for this axis
                axis = singletonDims[0][0]
                self.quadview.ensureMaximized(axis)
                self.hudsShown[axis] = self.editor.imageViews[axis].hudVisible(
                )
                self.editor.imageViews[axis].setHudVisible(False)
                self.quadViewStatusBar.showXYCoordinates()

                self.quadview.statusBar.positionCheckBox.setVisible(False)
            else:
                self.quadViewStatusBar.showXYZCoordinates()
                for i in range(3):
                    self.editor.imageViews[i].setHudVisible(self.hudsShown[i])
                self.quadview.statusBar.positionCheckBox.setVisible(True)

            self._setupVolumeExtent()

        self.editor.shapeChanged.connect(onShapeChanged)

        self.updateGeometry()
        self.update()
        self.quadview.update()

        # shortcuts
        self._initShortcuts()

    def _toggleDebugPatches(self, show):
        self.editor.showDebugPatches = show

    def _fitToScreen(self):
        shape = self.editor.posModel.shape
        for i, v in enumerate(self.editor.imageViews):
            s = list(copy.copy(shape))
            del s[i]
            v.changeViewPort(v.scene().data2scene.mapRect(QRectF(0, 0, *s)))

    def _fitImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].fitImage()

    def _restoreImageToOriginalSize(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()

    def _rubberBandZoom(self):
        if self.editor._lastImageViewFocus is not None:
            if not self.editor.imageViews[
                    self.editor._lastImageViewFocus]._isRubberBandZoom:
                self.editor.imageViews[
                    self.editor._lastImageViewFocus]._isRubberBandZoom = True
                self.editor.imageViews[
                    self.editor.
                    _lastImageViewFocus]._cursorBackup = self.editor.imageViews[
                        self.editor._lastImageViewFocus].cursor()
                self.editor.imageViews[
                    self.editor._lastImageViewFocus].setCursor(Qt.CrossCursor)
            else:
                self.editor.imageViews[
                    self.editor._lastImageViewFocus]._isRubberBandZoom = False
                self.editor.imageViews[
                    self.editor._lastImageViewFocus].setCursor(
                        self.editor.imageViews[
                            self.editor._lastImageViewFocus]._cursorBackup)

    def _toggleHUDs(self, checked):
        for v in self.editor.imageViews:
            v.setHudVisible(checked)

    def _toggleSelectedHud(self, checked):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[
                self.editor._lastImageViewFocus].setHudVisible(checked)

    def _centerAllImages(self):
        for v in self.editor.imageViews:
            v.centerImage()

    def _centerImage(self):
        if self.editor._lastImageViewFocus is not None:
            self.editor.imageViews[
                self.editor._lastImageViewFocus].centerImage()

    def _shortcutHelper(self,
                        keySequence,
                        group,
                        description,
                        parent,
                        function,
                        context=None,
                        enabled=None,
                        widget=None):
        shortcut = QShortcut(QKeySequence(keySequence),
                             parent,
                             member=function,
                             ambiguousMember=function)
        if context != None:
            shortcut.setContext(context)
        if enabled != None:
            shortcut.setEnabled(True)

        ShortcutManager().register(group, description, shortcut, widget)
        return shortcut, group, description

    def _initShortcuts(self):
        self.shortcuts = []

        # TODO: Fix this dependency on ImageView/HUD internals
        self.shortcuts.append(
            self._shortcutHelper(
                "x",
                "Navigation",
                "Minimize/Maximize x-Window",
                self,
                self.quadview.switchXMinMax,
                Qt.ApplicationShortcut,
                True,
                widget=self.editor.imageViews[0].hud.buttons['maximize']))
        self.shortcuts.append(
            self._shortcutHelper(
                "y",
                "Navigation",
                "Minimize/Maximize y-Window",
                self,
                self.quadview.switchYMinMax,
                Qt.ApplicationShortcut,
                True,
                widget=self.editor.imageViews[1].hud.buttons['maximize']))
        self.shortcuts.append(
            self._shortcutHelper(
                "z",
                "Navigation",
                "Minimize/Maximize z-Window",
                self,
                self.quadview.switchZMinMax,
                Qt.ApplicationShortcut,
                True,
                widget=self.editor.imageViews[2].hud.buttons['maximize']))

        for i, v in enumerate(self.editor.imageViews):
            self.shortcuts.append(
                self._shortcutHelper("+", "Navigation", "Zoom in", v, v.zoomIn,
                                     Qt.WidgetShortcut))
            self.shortcuts.append(
                self._shortcutHelper("-", "Navigation", "Zoom out", v,
                                     v.zoomOut, Qt.WidgetShortcut))

            self.shortcuts.append(
                self._shortcutHelper("c", "Navigation", "Center image", v,
                                     v.centerImage, Qt.WidgetShortcut))
            self.shortcuts.append(
                self._shortcutHelper("h", "Navigation", "Toggle hud", v,
                                     v.toggleHud, Qt.WidgetShortcut))

            # FIXME: The nextChannel/previousChannel functions don't work right now.
            #self.shortcuts.append(self._shortcutHelper("q", "Navigation", "Switch to next channel",     v, self.editor.nextChannel,     Qt.WidgetShortcut))
            #self.shortcuts.append(self._shortcutHelper("a", "Navigation", "Switch to previous channel", v, self.editor.previousChannel, Qt.WidgetShortcut))

            def sliceDelta(axis, delta):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] += delta
                newPos[axis] = max(0, newPos[axis])
                newPos[axis] = min(self.editor.posModel.shape[axis] - 1,
                                   newPos[axis])
                self.editor.posModel.slicingPos = newPos

            def jumpToFirstSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = 0
                self.editor.posModel.slicingPos = newPos

            def jumpToLastSlice(axis):
                newPos = copy.copy(self.editor.posModel.slicingPos)
                newPos[axis] = self.editor.posModel.shape[axis] - 1
                self.editor.posModel.slicingPos = newPos

            # TODO: Fix this dependency on ImageView/HUD internals
            self.shortcuts.append(
                self._shortcutHelper("Ctrl+Up",
                                     "Navigation",
                                     "Slice up",
                                     v,
                                     partial(sliceDelta, i, 1),
                                     Qt.WidgetShortcut,
                                     widget=v.hud.buttons['slice'].upLabel))
            self.shortcuts.append(
                self._shortcutHelper("Ctrl+Down",
                                     "Navigation",
                                     "Slice down",
                                     v,
                                     partial(sliceDelta, i, -1),
                                     Qt.WidgetShortcut,
                                     widget=v.hud.buttons['slice'].downLabel))

            #            self.shortcuts.append(self._shortcutHelper("p", "Navigation", "Slice up (alternate shortcut)",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut))
            #            self.shortcuts.append(self._shortcutHelper("o", "Navigation", "Slice down (alternate shortcut)", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut))

            self.shortcuts.append(
                self._shortcutHelper("Ctrl+Shift+Up", "Navigation",
                                     "10 slices up", v,
                                     partial(sliceDelta, i,
                                             10), Qt.WidgetShortcut))
            self.shortcuts.append(
                self._shortcutHelper("Ctrl+Shift+Down", "Navigation",
                                     "10 slices down", v,
                                     partial(sliceDelta, i,
                                             -10), Qt.WidgetShortcut))
            self.shortcuts.append(
                self._shortcutHelper("Shift+Up", "Navigation",
                                     "Jump to first slice", v,
                                     partial(jumpToFirstSlice,
                                             i), Qt.WidgetShortcut))
            self.shortcuts.append(
                self._shortcutHelper("Shift+Down", "Navigation",
                                     "Jump to last slice", v,
                                     partial(jumpToLastSlice,
                                             i), Qt.WidgetShortcut))

    def _updateInfoLabels(self, pos):
        self.quadViewStatusBar.setMouseCoords(*pos)

    def eventFilter(self, watched, event):
        # If the user performs a ctrl+scroll on the splitter itself,
        # scroll all views.
        if event.type() == QEvent.Wheel and (event.modifiers()
                                             == Qt.ControlModifier):
            for view in self.editor.imageViews:
                if event.delta() > 0:
                    view.zoomIn()
                else:
                    view.zoomOut()
            return True
        return False

    def getViewMenu(self, debug_mode=False):
        """
        Return a QMenu with a set of actions for our editor.
        """
        if self._viewMenu is None:
            self._initViewMenu()
        for action in self._debugActions:
            action.setEnabled(debug_mode)
            action.setVisible(debug_mode)
        return self._viewMenu

    def _initViewMenu(self):
        self._viewMenu = QMenu("View", parent=self)
        self._viewMenu.setObjectName("view_menu")
        self._debugActions = []

        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionFitToScreen = self._viewMenu.addAction(
            "&Zoom to &fit")
        self._viewMenu.actionFitToScreen.triggered.connect(self._fitToScreen)

        def toggleHud():
            hide = not self.editor.imageViews[0]._hud.isVisible()
            for v in self.editor.imageViews:
                v.setHudVisible(hide)

        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionToggleAllHuds = self._viewMenu.addAction(
            "Toggle huds")
        self._viewMenu.actionToggleAllHuds.triggered.connect(toggleHud)

        def resetAllAxes():
            for s in self.editor.imageScenes:
                s.resetAxes()

        self._viewMenu.addAction("Reset all axes").triggered.connect(
            resetAllAxes)

        def centerAllImages():
            for v in self.editor.imageViews:
                v.centerImage()

        self._viewMenu.addAction("Center images").triggered.connect(
            centerAllImages)

        def toggleDebugPatches(show):
            self.editor.showDebugPatches = show

        actionShowTiling = self._viewMenu.addAction("Show Tiling")
        actionShowTiling.setCheckable(True)
        actionShowTiling.toggled.connect(toggleDebugPatches)
        qsd = QShortcut(QKeySequence("Ctrl+D"),
                        self,
                        member=actionShowTiling.toggle,
                        context=Qt.WidgetShortcut)
        ShortcutManager().register("Navigation", "Show tiling", qsd)
        self._debugActions.append(actionShowTiling)

        def setCacheSize(cache_size):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget(QLabel("Cached Slices Per View:"))

            cache_size = [self.editor.cacheSize]

            def parseCacheSize(strSize):
                # TODO: Use a QValidator to make sure the user always gives a number
                try:
                    cache_size[0] = int(strSize)
                except:
                    pass

            edit = QLineEdit(str(cache_size[0]), parent=dlg)
            edit.textChanged.connect(parseCacheSize)
            layout.addWidget(edit)
            okButton = QPushButton("OK", parent=dlg)
            okButton.clicked.connect(dlg.accept)
            layout.addWidget(okButton)
            dlg.setLayout(layout)
            dlg.setModal(True)
            dlg.exec_()
            self.editor.cacheSize = cache_size[0]

        self._viewMenu.addAction("Set layer cache size").triggered.connect(
            setCacheSize)

        def enablePrefetching(enable):
            for scene in self.editor.imageScenes:
                scene.setPrefetchingEnabled(enable)

        actionUsePrefetching = self._viewMenu.addAction("Use prefetching")
        actionUsePrefetching.setCheckable(True)
        actionUsePrefetching.toggled.connect(enablePrefetching)

        def blockGuiForRendering():
            for v in self.editor.imageViews:
                v.scene().joinRenderingAllTiles()
                v.repaint()
            QApplication.processEvents()

        actionBlockGui = self._viewMenu.addAction("Block for rendering")
        actionBlockGui.triggered.connect(blockGuiForRendering)
        qsw = QShortcut(QKeySequence("Ctrl+B"),
                        self,
                        member=actionBlockGui.trigger,
                        context=Qt.WidgetShortcut)
        ShortcutManager().register("Navigation", "Block gui for rendering",
                                   qsw)
        self._debugActions.append(actionBlockGui)

        # ------ Separator ------
        self._viewMenu.addAction("").setSeparator(True)

        # Text only
        actionOnlyForSelectedView = self._viewMenu.addAction(
            "Only for selected view")
        actionOnlyForSelectedView.setIconVisibleInMenu(True)
        font = actionOnlyForSelectedView.font()
        font.setItalic(True)
        font.setBold(True)
        actionOnlyForSelectedView.setFont(font)

        def setCurrentAxisIcon():
            """Update the icon that shows the currently selected axis."""
            actionOnlyForSelectedView.setIcon(
                QIcon(self.editor.imageViews[
                    self.editor._lastImageViewFocus]._hud.axisLabel.pixmap()))

        self.editor.newImageView2DFocus.connect(setCurrentAxisIcon)
        setCurrentAxisIcon()

        actionFitImage = self._viewMenu.addAction("Fit image")
        actionFitImage.triggered.connect(self._fitImage)
        qsa = QShortcut(QKeySequence("K"),
                        self,
                        member=actionFitImage.trigger,
                        context=Qt.WidgetShortcut)
        ShortcutManager().register("Navigation", "Fit image on screen", qsa)

        def toggleSelectedHud():
            self.editor.imageViews[self.editor._lastImageViewFocus].toggleHud()

        actionToggleSelectedHud = self._viewMenu.addAction("Toggle hud")
        actionToggleSelectedHud.triggered.connect(toggleSelectedHud)

        def resetAxes():
            self.editor.imageScenes[
                self.editor._lastImageViewFocus].resetAxes()

        self._viewMenu.addAction("Reset axes").triggered.connect(resetAxes)

        def centerImage():
            self.editor.imageViews[
                self.editor._lastImageViewFocus].centerImage()

        actionCenterImage = self._viewMenu.addAction("Center image")
        actionCenterImage.triggered.connect(centerImage)
        qsc = QShortcut(QKeySequence("C"),
                        self,
                        member=actionCenterImage.trigger,
                        context=Qt.WidgetShortcut)
        ShortcutManager().register("Navigation", "Center image", qsc)

        def restoreImageToOriginalSize():
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()

        actionResetZoom = self._viewMenu.addAction("Reset zoom")
        actionResetZoom.triggered.connect(restoreImageToOriginalSize)
        qsw = QShortcut(QKeySequence("W"),
                        self,
                        member=actionResetZoom.trigger,
                        context=Qt.WidgetShortcut)
        ShortcutManager().register("Navigation", "Reset zoom", qsw)

        def updateHudActions():
            dataShape = self.editor.dataShape
            # if the image is 2D, do not show the HUD action (issue #190)
            is2D = numpy.sum(numpy.asarray(dataShape[1:4]) == 1) == 1
            actionToggleSelectedHud.setVisible(not is2D)
            self._viewMenu.actionToggleAllHuds.setVisible(not is2D)

        self.editor.shapeChanged.connect(updateHudActions)
    def addMenus(self):
        if self.profilesMenu is not None:
            self.profilesMenu.clear()
        self.actions = defaultdict(list)
        settings = QSettings()
        defaultProfile = settings.value('profilesplugin/LastProfile', 'Default', unicode)
        autoLoad = settings.value('profilesplugin/AutoLoad', False, bool)
        for k, v in profiles.iteritems():
            action = QAction(k, self.iface.mainWindow())
            action.setCheckable(True)
            if k == defaultProfile and autoLoad:
                action.setChecked(True)
            action.triggered.connect(lambda _, menuName=k: self.applyProfile(menuName))
            action.setObjectName('mProfilesPlugin_' + k)
            self.actions[v.group].append(action)

        actions = self.iface.mainWindow().menuBar().actions()
        settingsMenu = None
        self.profilesGroup = QActionGroup(self.iface.mainWindow())
        if self.profilesMenu is None:
            for action in actions:
                if action.menu().objectName() == 'mSettingsMenu':
                    settingsMenu = action.menu()
                    self.profilesMenu = QMenu(settingsMenu)
                    self.profilesMenu.setObjectName('mProfilesPlugin')
                    self.profilesMenu.setTitle(self.tr('Profiles'))
                    settingsMenu.addMenu(self.profilesMenu)
                    break

        if self.profilesMenu is not None:
            for k,v in self.actions.iteritems():
                submenu = QMenu(self.profilesMenu)
                submenu.setObjectName('mProfilesPlugin_submenu_' + k)
                submenu.setTitle(k)
                for action in v:
                    self.profilesGroup.addAction(action)
                    submenu.addAction(action)
                self.profilesMenu.addMenu(submenu)

        self.profilesMenu.addSeparator()

        settings = QSettings()
        def _setAutoLoad():
            settings.setValue('profilesplugin/AutoLoad', self.autoloadAction.isChecked())

        self.autoloadAction = QAction(self.tr('Auto-load last profile on QGIS start'), iface.mainWindow())
        self.autoloadAction.setCheckable(True)
        autoLoad = settings.value('profilesplugin/AutoLoad', False, bool)
        self.autoloadAction.setChecked(autoLoad)
        self.autoloadAction.setObjectName('mProfilesPluginAutoLoad')
        self.autoloadAction.triggered.connect(_setAutoLoad)
        self.profilesMenu.addAction(self.autoloadAction)

        self.saveProfileAction = QAction(self.tr('Profiles manager...'),
                                         self.iface.mainWindow())
        self.saveProfileAction.setObjectName('mProfilesPluginProfilesManager')
        self.saveProfileAction.triggered.connect(self.saveProfile)
        self.profilesMenu.addAction(self.saveProfileAction)

        self.showHelpAction = QAction(self.tr('Help'), self.iface.mainWindow())
        self.showHelpAction.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.showHelpAction.setObjectName('mProfilesPluginShowHelp')
        self.showHelpAction.triggered.connect(self.showHelp)
        self.profilesMenu.addAction(self.showHelpAction)
class LocationGenerator:
    """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',
                                   'LocationGenerator_{}.qm'.format(locale))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Check if the menu exists and get it
        self.menu = self.iface.mainWindow().findChild(QMenu,
                                                      '&Beaver Dam Tools')

        # If the menu does not exist, create it!
        if not self.menu:
            self.menu = QMenu('&Beaver Dam Tools',
                              self.iface.mainWindow().menuBar())
            self.menu.setObjectName('&Beaver Dam Tools')
            actions = self.iface.mainWindow().menuBar().actions()
            lastAction = actions[-1]
            self.iface.mainWindow().menuBar().insertMenu(lastAction, self.menu)

        self.action = QAction(QIcon(":/plugins/LocationGenerator/icon.png"),
                              "BD Location Generator", self.iface.mainWindow())
        self.action.triggered.connect(self.run)
        self.menu.addAction(self.action)
        self.dlg = LocationGeneratorDialog()

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

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Example #35
0
    def load_menus(self, profile=None, schema=None):
        """
        Load menus in the main windows qgis bar
        """
        if not schema:
            schema = self.combo_schema.currentText()
        if not profile:
            profile = self.combo_profile.currentText()
        # remove previous menus
        for menu in self.uiparent.menus:
            self.uiparent.iface.mainWindow().menuBar().removeAction(
                menu.menuAction())

        with self.transaction():
            cur = self.connection.cursor()
            select = """
                select name, profile, model_index, datasource_uri
                from {}.{}
                where profile = '{}'
                """.format(schema, self.table, profile)
            cur.execute(select)
            rows = cur.fetchall()
        # item accessor ex: '0-menu/0-submenu/1-item/'
        menudict = {}
        # reference to parent item
        parent = ''
        # reference to qgis main menu bar
        menubar = self.uiparent.iface.mainWindow().menuBar()

        for name, profile, model_index, datasource_uri in self.sortby_modelindex(
                rows):
            uri_struct = QgsMimeDataUtils.Uri(datasource_uri)
            indexes = json.loads(model_index)
            # root menu
            parent = '{}-{}/'.format(indexes[0][0], indexes[0][1])
            if parent not in menudict:
                menu = QMenu(self.uiparent.iface.mainWindow())
                self.uiparent.menus.append(menu)
                menu.setObjectName(indexes[0][1])
                menu.setTitle(indexes[0][1])
                menubar.insertMenu(
                    self.uiparent.iface.firstRightStandardMenu().menuAction(),
                    menu)
                menudict[parent] = menu
            else:
                # menu already there
                menu = menudict[parent]

            for idx, subname in indexes[1:-1]:
                # intermediate submenus
                parent += '{}-{}/'.format(idx, subname)
                if parent not in menudict:
                    submenu = menu.addMenu(subname)
                    submenu.setObjectName(subname)
                    submenu.setTitle(subname)
                    menu = submenu
                    # store it for later use
                    menudict[parent] = menu
                    continue
                # already treated
                menu = menudict[parent]

            # last item = layer
            layer = QAction(name, self.uiparent.iface.mainWindow())

            if uri_struct.providerKey in ICON_MAPPER:
                layer.setIcon(QIcon(ICON_MAPPER[uri_struct.providerKey]))

            if uri_struct.providerKey == 'postgres':
                # set tooltip to postgres comment
                comment = self.get_table_comment(uri_struct.uri)
                layer.setStatusTip(comment)
                layer.setToolTip(comment)

            layer.setData(uri_struct.uri)
            layer.setWhatsThis(uri_struct.providerKey)
            layer.triggered.connect(self.layer_handler[uri_struct.layerType])
            menu.addAction(layer)
Example #36
0
    def labelingContextMenu(self,names,op,position5d):
        menu = QMenu(self)
        menu.setObjectName("carving_context_menu")
        posItem = menu.addAction("position %d %d %d" % (position5d[1], position5d[2], position5d[3]))
        posItem.setEnabled(False)
        menu.addSeparator()
        for name in names:
            submenu = QMenu(name,menu)
            
            # Load
            loadAction = submenu.addAction("Load %s" % name)
            loadAction.triggered.connect( partial(op.loadObject, name) )
            
            # Delete
            def onDelAction(_name):
                self.confirmAndDelete([_name])
                if self.render and self._renderMgr.ready:
                    self._update_rendering()
            delAction = submenu.addAction("Delete %s" % name)
            delAction.triggered.connect( partial(onDelAction, name) )

            if self.render:
                if name in self._shownObjects3D:
                    # Remove
                    def onRemove3D(_name):
                        label = self._shownObjects3D.pop(_name)
                        self._renderMgr.removeObject(label)
                        self._update_rendering()
                    removeAction = submenu.addAction("Remove %s from 3D view" % name)
                    removeAction.triggered.connect( partial(onRemove3D, name) )
                else:
                    # Show
                    def onShow3D(_name):
                        label = self._renderMgr.addObject()
                        self._shownObjects3D[_name] = label
                        self._update_rendering()
                    showAction = submenu.addAction("Show 3D %s" % name)
                    showAction.triggered.connect( partial(onShow3D, name ) )
            
            # Export mesh
            if _have_vtk:
                exportAction = submenu.addAction("Export mesh for %s" % name)
                exportAction.triggered.connect( partial(self._onContextMenuExportMesh, name) )
                        
            menu.addMenu(submenu)

        if names:
            menu.addSeparator()

        menu.addSeparator()
        if self.render:
            showSeg3DAction = menu.addAction( "Show Editing Segmentation in 3D" )
            showSeg3DAction.setCheckable(True)
            showSeg3DAction.setChecked( self._showSegmentationIn3D )
            showSeg3DAction.triggered.connect( self._toggleSegmentation3D )
        
        if op.dataIsStorable():
            menu.addAction("Save object").triggered.connect( self.onSaveButton )
        menu.addAction("Browse objects").triggered.connect( self.onShowObjectNames )
        menu.addAction("Segment").triggered.connect( self.onSegmentButton )
        menu.addAction("Clear").triggered.connect( self._onClearAction )
        return menu
Example #37
0
class MainWindow(QMainWindow, object):
    """
    QMainWindow displays pipeline
    Parameters
    ----------
    port : str
        used port to communicate with pipeline
        Note: The firewall must be configure to accept input/output on this port
    """
    def __init__(self, port):
        super(MainWindow, self).__init__()
        self.setupUi(port)

    def setupUi(self, port):
        self.setObjectName("MainWindow")
        self.resize(600, 600)
        self.centralwidget = QWidget(self)
        p = self.centralwidget.palette()
        self.centralwidget.setAutoFillBackground(True)
        p.setColor(self.centralwidget.backgroundRole(), QColor(126, 135, 152))
        self.centralwidget.setPalette(p)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 808, 25))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.actionQuit = QAction(self)
        self.actionQuit.setObjectName("actionQuit")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
        self.menubar.addAction(self.menuFile.menuAction())
        self.actionReset = QAction(self)
        self.actionReset.setObjectName("reset")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionReset)
        self.menubar.addAction(self.menuFile.menuAction())
        # add other GUI objects
        self.graph_widget = GraphWidget(self.statusbar)
        self.gridLayout.addWidget(self.graph_widget, 1, 11, 10, 10)
        pixmap = QPixmap(':/images/cta-logo-mini.png')
        lbl = QLabel()
        lbl.setPixmap(pixmap)
        self.gridLayout.addWidget(lbl, 0, 0)
        p = self.graph_widget.palette()
        self.graph_widget.setAutoFillBackground(True)
        p.setColor(self.graph_widget.backgroundRole(),
                   QColor(255, 255, 255))  # QColor(226, 235, 252))
        self.graph_widget.setPalette(p)
        self.quitButton = QPushButton()  # self.centralwidget)
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setText(
            QApplication.translate("MainWindow", "Quit", None,
                                   QApplication.UnicodeUTF8))
        self.gridLayout.addWidget(self.quitButton, 12, 0, 1, 1)
        self.info_label = InfoLabel(0, 4)
        self.info_label.setAutoFillBackground(True)
        self.gridLayout.addWidget(self.info_label, 1, 0, 1, 5)
        #self.info_label.setAlignment(PyQt4.Qt.AlignCenter);
        palette = QPalette()
        palette.setColor(self.info_label.backgroundRole(), Qt.lightGray)
        self.info_label.setPalette(palette)
        QObject.connect(self.quitButton, SIGNAL("clicked()"), self.stop)
        QObject.connect(self.actionQuit, SIGNAL("triggered()"), self.stop)
        QMetaObject.connectSlotsByName(self)
        self.retranslateUi()
        QObject.connect(self.actionQuit, SIGNAL("triggered()"), self.close)
        QMetaObject.connectSlotsByName(self)
        # Create GuiConnexion for ZMQ comminucation with pipeline
        self.guiconnection = GuiConnexion(gui_port=port,
                                          statusBar=self.statusbar)
        self.guiconnection.message.connect(self.graph_widget.pipechange)
        self.guiconnection.message.connect(self.info_label.pipechange)
        self.guiconnection.reset_message.connect(self.graph_widget.reset)
        self.guiconnection.reset_message.connect(self.info_label.reset)
        self.guiconnection.mode_message.connect(self.info_label.mode_receive)
        QObject.connect(self.actionReset, SIGNAL("triggered()"),
                        self.guiconnection.reset)
        QMetaObject.connectSlotsByName(self)
        # start the process
        self.guiconnection.start()

    def retranslateUi(self):
        self.setWindowTitle(
            QApplication.translate("ctapipe flow based GUI",
                                   "ctapipe flow based GUI", None,
                                   QApplication.UnicodeUTF8))
        self.menuFile.setTitle(
            QApplication.translate("MainWindow", "File", None,
                                   QApplication.UnicodeUTF8))
        self.actionQuit.setText(
            QApplication.translate("MainWindow", "Quit", None,
                                   QApplication.UnicodeUTF8))
        self.actionReset.setText(
            QApplication.translate("MainWindow", "Reset", None,
                                   QApplication.UnicodeUTF8))

    def stop(self):
        """Method connect (via Qt slot) to exit button
        Stops self.guiconnection (for ZMQ communication) process.
        Close main_windows
        """
        self.guiconnection.finish()
        self.guiconnection.join()
        self.close()

    def closeEvent(self, event):
        self.guiconnection.finish()
        self.guiconnection.join()
        event.accept()  # let the window close
Example #38
0
    def _initTableViews(self):
        self.fileInfoTabWidget.setTabText( 0, "Summary" )
        self.laneSummaryTableView.setModel( DataLaneSummaryTableModel(self, self.topLevelOperator) )
        self.laneSummaryTableView.dataLaneSelected.connect( self.showDataset )
        self.laneSummaryTableView.addFilesRequested.connect( self.handleAddFiles )
        self.laneSummaryTableView.addStackRequested.connect( self.handleAddStack )
        self.laneSummaryTableView.addByPatternRequested.connect( self.handleAddByPattern )
        self.removeLaneButton.clicked.connect( self.handleRemoveLaneButtonClicked )
        self.laneSummaryTableView.removeLanesRequested.connect( self.handleRemoveLaneButtonClicked )

        # These two helper functions enable/disable an 'add files' button for a given role  
        #  based on the the max lane index for that role and the overall permitted max_lanes
        def _update_button_status(button, role_index):
            if self._max_lanes:
                button.setEnabled( self._findFirstEmptyLane(role_index) < self._max_lanes )

        def _handle_lane_added( button, role_index, slot, lane_index ):
            slot[lane_index][role_index].notifyReady( bind(_update_button_status, button, role_index) )
            slot[lane_index][role_index].notifyUnready( bind(_update_button_status, button, role_index) )

        self._retained = [] # Retain menus so they don't get deleted
        self._detailViewerWidgets = []
        for roleIndex, role in enumerate(self.topLevelOperator.DatasetRoles.value):
            detailViewer = DataDetailViewerWidget( self, self.topLevelOperator, roleIndex )
            self._detailViewerWidgets.append( detailViewer )

            # Button
            menu = QMenu(parent=self)
            menu.setObjectName("addFileButton_role_{}".format( roleIndex ))
            menu.addAction( "Add one or more separate Files ..." ).triggered.connect( partial(self.handleAddFiles, roleIndex) )
            menu.addAction( "Add Volume from Stack..." ).triggered.connect( partial(self.handleAddStack, roleIndex) )
            #disabled for ilastik 1.0
            #menu.addAction( "Add Many by Pattern..." ).triggered.connect( partial(self.handleAddByPattern, roleIndex) )
            detailViewer.appendButton.setMenu( menu )
            self._retained.append(menu)

            # Monitor changes to each lane so we can enable/disable the 'add lanes' button for each tab
            self.topLevelOperator.DatasetGroup.notifyInserted( bind( _handle_lane_added, detailViewer.appendButton, roleIndex ) )
            self.topLevelOperator.DatasetGroup.notifyRemoved( bind( _update_button_status, detailViewer.appendButton, roleIndex ) )
            
            # While we're at it, do the same for the buttons in the summary table, too
            self.topLevelOperator.DatasetGroup.notifyInserted( bind( _handle_lane_added, self.laneSummaryTableView.addFilesButtons[roleIndex], roleIndex ) )
            self.topLevelOperator.DatasetGroup.notifyRemoved( bind( _update_button_status, self.laneSummaryTableView.addFilesButtons[roleIndex], roleIndex ) )
            
            # Context menu            
            detailViewer.datasetDetailTableView.replaceWithFileRequested.connect( partial(self.handleReplaceFile, roleIndex) )
            detailViewer.datasetDetailTableView.replaceWithStackRequested.connect( partial(self.replaceWithStack, roleIndex) )
            detailViewer.datasetDetailTableView.editRequested.connect( partial(self.editDatasetInfo, roleIndex) )
            detailViewer.datasetDetailTableView.resetRequested.connect( partial(self.handleClearDatasets, roleIndex) )

            # Drag-and-drop
            detailViewer.datasetDetailTableView.addFilesRequested.connect( partial( self.addFileNames, roleIndex=roleIndex ) )

            # Selection handling
            def showFirstSelectedDataset( _roleIndex, lanes ):
                if lanes:
                    self.showDataset( lanes[0], _roleIndex )
            detailViewer.datasetDetailTableView.dataLaneSelected.connect( partial(showFirstSelectedDataset, roleIndex) )

            self.fileInfoTabWidget.insertTab(roleIndex, detailViewer, role)
                
        self.fileInfoTabWidget.currentChanged.connect( self.handleSwitchTabs )
        self.fileInfoTabWidget.setCurrentIndex(0)
Example #39
0
class RECS:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'RECS_HOME_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.initdlg=InitTaskDialog()
        self.selectdlg = SelectTaskDialog()
        self.loginDlg=LogInDialog()
        self.taskMgrDlg=TaskManagerDialog()
        self.taskInfoDlg=taskInfo()
        self.taskFeaturesDlg=taskFeatures()
        #self.loadmapDlg=LoadMapDialog()
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Task')
        self.logIn()
        self.selectTask()
        self.actions = []

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


        # layer.editingStarted.connect(editLayer() )




        # TODO: We are going to let the user set this up in a future iteration
        #self.toolbar = self.iface.addToolBar(u'SelectTask')
        #self.toolbar.setObjectName(u'SelectTask')

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Tasks', message)


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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            # self.menu = QMenu( "&Task", self.iface.mainWindow().menuBar() )
            action = self.iface.mainWindow().menuBar().actions()
            lastAction = action[-1]
            self.iface.addPluginToMenu(
                self.menu,
                lastAction)

        self.actions.append(lastAction)

        return action

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

        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        """ Task menu setting """
        self.menu = QMenu(self.iface.mainWindow())
        self.menu.setObjectName("task_menu_object")
        self.menu.setTitle("Task")





        """ Task """
        self.action_tasks = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Tasks", self.iface.mainWindow())
        self.action_tasks.setObjectName("Task_action_object")
        self.action_tasks.setWhatsThis("Task Initialized")
        #QtCore.QObject.connect(self.action_tasks, SIGNAL("triggered()"), self.tasks)

        """ Initializing Task """
        self.action_init_task = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Initialize ", self.iface.mainWindow())
        self.action_init_task.setObjectName("Task_action_object")
        self.action_init_task.setWhatsThis("Task Initialize")
        QtCore.QObject.connect(self.action_init_task, SIGNAL("triggered()"), self.initTask)


        """ Select Task """
        self.action_select_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Select Task", self.iface.mainWindow())
        self.action_select_task.setObjectName("Task_Select_object")
        self.action_select_task.setWhatsThis("Select Task")
        QtCore.QObject.connect(self.action_select_task, SIGNAL("triggered()"), self.selectTask)

        """ Reload Task """
        self.action_reload_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Reload Task", self.iface.mainWindow())
        self.action_reload_task.setObjectName("Task_Reload_object")
        self.action_reload_task.setWhatsThis("Reload Task")
        QtCore.QObject.connect(self.action_reload_task, SIGNAL("triggered()"), self.taskManager)

        """ Edit Task """
        self.action_edit_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Edit Task", self.iface.mainWindow())
        self.action_edit_task.setObjectName("Task_Edit_object")
        self.action_edit_task.setWhatsThis("Edit Task")
        QtCore.QObject.connect(self.action_edit_task, SIGNAL("triggered()"), self.editLayer)


        """ Finish Task """
        self.action_finish_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Finish Task", self.iface.mainWindow())
        self.action_finish_task.setObjectName("Task_Finish_object")
        self.action_finish_task.setWhatsThis("Edit Task")
        QtCore.QObject.connect(self.action_finish_task, SIGNAL("triggered()"), self.finishEditngLayer)


        """ Add action to the menu list """
        #self.menuTask.addAction(self.action_tasks)

        self.menu.addAction(self.action_init_task)
        self.menu.addAction(self.action_select_task)
        self.menu.addAction(self.action_reload_task)
        self.menu.addAction(self.action_edit_task)
        self.menu.addAction(self.action_finish_task)

        """ Add menu to the menubar """
        menubar=self.iface.mainWindow().menuBar()
        menubar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),self.menu)



        """ Add icon to the toolbar """
        #self.iface.addPluginToMenu(u"&load Map", self.action_loadmap)
        #self.iface.addToolBarIcon(self.action_init_task)

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

        layers = self.iface.legendInterface().layers()
        #layer_list = []
        for layer in layers:
           #layer_list.append(layer.name())
           if layer.name() == 'PARCEL':
            self.iface.setActiveLayer(layer)
        self.initdlg.show()
        #layer_list=list(set(layer_list))
        #self.initdlg.comboBox.addItems(layer_list)
        self.initdlg.setFixedSize(self.initdlg.size())
        result = self.initdlg.exec_()
        if result:
            pass
    def selectTask(self):
        self.selectdlg.show()
        self.selectdlg.setFixedSize(self.selectdlg.size())

        self.selectdlg.loadLayer()
        self.selectdlg.populate()
        result = self.selectdlg.exec_()
        if result:
            # self.selectdlg.close()
            pass
    def showTaskInfo(self):
        self.taskInfoDlg.show()
        t_id = self.taskMgrDlg.retTaskID()
        self.taskInfoDlg.getAttribData(t_id)
        #self.taskInfoDlg.populate()
    def taskManager(self):

        if self.taskMgrDlg.isVisible():
            self.taskMgrDlg.loadTaskClicked()
            # self.taskMgrDlg.close()
            # self.apdockwidget.close()
        else:
            self.taskMgrDlg.show()
            self.apdockwidget = QDockWidget("Task Manager", self.iface.mainWindow())
            self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint)
            self.apdockwidget.setWidget(self.taskMgrDlg)
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget)
            self.taskMgrDlg.populate()
            self.taskFeatures()




        # rows = self.taskMgrDlg.taskListTable.rowCount()
        # createdByList=[]
        #
        #
        # for row in range(0,rows):
        #     createdByItems=self.taskMgrDlg.taskListTable.item(row,1)
        #     createdByList.append(createdByItems.text())
        #
        #
        # createdByList=list(set(createdByList))
        # self.taskMgrDlg.createByComboBox.addItems(createdByList)
        # self.taskMgrDlg.createByComboBox.setCurrentIndex(createdByList.index())
        self.menu = QtGui.QMenu()
        #newTask=self.menu.addAction("New Task",self.newTask,"")
        newTask = self.menu.addAction("New Task", self.newTaskEvent)
        loadTask = self.menu.addAction("Load Task", self.loadTaskEvent)
        cancelTask = self.menu.addAction("Cancel Task", self.cancelTaskEvent)
        showTaskArea = self.menu.addAction("Show Task Area", self.showTaskAreaEvent)
        noTask=self.menu.addAction("No Task",self.noTaskEvent)
        showTaskInfo=self.menu.addAction("Show Task Info",self.showTaskInfoEvent)
        updateFeature=self.menu.addAction("Update Features",self.updateFeatureEvent)

        self.taskMgrDlg.taskListTable.addAction(newTask)
        self.taskMgrDlg.taskListTable.addAction(loadTask)
        self.taskMgrDlg.taskListTable.addAction(cancelTask)
        self.taskMgrDlg.taskListTable.addAction(showTaskArea)
        self.taskMgrDlg.taskListTable.addAction(noTask)
        self.taskMgrDlg.taskListTable.addAction(showTaskInfo)
        self.taskMgrDlg.taskListTable.addAction(updateFeature)
        self.taskMgrDlg.taskListTable.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.taskMgrDlg.taskListTable.customContextMenuRequested.connect(self.contextMenuEvent)
        result = self.taskMgrDlg.exec_()
        if result:
            self.taskMgrDlg.populate()
        #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange
    def contextMenuEvent(self, point):
        self.menu.exec_(self.taskMgrDlg.taskListTable.mapToGlobal(point))
    def newTaskEvent(self):
        self.initTask()
    def loadTaskEvent(self):
        self.taskMgrDlg.loadTaskClicked()
        t_id = self.taskMgrDlg.retTaskID()
        self.taskFeaturesDlg.populate(t_id)
    def cancelTaskEvent(self):
        self.taskMgrDlg.cancelTask()
    def showTaskAreaEvent(self):
        self.taskMgrDlg.showTaskAreaClicked()
    def noTaskEvent(self):
        print "noTask Called"
    def showTaskInfoEvent(self):
        self.showTaskInfo()
    def updateFeatureEvent(self):
        print "updateFeature"
    def logIn(self):

        self.loginDlg.show()
        self.loginDlg.setWindowFlags(Qt.FramelessWindowHint)
        result = self.loginDlg.exec_()
        if result:
            pass
    def loadLayer(self):
        self.mlr = None
        # QgsMapLayerRegistry.instance().removeAllMapLayers()
        self.mlr = QgsMapLayerRegistry.instance()
        uri = QgsDataSourceURI()
        uri.setConnection("172.20.0.71", "5432", "ncrprs_db", "postgres", "123456")
        uri.setDataSource("recs", "t_parcel", "parcelgeometry", "")
        vlayer = QgsVectorLayer(uri.uri(), "Parcel", "postgres")
        if vlayer.isValid():
            self.mlr.addMapLayer(vlayer)
        else:
            QMessageBox.information(None, "Unable to Laod Data", "Unable to Load Layers from the Database!")
            return None
    def editLayer(self):
        global taskLayer
        global featCount
        layers = self.iface.legendInterface().layers()
        for layer in layers:
            if layer.name() == 'TaskLayer':
                taskLayer = layer
                taskLayerID=layer.id()
                self.iface.setActiveLayer(taskLayer)
        featCount = taskLayer.featureCount()
        print featCount
        taskLayer.startEditing()
        QgsProject.instance().setSnapSettingsForLayer(taskLayerID,True,2,1,20,True)
    def finishEditngLayer(self):

        """
        change the edits to GML again to detect the changes

        """
        print featCount
        taskLayer_shape = iface.activeLayer()
        QgsVectorFileWriter.writeAsVectorFormat(taskLayer_shape,"Z:\\GMLEdited\\temp.gml","utf-8",None,"GML")

        #QgsMapLayerRegistry.instance().removeAllMapLayers()
        iface.addVectorLayer("Z:\\GMLEdited\\temp.gml","EditedTaskLayer","ogr")
        """
        Compare the two gml geometries
        """

        doc_edited = xml.dom.minidom.parse("Z:\\GMLEdited\\temp.gml")
        doc_origion = xml.dom.minidom.parse("Z:\\GMLFile\\ogrGML.gml")
        editedParcel = doc_edited.getElementsByTagName("gml:featureMember")
        epLength = editedParcel.length
        print epLength
        obj = GeometryEdit()
        if epLength > featCount:
           obj.split(doc_edited,doc_origion)
           print "split"
        elif epLength < featCount:
            obj.merge(doc_edited,doc_origion)
            print "merge"
        else:
            obj.updateGeom()
            print "update"
    def taskFeatures(self):
        self.taskFeaturesDlg.show()
        self.apdockwidget = QDockWidget("Features Of Current Task", self.iface.mainWindow())
        self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint)
        self.apdockwidget.setWidget(self.taskFeaturesDlg)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget)


        self.menu_feature = QtGui.QMenu()
        #newTask=self.menu.addAction("New Task",self.newTask,"")
        editAttr = self.menu_feature.addAction("Edit", self.editEvent)
        self.taskFeaturesDlg.currentTaskTable.addAction(editAttr)
        self.taskFeaturesDlg.currentTaskTable.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.taskFeaturesDlg.currentTaskTable.customContextMenuRequested.connect(self.contextMenuEvent2)

        #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange
    def contextMenuEvent2(self, point):
        self.menu_feature.exec_(self.taskFeaturesDlg.currentTaskTable.mapToGlobal(point))
    def editEvent(self):
        self.showTaskInfo()
Example #40
0
    def _initTableViews(self):
        self.fileInfoTabWidget.setTabText(0, "Summary")
        self.laneSummaryTableView.setModel(
            DataLaneSummaryTableModel(self, self.topLevelOperator))
        self.laneSummaryTableView.dataLaneSelected.connect(self.showDataset)
        self.laneSummaryTableView.addFilesRequested.connect(
            self.handleAddFiles)
        self.laneSummaryTableView.addStackRequested.connect(
            self.handleAddStack)
        self.laneSummaryTableView.addByPatternRequested.connect(
            self.handleAddByPattern)
        self.removeLaneButton.clicked.connect(
            self.handleRemoveLaneButtonClicked)
        self.laneSummaryTableView.removeLanesRequested.connect(
            self.handleRemoveLaneButtonClicked)

        # These two helper functions enable/disable an 'add files' button for a given role
        #  based on the the max lane index for that role and the overall permitted max_lanes
        def _update_button_status(button, role_index):
            if self._max_lanes:
                button.setEnabled(
                    self._findFirstEmptyLane(role_index) < self._max_lanes)

        def _handle_lane_added(button, role_index, slot, lane_index):
            slot[lane_index][role_index].notifyReady(
                bind(_update_button_status, button, role_index))
            slot[lane_index][role_index].notifyUnready(
                bind(_update_button_status, button, role_index))

        self._retained = []  # Retain menus so they don't get deleted
        self._detailViewerWidgets = []
        for roleIndex, role in enumerate(
                self.topLevelOperator.DatasetRoles.value):
            detailViewer = DataDetailViewerWidget(self, self.topLevelOperator,
                                                  roleIndex)
            self._detailViewerWidgets.append(detailViewer)

            # Button
            menu = QMenu(parent=self)
            menu.setObjectName("addFileButton_role_{}".format(roleIndex))
            menu.addAction("Add File(s)...").triggered.connect(
                partial(self.handleAddFiles, roleIndex))
            menu.addAction("Add Volume from Stack...").triggered.connect(
                partial(self.handleAddStack, roleIndex))
            menu.addAction("Add Many by Pattern...").triggered.connect(
                partial(self.handleAddByPattern, roleIndex))
            detailViewer.appendButton.setMenu(menu)
            self._retained.append(menu)

            # Monitor changes to each lane so we can enable/disable the 'add lanes' button for each tab
            self.topLevelOperator.DatasetGroup.notifyInserted(
                bind(_handle_lane_added, detailViewer.appendButton, roleIndex))
            self.topLevelOperator.DatasetGroup.notifyRemoved(
                bind(_update_button_status, detailViewer.appendButton,
                     roleIndex))

            # While we're at it, do the same for the buttons in the summary table, too
            self.topLevelOperator.DatasetGroup.notifyInserted(
                bind(_handle_lane_added,
                     self.laneSummaryTableView.addFilesButtons[roleIndex],
                     roleIndex))
            self.topLevelOperator.DatasetGroup.notifyRemoved(
                bind(_update_button_status,
                     self.laneSummaryTableView.addFilesButtons[roleIndex],
                     roleIndex))

            # Context menu
            detailViewer.datasetDetailTableView.replaceWithFileRequested.connect(
                partial(self.handleReplaceFile, roleIndex))
            detailViewer.datasetDetailTableView.replaceWithStackRequested.connect(
                partial(self.replaceWithStack, roleIndex))
            detailViewer.datasetDetailTableView.editRequested.connect(
                partial(self.editDatasetInfo, roleIndex))
            detailViewer.datasetDetailTableView.resetRequested.connect(
                partial(self.handleClearDatasets, roleIndex))

            # Drag-and-drop
            detailViewer.datasetDetailTableView.addFilesRequested.connect(
                partial(self.addFileNames, roleIndex=roleIndex))

            # Selection handling
            def showFirstSelectedDataset(_roleIndex, lanes):
                if lanes:
                    self.showDataset(lanes[0], _roleIndex)

            detailViewer.datasetDetailTableView.dataLaneSelected.connect(
                partial(showFirstSelectedDataset, roleIndex))

            self.fileInfoTabWidget.insertTab(roleIndex, detailViewer, role)

        self.fileInfoTabWidget.currentChanged.connect(self.handleSwitchTabs)
        self.fileInfoTabWidget.setCurrentIndex(0)