Example #1
0
    def _onTvFilesCustomContextMenuRequested(self, pos ):
        """Connected automatically by uic
        """
        menu = QMenu()
        
        menu.addAction( core.actionManager().action( "mFile/mClose/aCurrent" ) )
        menu.addAction( core.actionManager().action( "mFile/mSave/aCurrent" ) )
        menu.addAction( core.actionManager().action( "mFile/mReload/aCurrent" ) )
        menu.addSeparator()
        
        # sort menu
        sortMenu = QMenu( self )
        group = QActionGroup( sortMenu )

        group.addAction( self.tr( "Opening order" ) )
        group.addAction( self.tr( "File name" ) )
        group.addAction( self.tr( "URL" ) )
        group.addAction( self.tr( "Suffixes" ) )
        group.triggered.connect(self._onSortTriggered)
        sortMenu.addActions( group.actions() )
        
        for i, sortMode in enumerate(["OpeningOrder", "FileName", "URL", "Suffixes"]):
            action = group.actions()[i]
            action.setData( sortMode )
            action.setCheckable( True )
            if sortMode == self.model.sortMode():
                action.setChecked( True )
        
        aSortMenu = QAction( self.tr( "Sorting" ), self )
        aSortMenu.setMenu( sortMenu )
        aSortMenu.setIcon( QIcon( ":/enkiicons/sort.png" ))
        aSortMenu.setToolTip( aSortMenu.text() )
        
        menu.addAction( sortMenu.menuAction() )
        menu.exec_( self.tvFiles.mapToGlobal( pos ) )
Example #2
0
 def _setupUi(self):
     self.setupUi(self)
     self.browserView.setModel(self.boardModel)
     h = self.browserView.header()
     h.setResizeMode(QHeaderView.Fixed)
     h.resizeSection(1, 120)
     h.setResizeMode(0, QHeaderView.Stretch)
     
     # Action menu
     actionMenu = QMenu('Actions', self.toolBar)
     actionMenu.setIcon(QIcon(QPixmap(":/actions")))
     actionMenu.addAction(self.actionNewFolder)
     actionMenu.addAction(self.actionRemoveEmptyFolders)
     actionMenu.addAction(self.actionRenameSelected)
     actionMenu.addAction(self.actionMoveSelectedToIgnoreBox)
     actionMenu.addAction(self.actionSwitchConflictAndOriginal)
     actionMenu.addSeparator()
     actionMenu.addAction(self.actionMassRename)
     actionMenu.addAction(self.actionSplit)
     actionMenu.addAction(self.actionUndoSplit)
     actionMenu.addAction(self.actionMoveConflicts)
     actionMenu.addAction(self.actionMoveConflictsAndOriginals)
     self.actionActions.setMenu(actionMenu)
     button = QToolButton(self.toolBar)
     button.setDefaultAction(actionMenu.menuAction())
     button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
     self.actionsButton = button
     self.toolBar.insertWidget(self.actionActions, button) # the action is a placeholder
     self.toolBar.removeAction(self.actionActions)
     
     # Materialize menu
     materializeMenu = QMenu('Materialize', self.toolBar)
     materializeMenu.setIcon(QIcon(QPixmap(":/materialize")))
     materializeMenu.addAction(self.actionRenameInRespectiveLocations)
     materializeMenu.addAction(self.actionCopyToOtherLocation)
     materializeMenu.addAction(self.actionMoveToOtherLocation)
     self.actionMaterialize.setMenu(materializeMenu)
     button = QToolButton(self.toolBar)
     button.setDefaultAction(materializeMenu.menuAction())
     button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
     self.materializeButton = button
     self.toolBar.insertWidget(self.actionMaterialize, button) # the action is a placeholder
     self.toolBar.removeAction(self.actionMaterialize)
Example #3
0
 def init(self):
     menu = QMenu('', self)
     menu.menuAction().setIcon(QIcon('rsc/scene.png'))
     a = QAction(QIcon('rsc/scene.png'), 'Scene', self)
     a.setIconVisibleInMenu(True)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     menu.addAction(a)
     a = QAction(QIcon('rsc/node.png'), 'Node', self)
     a.setIconVisibleInMenu(True)
     menu.addAction(a)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     a = QAction(QIcon('rsc/tree.png'), 'Tree', self)
     a.setIconVisibleInMenu(True)
     menu.addAction(a)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     a = QAction(QIcon('rsc/menu.png'), 'Menu', self)
     a.setIconVisibleInMenu(True)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     menu.addAction(a)
     self.addAction(menu.menuAction())
     self.__menu = menu
     return
Example #4
0
 def init(self):
     menu = QMenu('', self)
     menu.menuAction().setIcon(QIcon('rsc/scene.png'))
     a = QAction(QIcon('rsc/scene.png'), 'Scene', self)
     a.setIconVisibleInMenu(True)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     menu.addAction(a)
     a = QAction(QIcon('rsc/node.png'), 'Node', self)
     a.setIconVisibleInMenu(True)
     menu.addAction(a)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     a = QAction(QIcon('rsc/tree.png'), 'Tree', self)
     a.setIconVisibleInMenu(True)
     menu.addAction(a)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     a = QAction(QIcon('rsc/menu.png'), 'Menu', self)
     a.setIconVisibleInMenu(True)
     self.connect(a, SIGNAL('triggered()'), self.menu_action)
     menu.addAction(a)
     self.addAction(menu.menuAction())
     self.__menu = menu
     return
    def addContextMenuActions(self, menu):
        ExperimentTreeItem.addContextMenuActions(self, menu)
        menu.addSeparator()
        onlineAction = QAction("Put Online", menu)
        onlineAction.triggered.connect(self.device.putOnline)
        menu.addAction(onlineAction)
        attentionAction = QAction("Draw Attention", menu)
        attentionAction.triggered.connect(self.device.drawAttention)
        menu.addAction(attentionAction)

        if hasattr(self.device, "documentation"):
            documentationMenu = QMenu("Documentation", menu)
            for name, url in self.device.documentation.items():
                urlAction = QAction(name, menu)

                urlAction.triggered.connect(lambda: QDesktopServices.openUrl(QUrl(url)))
                documentationMenu.addAction(urlAction)
            menu.addAction(documentationMenu.menuAction())
Example #6
0
    def addMenu(self, path, text, icon=QIcon() ):
        """Add menu to the main menu or submenu of main menu
        """
        action = self.action(path)
        if action is not None:
            if action.menu():
               return action
            else:
               assert 0 # not a menu!

        parentMenuPath = self._parentPath(path)
        if parentMenuPath:
            parentAction = self.action(parentMenuPath)
        else:
            parentAction = None
        
        menu = QMenu()
        action = menu.menuAction()
        action._menu = menu  # avoid deleting menu by the garbadge collectors        
        action.setIcon( icon )
        action.setText( text )

        if parentAction is not None:
            action.setParent( parentAction )
            parentAction.menu().addMenu( menu )
        else:
            action.setParent( self )

        self._pathToAction[ path ] = action
        action.path = path
        
        action.changed.connect(self._onActionChanged)
                
        self.actionInserted.emit( action )
        
        return action
Example #7
0
    def _onTvFilesCustomContextMenuRequested(self, pos):
        """Connected automatically by uic
        """
        menu = QMenu()

        menu.addAction(core.actionManager().action("mFile/mClose/aCurrent"))
        menu.addAction(core.actionManager().action("mFile/mSave/aCurrent"))
        menu.addAction(core.actionManager().action("mFile/mReload/aCurrent"))
        menu.addSeparator()

        # sort menu
        sortMenu = QMenu(self)
        group = QActionGroup(sortMenu)

        group.addAction(self.tr("Opening order"))
        group.addAction(self.tr("File name"))
        group.addAction(self.tr("URL"))
        group.addAction(self.tr("Suffixes"))
        group.triggered.connect(self._onSortTriggered)
        sortMenu.addActions(group.actions())

        for i, sortMode in enumerate(
            ["OpeningOrder", "FileName", "URL", "Suffixes"]):
            action = group.actions()[i]
            action.setData(sortMode)
            action.setCheckable(True)
            if sortMode == self.model.sortMode():
                action.setChecked(True)

        aSortMenu = QAction(self.tr("Sorting"), self)
        aSortMenu.setMenu(sortMenu)
        aSortMenu.setIcon(QIcon(":/enkiicons/sort.png"))
        aSortMenu.setToolTip(aSortMenu.text())

        menu.addAction(sortMenu.menuAction())
        menu.exec_(self.tvFiles.mapToGlobal(pos))
Example #8
0
    def addMenu(self, path, text, icon=QIcon() ):
        """Add menu to the main menu or submenu of main menu
        """
        action = self.action(path)
        if action is not None:
            if action.menu():
               return action
            else:
               assert 0 # not a menu!

        parentMenuPath = self._parentPath(path)
        if parentMenuPath:
            parentAction = self.action(parentMenuPath)
        else:
            parentAction = None

        menu = QMenu()
        action = menu.menuAction()
        action._menu = menu  # avoid deleting menu by the garbadge collectors
        action.setIcon( icon )
        action.setText( text )

        if parentAction is not None:
            action.setParent( parentAction )
            parentAction.menu().addMenu( menu )
        else:
            action.setParent( self )

        self._pathToAction[ path ] = action
        action.path = path

        action.changed.connect(self._onActionChanged)

        self.actionInserted.emit( action )

        return action
Example #9
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 #10
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)
Example #11
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 #12
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 DirectoriesDialog(QMainWindow):
    def __init__(self, parent, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self.lastAddedFolder = platform.INITIAL_FOLDER_IN_DIALOGS
        self.recentFolders = Recent(self.app, "recentFolders")
        self._setupUi()
        self.directoriesModel = DirectoriesModel(self.app.model.directory_tree, view=self.treeView)
        self.directoriesDelegate = DirectoriesDelegate()
        self.treeView.setItemDelegate(self.directoriesDelegate)
        self._setupColumns()
        self.app.recentResults.addMenu(self.menuLoadRecent)
        self.app.recentResults.addMenu(self.menuRecentResults)
        self.recentFolders.addMenu(self.menuRecentFolders)
        self._updateAddButton()
        self._updateRemoveButton()
        self._updateLoadResultsButton()
        self._setupBindings()

    def _setupBindings(self):
        self.scanButton.clicked.connect(self.scanButtonClicked)
        self.loadResultsButton.clicked.connect(self.actionLoadResults.trigger)
        self.addFolderButton.clicked.connect(self.actionAddFolder.trigger)
        self.removeFolderButton.clicked.connect(self.removeFolderButtonClicked)
        self.treeView.selectionModel().selectionChanged.connect(self.selectionChanged)
        self.app.recentResults.itemsChanged.connect(self._updateLoadResultsButton)
        self.recentFolders.itemsChanged.connect(self._updateAddButton)
        self.recentFolders.mustOpenItem.connect(self.app.model.add_directory)
        self.directoriesModel.foldersAdded.connect(self.directoriesModelAddedFolders)
        self.app.willSavePrefs.connect(self.appWillSavePrefs)

    def _setupActions(self):
        # (name, shortcut, icon, desc, func)
        ACTIONS = [
            ("actionLoadResults", "Ctrl+L", "", tr("Load Results..."), self.loadResultsTriggered),
            ("actionShowResultsWindow", "", "", tr("Results Window"), self.app.showResultsWindow),
            ("actionAddFolder", "", "", tr("Add Folder..."), self.addFolderTriggered),
        ]
        createActions(ACTIONS, self)

    def _setupMenu(self):
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 42, 22))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setTitle(tr("File"))
        self.menuView = QMenu(self.menubar)
        self.menuView.setTitle(tr("View"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setTitle(tr("Help"))
        self.menuLoadRecent = QMenu(self.menuFile)
        self.menuLoadRecent.setTitle(tr("Load Recent Results"))
        self.setMenuBar(self.menubar)

        self.menuFile.addAction(self.actionLoadResults)
        self.menuFile.addAction(self.menuLoadRecent.menuAction())
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.app.actionQuit)
        self.menuView.addAction(self.app.actionPreferences)
        self.menuView.addAction(self.actionShowResultsWindow)
        self.menuView.addAction(self.app.actionIgnoreList)
        self.menuHelp.addAction(self.app.actionShowHelp)
        self.menuHelp.addAction(self.app.actionRegister)
        self.menuHelp.addAction(self.app.actionCheckForUpdate)
        self.menuHelp.addAction(self.app.actionOpenDebugLog)
        self.menuHelp.addAction(self.app.actionAbout)

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

        # Recent folders menu
        self.menuRecentFolders = QMenu()
        self.menuRecentFolders.addAction(self.actionAddFolder)
        self.menuRecentFolders.addSeparator()

        # Recent results menu
        self.menuRecentResults = QMenu()
        self.menuRecentResults.addAction(self.actionLoadResults)
        self.menuRecentResults.addSeparator()

    def _setupUi(self):
        self.setWindowTitle(self.app.NAME)
        self.resize(420, 338)
        self.centralwidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.promptLabel = QLabel(tr('Select folders to scan and press "Scan".'), self.centralwidget)
        self.verticalLayout.addWidget(self.promptLabel)
        self.treeView = QTreeView(self.centralwidget)
        self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.treeView.setAcceptDrops(True)
        triggers = (
            QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked
        )
        self.treeView.setEditTriggers(triggers)
        self.treeView.setDragDropOverwriteMode(True)
        self.treeView.setDragDropMode(QAbstractItemView.DropOnly)
        self.treeView.setUniformRowHeights(True)
        self.verticalLayout.addWidget(self.treeView)
        self.horizontalLayout = QHBoxLayout()
        self.removeFolderButton = QPushButton(self.centralwidget)
        self.removeFolderButton.setIcon(QIcon(QPixmap(":/minus")))
        self.removeFolderButton.setShortcut("Del")
        self.horizontalLayout.addWidget(self.removeFolderButton)
        self.addFolderButton = QPushButton(self.centralwidget)
        self.addFolderButton.setIcon(QIcon(QPixmap(":/plus")))
        self.horizontalLayout.addWidget(self.addFolderButton)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.loadResultsButton = QPushButton(self.centralwidget)
        self.loadResultsButton.setText(tr("Load Results"))
        self.horizontalLayout.addWidget(self.loadResultsButton)
        self.scanButton = QPushButton(self.centralwidget)
        self.scanButton.setText(tr("Scan"))
        self.scanButton.setDefault(True)
        self.horizontalLayout.addWidget(self.scanButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.setCentralWidget(self.centralwidget)

        self._setupActions()
        self._setupMenu()

        if self.app.prefs.directoriesWindowRect is not None:
            self.setGeometry(self.app.prefs.directoriesWindowRect)
        else:
            moveToScreenCenter(self)

    def _setupColumns(self):
        header = self.treeView.header()
        header.setStretchLastSection(False)
        header.setResizeMode(0, QHeaderView.Stretch)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.resizeSection(1, 100)

    def _updateAddButton(self):
        if self.recentFolders.isEmpty():
            self.addFolderButton.setMenu(None)
        else:
            self.addFolderButton.setMenu(self.menuRecentFolders)

    def _updateRemoveButton(self):
        indexes = self.treeView.selectedIndexes()
        if not indexes:
            self.removeFolderButton.setEnabled(False)
            return
        self.removeFolderButton.setEnabled(True)

    def _updateLoadResultsButton(self):
        if self.app.recentResults.isEmpty():
            self.loadResultsButton.setMenu(None)
        else:
            self.loadResultsButton.setMenu(self.menuRecentResults)

    # --- QWidget overrides
    def closeEvent(self, event):
        event.accept()
        if self.app.model.results.is_modified:
            title = tr("Unsaved results")
            msg = tr("You have unsaved results, do you really want to quit?")
            if not self.app.confirm(title, msg):
                event.ignore()
        if event.isAccepted():
            QApplication.quit()

    # --- Events
    def addFolderTriggered(self):
        title = tr("Select a folder to add to the scanning list")
        flags = QFileDialog.ShowDirsOnly
        dirpath = str(QFileDialog.getExistingDirectory(self, title, self.lastAddedFolder, flags))
        if not dirpath:
            return
        self.lastAddedFolder = dirpath
        self.app.model.add_directory(dirpath)
        self.recentFolders.insertItem(dirpath)

    def appWillSavePrefs(self):
        self.app.prefs.directoriesWindowRect = self.geometry()

    def directoriesModelAddedFolders(self, folders):
        for folder in folders:
            self.recentFolders.insertItem(folder)

    def loadResultsTriggered(self):
        title = tr("Select a results file to load")
        files = ";;".join([tr("dupeGuru Results (*.dupeguru)"), tr("All Files (*.*)")])
        destination = QFileDialog.getOpenFileName(self, title, "", files)
        if destination:
            self.app.model.load_from(destination)
            self.app.recentResults.insertItem(destination)

    def removeFolderButtonClicked(self):
        self.directoriesModel.model.remove_selected()

    def scanButtonClicked(self):
        if self.app.model.results.is_modified:
            title = tr("Start a new scan")
            msg = tr("You have unsaved results, do you really want to continue?")
            if not self.app.confirm(title, msg):
                return
        self.app.model.start_scanning()

    def selectionChanged(self, selected, deselected):
        self._updateRemoveButton()
Example #14
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)
class Marsis:
    """Implement the main Plug in interface

    *Methods*
    * __init__ - Inizialize the plug in
    * initGui - Create the menu entries and toolbar icons inside the QGIS GUI
    * marsis_viewer - Launch the MARSIS/SHARAD viewer
    * marsis_free - Remove reference to MARSIS/SHARAD viewer dialog
    * radar_3d - Export 3D data in CSV format
    * radar_fetch - Fetch radargrams (To be implemented)
    * settings - Launch the preferences settings dialog
    * update_prefs - Update the plug in preferences
    * unload - Remove the plugin menu item and icon from QGIS GUI
    """

    def __init__(self, iface):
        """Inizialize the plug in

        :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

        #set preferences
        self.prefs = prefs.RadarPrefs()
        self.prefs.set_prefs()

        # 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',
            'Marsis_{}.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.iface = iface
        self.marsis_menu = None


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

        self.marsis_menu = QMenu(QCoreApplication.translate("marsissharadviewer", "Mars Radars"))
        self.iface.mainWindow().menuBar().insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.marsis_menu)

        icon = QIcon(':/plugins/marsissharadviewer/icon.png')
        self.marsis_viewer_action = QAction(icon, "MARSIS/SHARAD Viewer", self.iface.mainWindow())
        QObject.connect(self.marsis_viewer_action, SIGNAL("triggered()"), self.marsis_viewer)
        self.marsis_menu.addAction(self.marsis_viewer_action)

        self.depth_map_action = QAction(icon, "Make depth map", self.iface.mainWindow())
        QObject.connect(self.depth_map_action, SIGNAL("triggered()"), self.depth_map)
        self.marsis_menu.addAction(self.depth_map_action)

#        self.polar_viewer_action = QAction(icon, "Polar viewer", self.iface.mainWindow())
#        QObject.connect(self.marsis_viewer_action, SIGNAL("triggered()"), self.polar_viewer)
#        self.marsis_menu.addAction(self.polar_viewer_action)

 #       icon = QIcon(':/plugins/Marsis/icon.png')
#        self.radar_3d_action = QAction(icon, "Radar 3D", self.iface.mainWindow())
#        QObject.connect(self.radar_3d_action, SIGNAL("triggered()"), self.radar_3d)
#        self.marsis_menu.addAction(self.radar_3d_action)

#        icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png")
#        self.track_fetch_action = QAction(icon, "Marsis tracks fetch", self.iface.mainWindow())
#        QObject.connect(self.track_fetch_action, SIGNAL("triggered()"), self.track_fetch)
#        self.marsis_menu.addAction(self.track_fetch_action)

#        icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png")
#        self.radar_fetch_action = QAction(icon, "Marsis radargrams fetch", self.iface.mainWindow())
#        QObject.connect(self.radar_fetch_action, SIGNAL("triggered()"), self.radar_fetch)
#        self.marsis_menu.addAction(self.radar_fetch_action)

#        icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png")
        self.settings_action = QAction(icon, "Settings", self.iface.mainWindow())
        QObject.connect(self.settings_action, SIGNAL("triggered()"), self.settings)
        self.marsis_menu.addAction(self.settings_action)

        # Add toolbar button
#        self.iface.addToolBarIcon(self.marsis_viewer_action)

        self.toolbar = self.iface.addToolBar(u'MarsisViewer')
        self.toolbar.setObjectName(u'MarsisViewer')
        self.toolbar.addAction(self.marsis_viewer_action)


    def marsis_viewer(self):
        """Launch the MARSIS/SHARAD viewer
        """
        gc.collect()
        self.dialog = MarsisViewerDialog(self.iface, self.prefs, free_routine = self.marsis_free)
#        dialog.exec_()

    def marsis_free(self):
        """Remove reference to MARSIS/SHARAD viewer dialog
        """
        self.dialog = None
#        gc.collect()

#    def polar_viewer(self):
#        pass

    def depth_map(self):
        """
        """
        self.depth_map_run = DepthMap(self.iface)

    def radar_3d(self):
        """Export 3D data in CSV format
        """
        Radar3D(self.iface)

#    def track_fetch(self):
#        pass

    def radar_fetch(self):
        """Fetch radargrams #TODO(To be implemented)
        """
        pass

    def settings(self):
        """Launch the preferences settings dialog
        """

        self.set_dialog = SettingsDialog(self.prefs)

    def update_prefs(self):
        """Update the plug in preferences
        """

        self.prefs.set_prefs()

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

        if self.marsis_menu != None:
            self.iface.mainWindow().menuBar().removeAction(self.marsis_menu.menuAction())
        else:
            self.iface.removePluginMenu("&mmqgis", self.marsis_viewer.menuAction())

        self.iface.removeToolBarIcon(self.marsis_viewer_action)
Example #16
0
class LDMPPlugin:
    """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 and translation
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'LDMP_{}.qm'.format(locale))
        QgsMessageLog.logMessage(
            'Starting trends.earth version {} using locale "{}" in path {}.'.
            format(__version__, locale, locale_path),
            tag="trends.earth",
            level=QgsMessageLog.INFO)

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
                QgsMessageLog.logMessage("Translator installed.",
                                         tag="trends.earth",
                                         level=QgsMessageLog.INFO)

        # Declare instance attributes
        self.actions = []
        self.menu = QMenu(QApplication.translate('LDMP', u'&trends.earth'))
        self.menu.setIcon(
            QIcon(':/plugins/LDMP/trends_earth_logo_square_32x32.png'))
        self.raster_menu = self.iface.rasterMenu()
        self.raster_menu.addMenu(self.menu)
        self.toolbar = self.iface.addToolBar(u'trends.earth')

        self.dlg_settings = DlgSettings()
        self.dlg_calculate = DlgCalculate()
        self.dlg_jobs = DlgJobs()
        self.dlg_timeseries = DlgTimeseries()
        self.dlg_reporting = DlgReporting()
        self.dlg_download = DlgDownload()
        self.dlg_load_data = DlgLoadData()
        self.dlg_about = DlgAbout()

    # 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('LDMP', 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.addAction(action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.add_action(':/plugins/LDMP/icons/wrench.svg',
                        text=QApplication.translate('LDMP', u'Settings'),
                        callback=self.run_settings,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'LDMT Settings'))

        self.add_action(':/plugins/LDMP/icons/calculator.svg',
                        text=QApplication.translate('LDMP',
                                                    u'Calculate indicators'),
                        callback=self.run_calculate,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'Calculate land degradation indicators'))

        self.add_action(':/plugins/LDMP/icons/graph.svg',
                        text=QApplication.translate('LDMP', u'Plot data'),
                        callback=self.run_plot,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'Plot time series datasets'))

        self.add_action(
            ':/plugins/LDMP/icons/cloud-download.svg',
            text=QApplication.translate('LDMP',
                                        u'View Google Earth Engine tasks'),
            callback=self.get_jobs,
            parent=self.iface.mainWindow(),
            status_tip=QApplication.translate('LDMP',
                                              'View cloud processing tasks'))

        self.add_action(':/plugins/LDMP/icons/document.svg',
                        text=QApplication.translate('LDMP', u'Reporting tool'),
                        callback=self.run_reporting,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'Land degradation reporting'))

        self.add_action(':/plugins/LDMP/icons/globe.svg',
                        text=QApplication.translate('LDMP',
                                                    u'Download raw data'),
                        callback=self.run_download,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'Download raw datasets'))

        self.add_action(':/plugins/LDMP/icons/folder.svg',
                        text=QApplication.translate('LDMP', u'Load data'),
                        callback=self.load_data,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'Load local data'))

        self.add_action(':/plugins/LDMP/icons/info.svg',
                        text=QApplication.translate('LDMP', u'About'),
                        callback=self.run_about,
                        parent=self.iface.mainWindow(),
                        status_tip=QApplication.translate(
                            'LDMP', 'About trends.earth'))

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginRasterMenu(
                QApplication.translate('LDMP', u'&trends.earth'), action)
            self.iface.removeToolBarIcon(action)
        # remove the menu
        self.raster_menu.removeAction(self.menu.menuAction())
        # remove the toolbar
        del self.toolbar

    def run_settings(self):
        self.dlg_settings.show()
        result = self.dlg_settings.exec_()

    def run_download(self):
        self.dlg_download.show()
        result = self.dlg_download.exec_()

    def run_calculate(self):
        # show the dialog
        self.dlg_calculate.show()
        result = self.dlg_calculate.exec_()

    def get_jobs(self):
        # show the dialog
        self.dlg_jobs.show()
        result = self.dlg_jobs.exec_()

    def run_plot(self):
        self.dlg_timeseries.show()
        result = self.dlg_timeseries.exec_()

    def run_reporting(self):
        self.dlg_reporting.show()
        result = self.dlg_reporting.exec_()

    def load_data(self):
        self.dlg_load_data.show()
        result = self.dlg_load_data.exec_()

    def run_about(self):
        #showHelp()
        self.dlg_about.show()
        result = self.dlg_about.exec_()
Example #17
0
class QDataTableView(QTableView):
    """
    This is an actual table of waves.
    """

    def __init__(self, model=None, title="Table", *args):
        """
        Initialize the view.

        model is the DataTableModel to use.
        title is the window title.
        """

        QTableView.__init__(self, *args)
        self._app = QApplication.instance().window

        if model is None:
            model = DataTableModel()
        self.setModel(model)
        self.setWindowTitle(title)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setSelectionMode(QAbstractItemView.ContiguousSelection) # contiguous instead of extended so that we can easily insert/delete cells more easily.  See note below.
        self.setEditTriggers(QAbstractItemView.AnyKeyPressed | QAbstractItemView.SelectedClicked | QAbstractItemView.DoubleClicked)
        self.horizontalHeader().setMovable(True)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showCellContextMenu)
        
        self.verticalHeader().setContextMenuPolicy(Qt.CustomContextMenu)
        self.verticalHeader().customContextMenuRequested.connect(self.showVerticalHeaderMenu)
        
        self.setupHorizontalHeaderMenu()

    def name(self):
        """Return the name of the table."""
        return self.windowTitle()

    def renameWave(self, wave):
        """
        Create a dialog box to rename a wave.  When the dialog box is filled out and submitted, try to rename the wave.
        """

        # Setup dialog box
        renameWaveDialog = QDialog(self)
        renameWaveUi = Ui_RenameWaveDialog()
        renameWaveUi.setupUi(renameWaveDialog)
        renameWaveUi.oldWaveName.setText(wave.name())
        renameWaveDialog.setVisible(True)
        
        def saveRename():
            """Save button pressed.  Do work to save new name."""
            newName = wave.validateWaveName(str(renameWaveUi.newWaveNameLineEdit.text()))
            if str(renameWaveUi.newWaveNameLineEdit.text()) == "":
                failedMessage = QMessageBox(renameWaveDialog)
                failedMessage.setText("Cannot use a blank name.")
                failedMessage.exec_()
                renameWaveDialog.setVisible(True)
            elif self._app.waves().goodWaveName(newName) and wave.setName(newName):
                renameWaveDialog.close()
            else:
                failedMessage = QMessageBox()
                failedMessage.setText("Unable to rename wave.")
                failedMessage.exec_()
                renameWaveDialog.setVisible(True)
        
        def cancelRename():
            """Cancel button pressed."""
            renameWaveDialog.close()
        
        # connect actions
        renameWaveUi.buttons.accepted.connect(saveRename)
        renameWaveUi.buttons.rejected.connect(cancelRename)
        
    def removeWave(self, visualIndex):
        self.model().removeColumn(visualIndex)

    def addWave(self, wave, visualIndex):
        if self.model().addColumn(wave):
            # The wave was added (i.e. it did not already exist in the table)
            # We need to move the newly added column from the end to where the user clicked
            self.horizontalHeader().moveSection(self.model().columnCount() - 1, visualIndex + 1)

    def insertCells(self):
        """Insert cells into waves based on selected cells in this table."""

        # Sort by rows, so that we start at the top of the waves
        # This is the reason we only do contiguous selections, because
        # tracking which cells to insert into is really difficult otherwise
        selectedCells = self.selectedIndexes()
        selectedCells.sort(None, QModelIndex.row, False)

        # Disconnect the dataModified signal before changing anything, then connect
        # it after changing everything. This way, multiple calls are not emitted
        # in the middle, for no reason.
        # We create the waves list just in case the selectedCells indexes aren't valid
        # aftewards.
        waves = Util.uniqueList(map(lambda x: x.internalPointer(), selectedCells))
        for wave in waves:
            wave.blockSignals(True)

        for cell in selectedCells:
            try:
                cell.internalPointer().insert(cell.row(), "")
            except:
                # The cell did not exist (i.e. the wave does not extend this far)
                # but another wave does, so do not fail completely
                pass
        
        for wave in waves:
            wave.blockSignals(False)
            wave.dataModified.emit()
            wave.lengthChanged.emit()

    def deleteCells(self):
        """Delete cells from waves based on selected cells in this table."""

        # Sort by rows, inverted, so that we start by deleting at the
        # bottom of the waves, and don't screw up index values along
        # the way
        selectedCells = self.selectedIndexes()
        selectedCells.sort(None, QModelIndex.row, True)

        # Disconnect the dataModified signal before changing anything, then connect
        # it after changing everything. This way, multiple calls are not emitted
        # in the middle, for no reason.
        # We create the waves list just in case the selectedCells indexes aren't valid
        # aftewards.
        waves = Util.uniqueList(map(lambda x: x.internalPointer(), selectedCells))
        for wave in waves:
            wave.blockSignals(True)

        for cell in selectedCells:
            try:
                cell.internalPointer().pop(cell.row())
            except:
                # The cell did not exist (i.e. the wave does not extend this far)
                # but another wave does, so do not fail completely
                pass
    
        for wave in waves:
            wave.blockSignals(False)
            wave.dataModified.emit()
            wave.lengthChanged.emit()

    def showCellContextMenu(self, point):
        """Display the menu that occurs when right clicking on a table cell."""
        
        clickedCell = self.indexAt(point)

        if not clickedCell.isValid():
            # User clicked on a part of the table without a cell
            return False

        cellMenu = QMenu(self)
        insertCellAction = QAction("Insert Cells", cellMenu)
        deleteCellAction = QAction("Delete Cells", cellMenu)
        
        cellMenu.addAction(insertCellAction)
        cellMenu.addAction(deleteCellAction)

        # Connect signals
        insertCellAction.triggered.connect(self.insertCells)
        deleteCellAction.triggered.connect(self.deleteCells)

        # Display menu
        cellMenu.exec_(self.mapToGlobal(point))

        # Disconnect signals
        insertCellAction.triggered.disconnect(self.insertCells)
        deleteCellAction.triggered.disconnect(self.deleteCells)

    def showVerticalHeaderMenu(self, point):
        """Display the menu that occurs when right clicking on a vertical header."""

        rowMenu = QMenu(self)
        insertRowAction = QAction("Insert Rows", rowMenu)
        deleteRowAction = QAction("Delete Rows", rowMenu)
        
        rowMenu.addAction(insertRowAction)
        rowMenu.addAction(deleteRowAction)

        # Connect signals
        insertRowAction.triggered.connect(self.insertCells)
        deleteRowAction.triggered.connect(self.deleteCells)

        # Display menu
        rowMenu.exec_(self.mapToGlobal(point))

        # Disconnect signals
        insertRowAction.triggered.disconnect(self.insertCells)
        deleteRowAction.triggered.disconnect(self.deleteCells)

    def setupHorizontalHeaderMenu(self):
        self.horizontalHeader().setContextMenuPolicy(Qt.CustomContextMenu)
        self.horizontalHeader().customContextMenuRequested.connect(self.showHorizontalHeaderMenu)

        self.horizontalHeaderMenu = QMenu(self.horizontalHeader())
        
        # Create actions
        self.renameWaveAction = QAction("Rename Wave", self.horizontalHeaderMenu)
        self.removeWaveAction = QAction("Remove Wave", self.horizontalHeaderMenu)
        self.addWaveMenu = QMenu("Add Wave", self.horizontalHeaderMenu)

        # Add actions to menu
        self.horizontalHeaderMenu.addAction(self.addWaveMenu.menuAction())
        self.horizontalHeaderMenu.addAction(self.renameWaveAction)
        self.horizontalHeaderMenu.addAction(self.removeWaveAction)


    def showHorizontalHeaderMenu(self, point):
        """Display the menu that occurs when right clicking on a column header."""

        logicalIndex = self.horizontalHeader().logicalIndexAt(point)
        visualIndex = self.horizontalHeader().visualIndex(logicalIndex)
        
        self.selectColumn(logicalIndex)

        #print "l: " + str(logicalIndex)
        #print "v: " + str(visualIndex)
        selectedWave = self.model().waves()[logicalIndex]
        
        # Create helper functions, defined for this specific menu location
        def renameWaveHelper():
            self.renameWave(selectedWave)
        def removeWaveHelper():
            #self.removeWave(selectedWave)
            self.removeWave(visualIndex)
        def addWaveHelper(wave):
            self.addWave(wave, visualIndex)
        def addNewWaveHelper():
            wave = Wave(self._app.waves().findGoodWaveName())
            self._app.waves().addWave(wave)
            self.addWave(wave, visualIndex)


        self.addWaveMenu.clear()
        
        # Add "New Wave" entry
        newWaveAction = QAction("New Wave", self.addWaveMenu)
        self.addWaveMenu.addAction(newWaveAction)
        newWaveAction.triggered.connect(addNewWaveHelper)
        
        # Get current list of waves for "add wave to table" menu
        #for wave in self._app.waves().waves().values():
        for wave in self._app.model('appWaves').waves():
            waveAction = AddWaveAction(wave, self.addWaveMenu)
            self.addWaveMenu.addAction(waveAction)
            waveAction.addWaveClicked.connect(addWaveHelper)

        # Connect actions
        self.renameWaveAction.triggered.connect(renameWaveHelper)
        self.removeWaveAction.triggered.connect(removeWaveHelper)
        
        self.horizontalHeaderMenu.exec_(self.mapToGlobal(point))

        # Disconnect actions.  We need to do this or else there will be multiple connections
        # when we open the menu again, and the old connections will have strange visualIndex values
        self.renameWaveAction.triggered.disconnect(renameWaveHelper)
        self.removeWaveAction.triggered.disconnect(removeWaveHelper)
        for waveAction in self.addWaveMenu.actions():
            try:
                waveAction.addWaveClicked.disconnect(addWaveHelper)
            except:
                waveAction.triggered.disconnect(addNewWaveHelper)
   
    def reset(self):
        QTableView.reset(self)
        self.resizeRowsToContents()
        self.resizeColumnsToContents()

    def keyPressEvent(self, event):
        """Capture certain types of keypress events and handle them different ways."""
        # When data has been edited, move to the next row in the column and continue editing.
        currentIndex = self.currentIndex()

        #print "row: " + str(currentIndex.row()) + ", col: " + str(currentIndex.column())
        
        if currentIndex.isValid():
            if self.state() == QAbstractItemView.EditingState:
                if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
                    Util.debug(3, "DataTableView.keyPressEvent", "Enter key pressed in table")
                    newIndex = self.model().createIndex(currentIndex.row() + 1, currentIndex.column())
                    self.setCurrentIndex(newIndex)
                    self.edit(newIndex)
                    self.setCurrentIndex(newIndex)
                    return
                elif event.key() == Qt.Key_Up:
                    Util.debug(3, "DataTableView.keyPressEvent", "Up key pressed in table")
                    newIndex = self.model().createIndex(currentIndex.row() - 1, currentIndex.column())
                    #print "nrow: " + str(newIndex.row()) + ", ncol: " + str(newIndex.column())
                    #self.setCurrentIndex(newIndex)
                    self.setState(QAbstractItemView.NoState)
                elif event.key() == Qt.Key_Down:
                    Util.debug(3, "DataTableView.keyPressEvent", "Down key pressed in table")
                    newIndex = self.model().createIndex(currentIndex.row() + 1, currentIndex.column())
                    #print "nrow: " + str(newIndex.row()) + ", ncol: " + str(newIndex.column())
                    #self.setCurrentIndex(newIndex)
                    self.setState(QAbstractItemView.NoState)
        
        # Nothing found, so resort to default behavior
        QTableView.keyPressEvent(self, event)
Example #18
0
class SOSClient:
    """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')
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            '{}.qm'.format(locale))
        
        if not os.path.exists(locale_path):
            locale = locale.split('_')[0]
            locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            '{}.qm'.format(locale))
        
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

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

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

        # Declare instance attributes
        self.actions = []
        self.menu = QMenu(self.tr(u'&SOS Client'))
        self.toolbar = self.iface.addToolBar(u'SOSClient')
        self.toolbar.setObjectName(u'SOSClient')

    # 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('SOSClient', 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.addAction (action)

        self.actions.append(action)

        return action

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

        self.add_action(
            ':/plugins/SOSClient/icon_add.png',
            text=self.tr(u'SOS Client'),
            callback=self.run,
            parent=self.iface.mainWindow())

        self.add_action(
            ':/plugins/SOSClient/icon_xml.png',
            text=self.tr(u'Show XML'),
            callback=self.showLayerXml,
            parent=self.iface.mainWindow(),
            add_to_toolbar=True)
        
        self.add_action(
            ':/plugins/SOSClient/icon_plot.png',
            text=self.tr(u'Plot'),
            callback=self.showPlotDialog,
            parent=self.iface.mainWindow(),
            add_to_toolbar=True)

        self.add_action(
            ':/plugins/SOSClient/icon.png',
            text=self.tr(u'About'),
            callback=self.about,
            parent=self.iface.mainWindow(),
            add_to_toolbar=False)
        
        self.menu.setIcon(QIcon(':/plugins/SOSClient/icon.png'))
        self.iface.webMenu().addMenu (self.menu)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removeToolBarIcon(action)
        self.iface.webMenu().removeAction(self.menu.menuAction())

    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 showLayerXml (self):
        layer = self.iface.activeLayer()
        if layer == None:
            self.iface.messageBar().pushMessage (self.tr(u'SOS Client'),self.tr("You must select a layer"), QgsMessageBar.WARNING, 10)
            return
        
        xml = layer.customProperty("xml")
        if len (xml):
            dlg = XmlViewerDialog (self.iface.mainWindow(), QFile(xml), XmlHighlighter)
            dlg.show()
            dlg.exec_()
        else:
            self.iface.messageBar().pushMessage (self.tr(u'SOS Client'),self.tr("Layer have not a xml property"), QgsMessageBar.WARNING, 10)
            
    def showPlotDialog (self):
        try:
            dlg = SOSPlotDialog (self.iface.activeLayer(), parent=self.iface.mainWindow())
            dlg.show()
            dlg.exec_()
        except Exception as error:
            self.iface.messageBar().pushMessage (self.tr(u'SOS Client'),unicode(error), QgsMessageBar.CRITICAL, 10)
    
    def about(self):
        #TODO
        QMessageBox.information(self.iface.mainWindow(), self.tr(u"About SOS Client"), 
                                self.tr(u"SOS Client Plugin<br />This plugin request observations data from OGC SOS server to create a vector layer.<br />Also provides tools to plot observations data<br /><br />Author: Rubén Mosquera Varela<br />E-mail: <a href=\"mailto:[email protected]\">[email protected]</a>"))
class QuickMapServices:
    """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__).decode(sys.getfilesystemencoding())

        # initialize locale
        self.translator = QTranslator()

        self.locale = Locale.get_locale()
        locale_path = os.path.join(self.plugin_dir, "i18n", "QuickMapServices_{}.qm".format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > "4.3.3":
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.info_dlg = AboutDialog()

        # Check Contrib and User dirs
        try:
            ExtraSources.check_extra_dirs()
        except:
            error_message = self.tr("Extra dirs for %s can't be created: %s %s") % (
                PluginSettings.product_name(),
                sys.exc_type,
                sys.exc_value,
            )
            self.iface.messageBar().pushMessage(self.tr("Error"), error_message, level=QgsMessageBar.CRITICAL)

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None

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

    def initGui(self):
        # import pydevd
        # pydevd.settrace('localhost', port=9921, stdoutToServer=True, stderrToServer=True, suspend=False)

        # Register plugin layer type
        self.tileLayerType = TileLayerType(self)
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.tileLayerType)

        # Create menu
        icon_path = self.plugin_dir + "/icons/mActionAddLayer.png"
        self.menu = QMenu(self.tr(u"QuickMapServices"))
        self.menu.setIcon(QIcon(icon_path))

        self.build_menu_tree()

        # add to QGIS menu/toolbars
        self.append_menu_buttons()

    def _load_scales_list(self):
        scales_filename = os.path.join(self.plugin_dir, "scales.xml")
        scales_list = []
        # TODO: remake when fix: http://hub.qgis.org/issues/11915
        # QgsScaleUtils.loadScaleList(scales_filename, scales_list, importer_message)
        xml_root = ET.parse(scales_filename).getroot()
        for scale_el in xml_root.findall("scale"):
            scales_list.append(scale_el.get("value"))
        return scales_list

    @property
    def scales_list(self):
        if not self._scales_list:
            self._scales_list = self._load_scales_list()
        return self._scales_list

    def set_nearest_scale(self):
        # get current scale
        curr_scale = self.iface.mapCanvas().scale()
        # find nearest
        nearest_scale = sys.maxint
        for scale_str in self.scales_list:
            scale = scale_str.split(":")[1]
            scale_int = int(scale)
            if abs(scale_int - curr_scale) < abs(nearest_scale - curr_scale):
                nearest_scale = scale_int

        # set new scale
        if nearest_scale != sys.maxint:
            self.iface.mapCanvas().zoomScale(nearest_scale)

    def set_tms_scales(self):
        res = QMessageBox.question(
            self.iface.mainWindow(),
            self.tr("QuickMapServices"),
            self.tr("Set SlippyMap scales for current project? \nThe previous settings will be overwritten!"),
            QMessageBox.Yes | QMessageBox.No,
        )
        if res == QMessageBox.Yes:
            # set scales
            QgsProject.instance().writeEntry("Scales", "/ScalesList", self.scales_list)
            # activate
            QgsProject.instance().writeEntry("Scales", "/useProjectScales", True)
            # update in main window
            # ???? no way to update: http://hub.qgis.org/issues/11917

    def insert_layer(self):
        # TODO: need factory!
        layers4add = []
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias), ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            if ds.tms_y_origin_top is not None:
                service_info.yOriginTop = ds.tms_y_origin_top
            service_info.epsg_crs_id = ds.tms_epsg_crs_id
            service_info.postgis_crs_id = ds.tms_postgis_crs_id
            service_info.custom_proj = ds.tms_custom_proj
            layer = TileLayer(self, service_info, False)
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u""
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(",")
                if layers:
                    if ds.wms_turn_over:
                        layers.reverse()
                    qgis_wms_uri += "&layers=" + "&layers=".join(layers) + "&styles=" * len(layers)
            qgis_wms_uri += "&url=" + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias), KNOWN_DRIVERS.WMS.lower())
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WFS:
            qgis_wfs_uri_base = ds.wfs_url
            o = urlparse.urlparse(qgis_wfs_uri_base)
            request_attrs = dict(urlparse.parse_qsl(o.query))

            layers_str = request_attrs.get("TYPENAME", "")
            layers = layers_str.split(",")
            for layer_name in layers:
                new_request_attrs = request_attrs
                new_request_attrs["TYPENAME"] == layer_name

                url_parts = list(o)
                url_parts[4] = "&".join(["%s=%s" % (k, v) for k, v in new_request_attrs.items()])

                qgis_wfs_uri = urlparse.urlunparse(url_parts)

                layer = QgsVectorLayer(qgis_wfs_uri, "%s - %s" % (self.tr(ds.alias), layer_name), "WFS")
                layers4add.append(layer)

        for layer in layers4add:
            if not layer.isValid():
                error_message = self.tr("Layer %s can't be added to the map!") % ds.alias
                self.iface.messageBar().pushMessage(self.tr("Error"), error_message, level=QgsMessageBar.CRITICAL)
                QgsMessageLog.logMessage(error_message, level=QgsMessageLog.CRITICAL)
            else:
                # Set attribs
                layer.setAttribution(ds.copyright_text)
                layer.setAttributionUrl(ds.copyright_link)
                # Insert to bottom
                QgsMapLayerRegistry.instance().addMapLayer(layer, False)
                toc_root = QgsProject.instance().layerTreeRoot()
                toc_root.insertLayer(len(toc_root.children()), layer)
                # Save link
                self.service_layers.append(layer)
                # Set OTF CRS Transform for map
                if PluginSettings.enable_otf_3857() and ds.type == KNOWN_DRIVERS.TMS:
                    self.iface.mapCanvas().setCrsTransformEnabled(True)
                    self.iface.mapCanvas().setDestinationCrs(TileLayer.CRS_3857)

    def unload(self):
        # remove menu/
        self.remove_menu_buttons()

        # clean vars
        self.menu = None
        self.toolbutton = None
        self.service_actions = None
        self.ds_list = None
        self.groups_list = None
        self.service_layers = None
        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(TileLayer.LAYER_TYPE)

    def build_menu_tree(self):
        # Main Menu
        self.menu.clear()

        self.groups_list = GroupsList()
        self.ds_list = DataSourcesList()

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        ds_hide_list = PluginSettings.get_hide_ds_id_list()

        for ds in data_sources:
            if ds.id in ds_hide_list:
                continue
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        self.menu.addSeparator()
        icon_set_nearest_scale_path = self.plugin_dir + "/icons/mActionSettings.png"  # TODO change icon
        set_nearest_scale_act = QAction(
            QIcon(icon_set_nearest_scale_path), self.tr("Set proper scale"), self.iface.mainWindow()
        )
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + "/icons/mActionSettings.png"  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path), self.tr("Set SlippyMap scales"), self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        # self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + "/icons/mActionSettings.png"
        settings_act = QAction(QIcon(icon_settings_path), self.tr("Settings"), self.iface.mainWindow())
        self.service_actions.append(settings_act)
        settings_act.triggered.connect(self.show_settings_dialog)
        self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + "/icons/mActionAbout.png"
        info_act = QAction(QIcon(icon_about_path), self.tr("About"), self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)

    def remove_menu_buttons(self):
        """
        Remove menus/buttons from all toolbars and main submenu
        :return:
        None
        """
        # remove menu
        if self.menu:
            self.iface.webMenu().removeAction(self.menu.menuAction())
            self.iface.addLayerMenu().removeAction(self.menu.menuAction())
        # remove toolbar button
        if self.tb_action:
            self.iface.webToolBar().removeAction(self.tb_action)
            self.iface.layerToolBar().removeAction(self.tb_action)

    def append_menu_buttons(self):
        """
        Append menus and buttons to appropriate toolbar
        :return:
        """
        # add to QGIS menu
        if PluginSettings.move_to_layers_menu():
            self.iface.addLayerMenu().addMenu(self.menu)
        else:
            # need workaround for WebMenu
            _temp_act = QAction("temp", self.iface.mainWindow())
            self.iface.addPluginToWebMenu("_tmp", _temp_act)
            self.iface.webMenu().addMenu(self.menu)
            self.iface.removePluginWebMenu("_tmp", _temp_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        if PluginSettings.move_to_layers_menu():
            self.tb_action = self.iface.layerToolBar().addWidget(toolbutton)
        else:
            self.tb_action = self.iface.webToolBar().addWidget(toolbutton)

    def show_settings_dialog(self):
        settings_dlg = SettingsDialog()
        settings_dlg.exec_()
        # apply settings
        # self.remove_menu_buttons()
        self.build_menu_tree()
Example #20
0
class Marsis:
    """Implement the main Plug in interface

    *Methods*
    * __init__ - Inizialize the plug in
    * initGui - Create the menu entries and toolbar icons inside the QGIS GUI
    * marsis_viewer - Launch the MARSIS/SHARAD viewer
    * marsis_free - Remove reference to MARSIS/SHARAD viewer dialog
    * radar_3d - Export 3D data in CSV format
    * radar_fetch - Fetch radargrams (To be implemented)
    * settings - Launch the preferences settings dialog
    * update_prefs - Update the plug in preferences
    * unload - Remove the plugin menu item and icon from QGIS GUI
    """
    def __init__(self, iface):
        """Inizialize the plug in

        :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

        #set preferences
        self.prefs = prefs.RadarPrefs()
        self.prefs.set_prefs()

        # 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',
                                   'Marsis_{}.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.iface = iface
        self.marsis_menu = None

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

        self.marsis_menu = QMenu(
            QCoreApplication.translate("marsissharadviewer", "Mars Radars"))
        self.iface.mainWindow().menuBar().insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.marsis_menu)

        icon = QIcon(':/plugins/marsissharadviewer/icon.png')
        self.marsis_viewer_action = QAction(icon, "MARSIS/SHARAD Viewer",
                                            self.iface.mainWindow())
        QObject.connect(self.marsis_viewer_action, SIGNAL("triggered()"),
                        self.marsis_viewer)
        self.marsis_menu.addAction(self.marsis_viewer_action)

        self.depth_map_action = QAction(icon, "Make depth map",
                                        self.iface.mainWindow())
        QObject.connect(self.depth_map_action, SIGNAL("triggered()"),
                        self.depth_map)
        self.marsis_menu.addAction(self.depth_map_action)

        #        self.polar_viewer_action = QAction(icon, "Polar viewer", self.iface.mainWindow())
        #        QObject.connect(self.marsis_viewer_action, SIGNAL("triggered()"), self.polar_viewer)
        #        self.marsis_menu.addAction(self.polar_viewer_action)

        #       icon = QIcon(':/plugins/Marsis/icon.png')
        #        self.radar_3d_action = QAction(icon, "Radar 3D", self.iface.mainWindow())
        #        QObject.connect(self.radar_3d_action, SIGNAL("triggered()"), self.radar_3d)
        #        self.marsis_menu.addAction(self.radar_3d_action)

        #        icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png")
        #        self.track_fetch_action = QAction(icon, "Marsis tracks fetch", self.iface.mainWindow())
        #        QObject.connect(self.track_fetch_action, SIGNAL("triggered()"), self.track_fetch)
        #        self.marsis_menu.addAction(self.track_fetch_action)

        #        icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png")
        #        self.radar_fetch_action = QAction(icon, "Marsis radargrams fetch", self.iface.mainWindow())
        #        QObject.connect(self.radar_fetch_action, SIGNAL("triggered()"), self.radar_fetch)
        #        self.marsis_menu.addAction(self.radar_fetch_action)

        #        icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png")
        self.settings_action = QAction(icon, "Settings",
                                       self.iface.mainWindow())
        QObject.connect(self.settings_action, SIGNAL("triggered()"),
                        self.settings)
        self.marsis_menu.addAction(self.settings_action)

        # Add toolbar button
        #        self.iface.addToolBarIcon(self.marsis_viewer_action)

        self.toolbar = self.iface.addToolBar(u'MarsisViewer')
        self.toolbar.setObjectName(u'MarsisViewer')
        self.toolbar.addAction(self.marsis_viewer_action)

    def marsis_viewer(self):
        """Launch the MARSIS/SHARAD viewer
        """
        gc.collect()
        self.dialog = MarsisViewerDialog(self.iface,
                                         self.prefs,
                                         free_routine=self.marsis_free)
#        dialog.exec_()

    def marsis_free(self):
        """Remove reference to MARSIS/SHARAD viewer dialog
        """
        self.dialog = None
#        gc.collect()

#    def polar_viewer(self):
#        pass

    def depth_map(self):
        """
        """
        self.depth_map_run = DepthMap(self.iface)

    def radar_3d(self):
        """Export 3D data in CSV format
        """
        Radar3D(self.iface)

#    def track_fetch(self):
#        pass

    def radar_fetch(self):
        """Fetch radargrams #TODO(To be implemented)
        """
        pass

    def settings(self):
        """Launch the preferences settings dialog
        """

        self.set_dialog = SettingsDialog(self.prefs)

    def update_prefs(self):
        """Update the plug in preferences
        """

        self.prefs.set_prefs()

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

        if self.marsis_menu != None:
            self.iface.mainWindow().menuBar().removeAction(
                self.marsis_menu.menuAction())
        else:
            self.iface.removePluginMenu("&mmqgis",
                                        self.marsis_viewer.menuAction())

        self.iface.removeToolBarIcon(self.marsis_viewer_action)
Example #21
0
class MainWindow(QMainWindow):
    def __init__(self, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self._setupUi()
        self.elementTable = ElementTable(self.app.model.element_table,
                                         self.elementTableView)
        self.openedFileLabel = TextField(self.app.model.opened_file_label,
                                         self.openedFileLabelView)

        self.openButton.clicked.connect(self.actionLoadPDF.trigger)

    def _setupActions(self):
        ACTIONS = [
            ('actionLoadPDF', 'Ctrl+O', '', tr("Load PDF"),
             self.app.model.load_pdf),
        ]
        createActions(ACTIONS, self)

    def _setupMenu(self):
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 42, 22))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setTitle(tr("File"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setTitle(tr("Help"))
        self.setMenuBar(self.menubar)

        self.menuFile.addAction(self.actionLoadPDF)
        self.menuFile.addAction(self.app.actionLoadProject)
        self.menuFile.addAction(self.app.actionSaveProject)
        self.menuFile.addAction(self.app.actionQuit)
        self.menuHelp.addAction(self.app.actionShowHelp)
        self.menuHelp.addAction(self.app.actionCheckForUpdate)
        self.menuHelp.addAction(self.app.actionOpenDebugLog)
        self.menuHelp.addAction(self.app.actionAbout)

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

    def _setupUi(self):
        self.setWindowTitle(QCoreApplication.instance().applicationName())
        self.resize(900, 600)
        self.mainWidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.mainWidget)
        self.fileLayout = QHBoxLayout()
        self.openButton = QPushButton("Open File")
        # We want to leave the space to the label
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.openButton.setSizePolicy(sizePolicy)
        self.fileLayout.addWidget(self.openButton)
        self.openedFileLabelView = QLabel()
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.openedFileLabelView.setSizePolicy(sizePolicy)
        self.fileLayout.addWidget(self.openedFileLabelView)
        self.verticalLayout.addLayout(self.fileLayout)
        self.tabViewsLayout = QHBoxLayout()
        self.topTabWidget = QTabWidget()
        self.elementTableView = ElementTableView()
        self.topTabWidget.addTab(self.elementTableView, "Table")
        self.pageController = PageController(self.app.model.page_controller)
        self.topTabWidget.addTab(self.pageController, "Page")
        self.tabViewsLayout.addWidget(self.topTabWidget)
        self.bottomTabWidget = QTabWidget()
        # We want to leave the most screen estate possible to the table.
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)
        self.bottomTabWidget.setSizePolicy(sizePolicy)
        self.editTab = EditPane(self.app.model.edit_pane)
        self.bottomTabWidget.addTab(self.editTab, "Edit")
        self.buildTab = BuildPane(self.app.model.build_pane)
        self.bottomTabWidget.addTab(self.buildTab, "Build")
        self.tabViewsLayout.addWidget(self.bottomTabWidget)
        self.verticalLayout.addLayout(self.tabViewsLayout)
        self.setCentralWidget(self.mainWidget)

        self._setupActions()
        self._setupMenu()
        moveToScreenCenter(self)
Example #22
0
class MainWindow(QMainWindow):
    def __init__(self, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self._setupUi()
        self.elementTable = ElementTable(self.app.model.element_table, self.elementTableView)
        self.openedFileLabel = TextField(self.app.model.opened_file_label, self.openedFileLabelView)
        
        self.openButton.clicked.connect(self.actionLoadPDF.trigger)
    
    def _setupActions(self):
        ACTIONS = [
            ('actionLoadPDF', 'Ctrl+O', '', tr("Load PDF"), self.app.model.load_pdf),
        ]
        createActions(ACTIONS, self)
    
    def _setupMenu(self):
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 42, 22))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setTitle(tr("File"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setTitle(tr("Help"))
        self.setMenuBar(self.menubar)
        
        self.menuFile.addAction(self.actionLoadPDF)
        self.menuFile.addAction(self.app.actionLoadProject)
        self.menuFile.addAction(self.app.actionSaveProject)
        self.menuFile.addAction(self.app.actionQuit)
        self.menuHelp.addAction(self.app.actionShowHelp)
        self.menuHelp.addAction(self.app.actionCheckForUpdate)
        self.menuHelp.addAction(self.app.actionOpenDebugLog)
        self.menuHelp.addAction(self.app.actionAbout)
        
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())
    
    def _setupUi(self):
        self.setWindowTitle(QCoreApplication.instance().applicationName())
        self.resize(900, 600)
        self.mainWidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.mainWidget)
        self.fileLayout = QHBoxLayout()
        self.openButton = QPushButton("Open File")
        # We want to leave the space to the label
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.openButton.setSizePolicy(sizePolicy)
        self.fileLayout.addWidget(self.openButton)
        self.openedFileLabelView = QLabel()
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.openedFileLabelView.setSizePolicy(sizePolicy)
        self.fileLayout.addWidget(self.openedFileLabelView)
        self.verticalLayout.addLayout(self.fileLayout)
        self.tabViewsLayout = QHBoxLayout()
        self.topTabWidget = QTabWidget()
        self.elementTableView = ElementTableView()
        self.topTabWidget.addTab(self.elementTableView, "Table")
        self.pageController = PageController(self.app.model.page_controller)
        self.topTabWidget.addTab(self.pageController, "Page")
        self.tabViewsLayout.addWidget(self.topTabWidget)
        self.bottomTabWidget = QTabWidget()
        # We want to leave the most screen estate possible to the table.
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)
        self.bottomTabWidget.setSizePolicy(sizePolicy)
        self.editTab = EditPane(self.app.model.edit_pane)
        self.bottomTabWidget.addTab(self.editTab, "Edit")
        self.buildTab = BuildPane(self.app.model.build_pane)
        self.bottomTabWidget.addTab(self.buildTab, "Build")
        self.tabViewsLayout.addWidget(self.bottomTabWidget)
        self.verticalLayout.addLayout(self.tabViewsLayout)
        self.setCentralWidget(self.mainWidget)
        
        self._setupActions()
        self._setupMenu()
        moveToScreenCenter(self)
Example #23
0
class ResultWindow(QMainWindow):
    def __init__(self, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self._setupUi()
        self.resultsModel = app.RESULT_MODEL_CLASS(self.app, self.resultsView)
        self.stats = StatsLabel(app.model.stats_label, self.statusLabel)
        self._update_column_actions_status()
        
        self.menuColumns.triggered[QAction].connect(self.columnToggled)
        self.resultsView.doubleClicked.connect(self.resultsDoubleClicked)
        self.resultsView.spacePressed.connect(self.resultsSpacePressed)
        self.detailsButton.clicked.connect(self.actionDetails.triggered)
        self.dupesOnlyCheckBox.stateChanged.connect(self.powerMarkerTriggered)
        self.deltaValuesCheckBox.stateChanged.connect(self.deltaTriggered)
        self.searchEdit.searchChanged.connect(self.searchChanged)
        self.app.willSavePrefs.connect(self.appWillSavePrefs)
    
    def _setupActions(self):
        # (name, shortcut, icon, desc, func)
        ACTIONS = [
            ('actionDetails', 'Ctrl+I', '', tr("Details"), self.detailsTriggered),
            ('actionActions', '', '', tr("Actions"), self.actionsTriggered),
            ('actionPowerMarker', 'Ctrl+1', '', tr("Show Dupes Only"), self.powerMarkerTriggered),
            ('actionDelta', 'Ctrl+2', '', tr("Show Delta Values"), self.deltaTriggered),
            ('actionDeleteMarked', 'Ctrl+D', '', tr("Send Marked to Recycle Bin..."), self.deleteTriggered),
            ('actionMoveMarked', 'Ctrl+M', '', tr("Move Marked to..."), self.moveTriggered),
            ('actionCopyMarked', 'Ctrl+Shift+M', '', tr("Copy Marked to..."), self.copyTriggered),
            ('actionRemoveMarked', 'Ctrl+R', '', tr("Remove Marked from Results"), self.removeMarkedTriggered),
            ('actionReprioritize', '', '', tr("Re-Prioritize Results..."), self.reprioritizeTriggered),
            ('actionRemoveSelected', 'Ctrl+Del', '', tr("Remove Selected from Results"), self.removeSelectedTriggered),
            ('actionIgnoreSelected', 'Ctrl+Shift+Del', '', tr("Add Selected to Ignore List"), self.addToIgnoreListTriggered),
            ('actionMakeSelectedReference', 'Ctrl+Space', '', tr("Make Selected into Reference"), self.app.model.make_selected_reference),
            ('actionOpenSelected', 'Ctrl+O', '', tr("Open Selected with Default Application"), self.openTriggered),
            ('actionRevealSelected', 'Ctrl+Shift+O', '', tr("Open Containing Folder of Selected"), self.revealTriggered),
            ('actionRenameSelected', 'F2', '', tr("Rename Selected"), self.renameTriggered),
            ('actionMarkAll', 'Ctrl+A', '', tr("Mark All"), self.markAllTriggered),
            ('actionMarkNone', 'Ctrl+Shift+A', '', tr("Mark None"), self.markNoneTriggered),
            ('actionInvertMarking', 'Ctrl+Alt+A', '', tr("Invert Marking"), self.markInvertTriggered),
            ('actionMarkSelected', '', '', tr("Mark Selected"), self.markSelectedTriggered),
            ('actionExportToHTML', '', '', tr("Export To HTML"), self.app.model.export_to_xhtml),
            ('actionExportToCSV', '', '', tr("Export To CSV"), self.app.model.export_to_csv),
            ('actionSaveResults', 'Ctrl+S', '', tr("Save Results..."), self.saveResultsTriggered),
            ('actionInvokeCustomCommand', 'Ctrl+Alt+I', '', tr("Invoke Custom Command"), self.app.invokeCustomCommand),
        ]
        createActions(ACTIONS, self)
        self.actionDelta.setCheckable(True)
        self.actionPowerMarker.setCheckable(True)
        
    def _setupMenu(self):
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 630, 22))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setTitle(tr("File"))
        self.menuMark = QMenu(self.menubar)
        self.menuMark.setTitle(tr("Mark"))
        self.menuActions = QMenu(self.menubar)
        self.menuActions.setTitle(tr("Actions"))
        self.menuColumns = QMenu(self.menubar)
        self.menuColumns.setTitle(tr("Columns"))
        self.menuView = QMenu(self.menubar)
        self.menuView.setTitle(tr("View"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setTitle(tr("Help"))
        self.setMenuBar(self.menubar)
        
        self.menuActions.addAction(self.actionDeleteMarked)
        self.menuActions.addAction(self.actionMoveMarked)
        self.menuActions.addAction(self.actionCopyMarked)
        self.menuActions.addAction(self.actionRemoveMarked)
        self.menuActions.addAction(self.actionReprioritize)
        self.menuActions.addSeparator()
        self.menuActions.addAction(self.actionRemoveSelected)
        self.menuActions.addAction(self.actionIgnoreSelected)
        self.menuActions.addAction(self.actionMakeSelectedReference)
        self.menuActions.addSeparator()
        self.menuActions.addAction(self.actionOpenSelected)
        self.menuActions.addAction(self.actionRevealSelected)
        self.menuActions.addAction(self.actionInvokeCustomCommand)
        self.menuActions.addAction(self.actionRenameSelected)
        self.menuMark.addAction(self.actionMarkAll)
        self.menuMark.addAction(self.actionMarkNone)
        self.menuMark.addAction(self.actionInvertMarking)
        self.menuMark.addAction(self.actionMarkSelected)
        self.menuView.addAction(self.actionPowerMarker)
        self.menuView.addAction(self.actionDelta)
        self.menuView.addSeparator()
        self.menuView.addAction(self.actionDetails)
        self.menuView.addAction(self.app.actionIgnoreList)
        self.menuView.addAction(self.app.actionPreferences)
        self.menuHelp.addAction(self.app.actionShowHelp)
        self.menuHelp.addAction(self.app.actionCheckForUpdate)
        self.menuHelp.addAction(self.app.actionOpenDebugLog)
        self.menuHelp.addAction(self.app.actionAbout)
        self.menuFile.addAction(self.actionSaveResults)
        self.menuFile.addAction(self.actionExportToHTML)
        self.menuFile.addAction(self.actionExportToCSV)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.app.actionQuit)
        
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuMark.menuAction())
        self.menubar.addAction(self.menuActions.menuAction())
        self.menubar.addAction(self.menuColumns.menuAction())
        self.menubar.addAction(self.menuView.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())
        
        # Columns menu
        menu = self.menuColumns
        self._column_actions = []
        for index, (display, visible) in enumerate(self.app.model.result_table.columns.menu_items()):
            action = menu.addAction(display)
            action.setCheckable(True)
            action.setChecked(visible)
            action.item_index = index
            self._column_actions.append(action)
        menu.addSeparator()
        action = menu.addAction(tr("Reset to Defaults"))
        action.item_index = -1
        
        # Action menu
        actionMenu = QMenu(tr("Actions"), self.menubar)
        actionMenu.addAction(self.actionDeleteMarked)
        actionMenu.addAction(self.actionMoveMarked)
        actionMenu.addAction(self.actionCopyMarked)
        actionMenu.addAction(self.actionRemoveMarked)
        actionMenu.addSeparator()
        actionMenu.addAction(self.actionRemoveSelected)
        actionMenu.addAction(self.actionIgnoreSelected)
        actionMenu.addAction(self.actionMakeSelectedReference)
        actionMenu.addSeparator()
        actionMenu.addAction(self.actionOpenSelected)
        actionMenu.addAction(self.actionRevealSelected)
        actionMenu.addAction(self.actionInvokeCustomCommand)
        actionMenu.addAction(self.actionRenameSelected)
        self.actionActions.setMenu(actionMenu)
        self.actionsButton.setMenu(self.actionActions.menu())
    
    def _setupUi(self):
        self.setWindowTitle(tr("{} Results").format(self.app.NAME))
        self.resize(630, 514)
        self.centralwidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.setSpacing(0)
        self.actionsButton = QPushButton(tr("Actions"))
        self.detailsButton = QPushButton(tr("Details"))
        self.dupesOnlyCheckBox = QCheckBox(tr("Dupes Only"))
        self.deltaValuesCheckBox = QCheckBox(tr("Delta Values"))
        self.searchEdit = SearchEdit()
        self.searchEdit.setMaximumWidth(300)
        self.horizontalLayout = horizontalWrap([self.actionsButton, self.detailsButton,
            self.dupesOnlyCheckBox, self.deltaValuesCheckBox, None, self.searchEdit, 8])
        self.horizontalLayout.setSpacing(8)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.resultsView = ResultsView(self.centralwidget)
        self.resultsView.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.resultsView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.resultsView.setSortingEnabled(True)
        self.resultsView.verticalHeader().setVisible(False)
        h = self.resultsView.horizontalHeader()
        h.setHighlightSections(False)
        h.setMovable(True)
        h.setStretchLastSection(False)
        h.setDefaultAlignment(Qt.AlignLeft)
        self.verticalLayout.addWidget(self.resultsView)
        self.setCentralWidget(self.centralwidget)
        self._setupActions()
        self._setupMenu()
        self.statusbar = QStatusBar(self)
        self.statusbar.setSizeGripEnabled(True)
        self.setStatusBar(self.statusbar)
        self.statusLabel = QLabel(self)
        self.statusbar.addPermanentWidget(self.statusLabel, 1)
        
        if self.app.prefs.resultWindowIsMaximized:
            self.setWindowState(self.windowState() | Qt.WindowMaximized)
        else:
            if self.app.prefs.resultWindowRect is not None:
                self.setGeometry(self.app.prefs.resultWindowRect)
            else:
                moveToScreenCenter(self)
    
    #--- Private
    def _update_column_actions_status(self):
        # Update menu checked state
        menu_items = self.app.model.result_table.columns.menu_items()
        for action, (display, visible) in zip(self._column_actions, menu_items):
            action.setChecked(visible)
    
    #--- Actions
    def actionsTriggered(self):
        self.actionsButton.showMenu()
    
    def addToIgnoreListTriggered(self):
        self.app.model.add_selected_to_ignore_list()
    
    def copyTriggered(self):
        self.app.model.copy_or_move_marked(True)
    
    def deleteTriggered(self):
        self.app.model.delete_marked()
    
    def deltaTriggered(self, state=None):
        # The sender can be either the action or the checkbox, but both have a isChecked() method.
        self.resultsModel.delta_values = self.sender().isChecked()
        self.actionDelta.setChecked(self.resultsModel.delta_values)
        self.deltaValuesCheckBox.setChecked(self.resultsModel.delta_values)
    
    def detailsTriggered(self):
        self.app.show_details()
    
    def markAllTriggered(self):
        self.app.model.mark_all()
    
    def markInvertTriggered(self):
        self.app.model.mark_invert()
    
    def markNoneTriggered(self):
        self.app.model.mark_none()
    
    def markSelectedTriggered(self):
        self.app.model.toggle_selected_mark_state()
    
    def moveTriggered(self):
        self.app.model.copy_or_move_marked(False)
    
    def openTriggered(self):
        self.app.model.open_selected()
    
    def powerMarkerTriggered(self, state=None):
        # see deltaTriggered
        self.resultsModel.power_marker = self.sender().isChecked()
        self.actionPowerMarker.setChecked(self.resultsModel.power_marker)
        self.dupesOnlyCheckBox.setChecked(self.resultsModel.power_marker)
    
    def preferencesTriggered(self):
        self.app.show_preferences()
    
    def removeMarkedTriggered(self):
        self.app.model.remove_marked()
    
    def removeSelectedTriggered(self):
        self.app.model.remove_selected()
    
    def renameTriggered(self):
        index = self.resultsView.selectionModel().currentIndex()
        # Our index is the current row, with column set to 0. Our filename column is 1 and that's
        # what we want.
        index = index.sibling(index.row(), 1)
        self.resultsView.edit(index)
    
    def reprioritizeTriggered(self):
        dlg = PrioritizeDialog(self, self.app)
        result = dlg.exec()
        if result == QDialog.Accepted:
            dlg.model.perform_reprioritization()
    
    def revealTriggered(self):
        self.app.model.reveal_selected()
    
    def saveResultsTriggered(self):
        title = tr("Select a file to save your results to")
        files = tr("dupeGuru Results (*.dupeguru)")
        destination = QFileDialog.getSaveFileName(self, title, '', files)
        if destination:
            if not destination.endswith('.dupeguru'):
                destination = '{}.dupeguru'.format(destination)
            self.app.model.save_as(destination)
            self.app.recentResults.insertItem(destination)
    
    #--- Events
    def appWillSavePrefs(self):
        prefs = self.app.prefs
        prefs.resultWindowIsMaximized = self.isMaximized()
        prefs.resultWindowRect = self.geometry()
    
    def columnToggled(self, action):
        index = action.item_index
        if index == -1:
            self.app.model.result_table.columns.reset_to_defaults()
            self._update_column_actions_status()
        else:
            visible = self.app.model.result_table.columns.toggle_menu_item(index)
            action.setChecked(visible)
    
    def contextMenuEvent(self, event):
        self.actionActions.menu().exec_(event.globalPos())
    
    def resultsDoubleClicked(self, modelIndex):
        self.app.model.open_selected()
    
    def resultsSpacePressed(self):
        self.app.model.toggle_selected_mark_state()
    
    def searchChanged(self):
        self.app.model.apply_filter(self.searchEdit.text())
class QuickMapServices:
    """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__).decode(sys.getfilesystemencoding())

        # initialize locale
        self.translator = QTranslator()

        self.locale = Locale.get_locale()
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.info_dlg = AboutDialog()

        # Check Contrib and User dirs
        try:
            ExtraSources.check_extra_dirs()
        except:
            error_message = self.tr('Extra dirs for %s can\'t be created: %s %s') % (PluginSettings.product_name(),
                                                                                      sys.exc_type,
                                                                                      sys.exc_value)
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None

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

    def initGui(self):
        #import pydevd
        #pydevd.settrace('localhost', port=9921, stdoutToServer=True, stderrToServer=True, suspend=False)

        # Register plugin layer type
        self.tileLayerType = TileLayerType(self)
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.tileLayerType)

        # Create menu
        icon_path = self.plugin_dir + '/icons/mActionAddLayer.png'
        self.menu = QMenu(self.tr(u'QuickMapServices'))
        self.menu.setIcon(QIcon(icon_path))
        self.init_server_panel()

        self.build_menu_tree()

        # add to QGIS menu/toolbars
        self.append_menu_buttons()

    def _load_scales_list(self):
        scales_filename = os.path.join(self.plugin_dir, 'scales.xml')
        scales_list = []
        # TODO: remake when fix: http://hub.qgis.org/issues/11915
        # QgsScaleUtils.loadScaleList(scales_filename, scales_list, importer_message)
        xml_root = ET.parse(scales_filename).getroot()
        for scale_el in xml_root.findall('scale'):
            scales_list.append(scale_el.get('value'))
        return scales_list

    @property
    def scales_list(self):
        if not self._scales_list:
            self._scales_list = self._load_scales_list()
        return self._scales_list

    def set_nearest_scale(self):
        #get current scale
        curr_scale = self.iface.mapCanvas().scale()
        #find nearest
        nearest_scale = sys.maxint
        for scale_str in self.scales_list:
            scale = scale_str.split(':')[1]
            scale_int = int(scale)
            if abs(scale_int-curr_scale) < abs(nearest_scale - curr_scale):
                nearest_scale = scale_int

        #set new scale
        if nearest_scale != sys.maxint:
            self.iface.mapCanvas().zoomScale(nearest_scale)

    def set_tms_scales(self):
        res = QMessageBox.question(
            self.iface.mainWindow(),
            self.tr('QuickMapServices'),
            self.tr('Set SlippyMap scales for current project? \nThe previous settings will be overwritten!'),
            QMessageBox.Yes | QMessageBox.No)
        if res == QMessageBox.Yes:
            # set scales
            QgsProject.instance().writeEntry('Scales', '/ScalesList', self.scales_list)
            # activate
            QgsProject.instance().writeEntry('Scales', '/useProjectScales', True)
            # update in main window
            # ???? no way to update: http://hub.qgis.org/issues/11917

    def insert_layer(self):
        action = self.menu.sender()
        ds = action.data()
        add_layer_to_map(ds)

    def unload(self):
        # remove menu/panels
        self.remove_menu_buttons()
        self.remove_server_panel()

        # clean vars
        self.menu = None
        self.toolbutton = None
        self.service_actions = None
        self.ds_list = None
        self.groups_list = None
        self.service_layers = None
        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(TileLayer.LAYER_TYPE)

    def build_menu_tree(self):
        # Main Menu
        self.menu.clear()

        self.groups_list = GroupsList()
        self.ds_list = DataSourcesList()

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        ds_hide_list = PluginSettings.get_hide_ds_id_list()

        for ds in data_sources:
            if ds.id in ds_hide_list:
                continue
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        self.menu.addSeparator()
        icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path), self.tr('Set proper scale'), self.iface.mainWindow())
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path), self.tr('Set SlippyMap scales'), self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        #self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + '/icons/mapservices.png'
        server_panel_act = self.server_toolbox.toggleViewAction()
        server_panel_act.setIcon(QIcon(icon_settings_path))
        server_panel_act.setText(self.tr('Search QMS'))
        self.service_actions.append(server_panel_act)
        self.menu.addAction(server_panel_act)

        icon_settings_path = self.plugin_dir + '/icons/mActionSettings.png'
        settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'), self.iface.mainWindow())
        self.service_actions.append(settings_act)
        settings_act.triggered.connect(self.show_settings_dialog)
        self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + '/icons/mActionAbout.png'
        info_act = QAction(QIcon(icon_about_path), self.tr('About'), self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)


    def remove_menu_buttons(self):
        """
        Remove menus/buttons from all toolbars and main submenu
        :return:
        None
        """
        # remove menu
        if self.menu:
            self.iface.webMenu().removeAction(self.menu.menuAction())
            self.iface.addLayerMenu().removeAction(self.menu.menuAction())
        # remove toolbar button
        if self.tb_action:
            self.iface.webToolBar().removeAction(self.tb_action)
            self.iface.layerToolBar().removeAction(self.tb_action)

    def append_menu_buttons(self):
        """
        Append menus and buttons to appropriate toolbar
        :return:
        """
        # add to QGIS menu
        if PluginSettings.move_to_layers_menu():
            self.iface.addLayerMenu().addMenu(self.menu)
        else:
            # need workaround for WebMenu
            _temp_act = QAction('temp', self.iface.mainWindow())
            self.iface.addPluginToWebMenu("_tmp", _temp_act)
            self.iface.webMenu().addMenu(self.menu)
            self.iface.removePluginWebMenu("_tmp", _temp_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        if PluginSettings.move_to_layers_menu():
            self.tb_action = self.iface.layerToolBar().addWidget(toolbutton)
        else:
            self.tb_action = self.iface.webToolBar().addWidget(toolbutton)

    def show_settings_dialog(self):
        settings_dlg = SettingsDialog()
        settings_dlg.exec_()
        # apply settings
        # self.remove_menu_buttons()
        self.build_menu_tree()
        # self.append_menu_buttons()

    def init_server_panel(self):
        self.server_toolbox = QmsServiceToolbox(self.iface)
        self.iface.addDockWidget(PluginSettings.server_dock_area(), self.server_toolbox)
        self.server_toolbox.setWindowIcon(QIcon(self.plugin_dir + '/icons/mapservices.png'))
        self.server_toolbox.setVisible(PluginSettings.server_dock_visibility())
        # self.server_toolbox.setFloating(PluginSettings.dock_floating())
        # self.server_toolbox.resize(PluginSettings.dock_size())
        # self.server_toolbox.move(PluginSettings.dock_pos())
        # self.server_toolbox.setWindowIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))

    def remove_server_panel(self):
        mw = self.iface.mainWindow()
        PluginSettings.set_server_dock_area(mw.dockWidgetArea(self.server_toolbox))
        PluginSettings.set_server_dock_visibility(self.server_toolbox.isVisible())
        # PluginSettings.set_dock_floating(self.__quick_tlb.isFloating())
        # PluginSettings.set_dock_pos(self.__quick_tlb.pos())
        # PluginSettings.set_dock_size(self.__quick_tlb.size())
        # PluginSettings.set_dock_geocoder_name(self.__quick_tlb.get_active_geocoder_name())
        self.iface.removeDockWidget(self.server_toolbox)
        del self.server_toolbox
Example #25
0
class FScan(QMainWindow):
    """This is the main windown of the xc2424scan software"""
    def __init__(self, parent=None):
        """Create a new main window
        
        @param parent: Parent widget
        @type parent: QWidget
        """
        QMainWindow.__init__(self, parent)
        self.setWindowTitle(
            _("Xerox WorkCentre C2424 Scanner Utility v%s") %
            version.__version__)

        # Get the software configuration (~/.xc2424scan) or show the config
        # dialog if there is no configuration file
        self.__config_ = Config()
        if self.__config_.address is None:
            if self.__show_config_() is False:
                sys.exit()
            self.__config_.reload()

        # Set the main widget
        self.__scanWidget_ = ScanWidget(self)
        self.setCentralWidget(self.__scanWidget_)

        self.__scanWidget_.connectToScanner(self.__config_.address,
                                            self.__config_.port)

        # Create the menu
        self.__setupMenu_()

    def __setupMenu_(self):
        """Used to create the default menu"""
        # Create the menu bar
        self.__menu_ = QMenuBar(self)
        self.setMenuBar(self.__menu_)

        # File
        self.menuFile = QMenu(self.__menu_)
        self.menuFile.setTitle(_("&File"))
        self.actionQuit = QAction(self)
        self.actionQuit.setText(_("&Quit"))
        self.actionQuit.setShortcut(_("Ctrl+Q"))
        self.menuFile.addAction(self.actionQuit)

        # Settings
        self.menuSettings = QMenu(self.__menu_)
        self.menuSettings.setTitle(_("&Settings"))
        self.actionConfigure = QAction(self)
        self.actionConfigure.setText(_("&Configure xc2424scan"))
        self.menuSettings.addAction(self.actionConfigure)

        # Add the menus to the menu
        self.__menu_.addAction(self.menuFile.menuAction())
        self.__menu_.addAction(self.menuSettings.menuAction())

        self.connect(self.actionQuit, SIGNAL("triggered(bool)"), self.close)
        self.connect(self.actionConfigure, SIGNAL("triggered(bool)"),
                     self.__change_config_)

    def __change_config_(self):
        """Called when the configuration has changed and we need to reconnect
        to the scanner"""
        if self.__show_config_():
            self.__scanWidget_.connectToScanner(self.__config_.address,
                                                self.__config_.port)

    def __show_config_(self):
        """Called when we need to show the config dialog
        
        @return: True if the config has changed, False otherwise
        @rtype: bool
        """
        fconfig = FScanConfig(self)
        fconfig.config.setAddress(self.__config_.address)
        fconfig.config.setPort(self.__config_.port)

        if fconfig.exec_() == QDialog.Accepted:
            self.__config_.address = fconfig.config.getAddress()
            self.__config_.port = fconfig.config.getPort()
            return True
        else:
            return False
Example #26
0
class View(QMainWindow, auxilia.Actions, MainWindow):
    partyMode = None
    hide_window = True

    def __init__(self, modelManager, configuration, mpdclient, library, app):
        QMainWindow.__init__(self)
        self.modelManager = modelManager
        self.app = app
        self.app.commitData = self.commitData
        self.focus = time()
        self.shuttingDown = False
        self.config = configuration
        self.mpdclient = mpdclient
        self.library = library
        self.appIcon = os.path.abspath(DATA_DIR+'icons/Pythagora.png')
        self.setupUi(self)
        self.setWindowTitle('Pythagora')
        self.setWindowIcon(QIcon(self.appIcon))
        # Create standard views.
        self.playerForm = PlayerForm(self.modelManager, self.config)
        self.topLayout.addWidget(self.playerForm)
        self.connect(self.modelManager.playerState, SIGNAL('currentSongChanged'), self.playerForm.updateSong)
        self.connect(self.modelManager.playerState, SIGNAL('volumeChanged'), self.playerForm.setVolume)
        self.connect(self.modelManager.playerState, SIGNAL('progressChanged'), self.playerForm.setProgress)
        self.connect(self.modelManager.playerState, SIGNAL('playStateChanged'), self.playerForm.setPlayState)
        self.connect(self.modelManager.playerState, SIGNAL('bitrateChanged'), self.playerForm.songLabel.setBitrate)
        self.dbusNotifications = DBusNotifications(self.config)
        self.connect(self.modelManager.playerState, SIGNAL('currentSongChanged'), self.dbusNotifications.showNotification)
        self.toolBarLayout = self.playerForm.toolBarLayout
        self.currentList = CurrentPlaylistForm.CurrentPlaylistForm(
                self.modelManager, self, self.app, self.config)
        self.currentListLayout.addWidget(self.currentList)
        self.connect(self.playerForm.play, SIGNAL('clicked(bool)'), self.modelManager.playerState.playPause)
        self.connect(self.playerForm.back, SIGNAL('clicked(bool)'), self.modelManager.playerState.previousSong)
        self.connect(self.playerForm.forward, SIGNAL('clicked(bool)'), self.modelManager.playerState.nextSong)
        self.connect(self.playerForm.stop, SIGNAL('clicked(bool)'), self.modelManager.playerState.stop)
        self.connect(self.playerForm.volume, SIGNAL('valueChanged(int)'), self.modelManager.playerState.setVolume)

        # Standard toolbar buttons.
        self.exitAction = self.actionExit(self, self.app.quit)
        self.exitButton = QToolButton()
        self.exitButton.setAutoRaise(True)
        self.exitButton.setIconSize(QSize(22, 22))
        self.exitButton.setDefaultAction(self.exitAction)
        self.settingsAction = self.actionSettings(self, self.showConfig)
        self.settingsButton = QToolButton()
        self.settingsButton.setAutoRaise(True)
        self.settingsButton.setIconSize(QSize(22, 22))
        self.settingsButton.setDefaultAction(self.settingsAction)
        # Create 'Connect to' menu.
        self.menuConnect = QMenu('Connect To')
        self.menuConnect.menuAction().setIcon(auxilia.PIcon('network-disconnect'))
        self.connectButton = QToolButton()
        self.connectButton.setAutoRaise(True)
        self.connectButton.setIconSize(QSize(22, 22))
        self.connectButton.setPopupMode(QToolButton.InstantPopup)
        self.connectButton.setIcon(auxilia.PIcon('network-disconnect'))
        self.connectButton.setText('Connect To')
        self.connectButton.setMenu(self.menuConnect)
        # Create 'MDP' menu.
        self.menuMPD = QMenu('MPD')
        self.menuMPD.menuAction().setIcon(auxilia.PIcon('network-workgroup'))
        self.connect(self.menuConnect, SIGNAL('aboutToShow()'), self._buildConnectTo)
        self.mpdButton = QToolButton()
        self.mpdButton.setAutoRaise(True)
        self.mpdButton.setIconSize(QSize(22, 22))
        self.mpdButton.setPopupMode(QToolButton.InstantPopup)
        self.mpdButton.setIcon(auxilia.PIcon('network-workgroup'))
        self.mpdButton.setText('MPD')
        self.mpdButton.setMenu(self.menuMPD)
        self.reloadLibrary = self.actionLibReload(self.menuMPD, lambda: self.modelManager.reloadLibrary(True))
        self.updateLibrary = self.actionLibUpdate(self.menuMPD, lambda: self.mpdclient.send('update'))
        self.rescanLibrary = self.actionLibRescan(self.menuMPD, lambda: self.mpdclient.send('rescan'))
        # Create 'Outputs' menu.
        self.menuOutputs = QMenu('Outputs')
        self.menuOutputs.menuAction().setIcon(auxilia.PIcon('audio-card'))
        self.connect(self.menuOutputs, SIGNAL('aboutToShow()'), self._buildOutputs)
        self.outputsButton = QToolButton()
        self.outputsButton.setAutoRaise(True)
        self.outputsButton.setIconSize(QSize(22, 22))
        self.outputsButton.setPopupMode(QToolButton.InstantPopup)
        self.outputsButton.setIcon(auxilia.PIcon('audio-card'))
        self.outputsButton.setText('Outputs')
        self.outputsButton.setMenu(self.menuOutputs)
        # Fill Toolbar.
        self.toolBarLayout.addWidget(self.exitButton)
        self.toolBarLayout.addWidget(self.settingsButton)
        self.toolBarLayout.addWidget(self.connectButton)
        self.toolBarLayout.addWidget(self.outputsButton)
        self.toolBarLayout.addWidget(self.mpdButton)
        self.toolBarLayout.addStretch(1)
        # Fill Statusbar.
        self.serverLabel = QLabel('Not connected')
        self.numSongsLabel = QLabel('Songs')
        self.playTimeLabel = QLabel('playTime')
        self.statusbar.addWidget(self.serverLabel)
        self.statusbar.addPermanentWidget(self.numSongsLabel)
        self.statusbar.addPermanentWidget(self.playTimeLabel)

        # Set up trayicon and menu.
        if KDE:
            self.trayIcon = KTrayIcon(self.appIcon, self)
        else:
            self.trayIcon = QTrayIcon(self.appIcon, self)
        outputsMenuAction = self.menuOutputs.menuAction()
        connectMenuAction = self.menuConnect.menuAction()
        self.trayIcon.addMenuItem(outputsMenuAction)
        self.trayIcon.addMenuItem(connectMenuAction)
        self.trayIcon.addMenuItem(self.settingsAction)
        self.connect(self.trayIcon, SIGNAL('activate()'), self.toggleHideRestore)
        self.connect(self.trayIcon, SIGNAL('secondaryActivateRequested(QPoint)'), self._playPause)
        self.connect(self.trayIcon, SIGNAL('scrollRequested(int, Qt::Orientation)'),
                lambda amount: self.modelManager.playerState.volumeUp((amount+30)/60))
        self.connect(self.modelManager.playerState, SIGNAL('playStateChanged'), self.trayIcon.setState)
        self.connect(self.playerForm, SIGNAL('tooltipChanged'), self.trayIcon.setToolTip)

        self.connect(self.tabs, SIGNAL('currentChanged(int)'), self._tabsIndexChanged)
        self.connect(self.tabs.tabBar(), SIGNAL('tabMoved(int,int)'), self._tabMoved)
        self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'), self._storeSplitter)

        # Apply configuration.
        self.resize(configuration.mgrSize)
        self.splitter.setSizes(configuration.mgrSplit)
        self.tabs.setCurrentIndex(configuration.tabsIndex)

        self.closeEvent = self.closeEvent
        self.connect(self.app,SIGNAL('aboutToQuit()'),self.shutdown)

#==============================================================================
# Code for switching tabs on drag & drop. (__init__() continues)
#==============================================================================

        # Instantiate timer
        self.tabTimer = QTimer()
        self.connect(self.tabTimer, SIGNAL('timeout()'), self._selectTab)

        # Overload the default dragEvents.
        self.tabs.dragLeaveEvent = self.dragLeaveEvent
        self.tabs.dragEnterEvent = self.dragEnterEvent
        self.tabs.dragMoveEvent = self.dragMoveEvent

    def dragEnterEvent(self, event):
        '''Starts timer on enter and sets first position.'''
        self.tabPos = event.pos()
        event.accept()
        self.tabTimer.start(500)

    def dragLeaveEvent(self, event):
        '''If the mouse leaves the tabWidget stop the timer.'''
        self.tabTimer.stop()

    def dragMoveEvent(self, event):
        '''Keep track of the mouse and change the position, restarts the timer when moved.'''
        tabPos = event.pos()
        moved = tabPos.manhattanLength() - self.tabPos.manhattanLength()
        if moved > 7 or moved < -7:
            self.tabTimer.start(500)
        self.tabPos = tabPos


    def _selectTab(self):
        '''Changes the view to the tab where the mouse was hovering above.'''
        index = self.tabs.tabBar().tabAt(self.tabPos)
        self.tabs.setCurrentIndex(index)
        self.tabTimer.stop()


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

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_F11:
            self._togglePartymode()
        else:
            super(View, self).keyPressEvent(event)

    def createPluginViews(self):
        '''Set all plugin tabs up.'''
        loadedPlugins = {}
        for plugin in plugins.allPlugins:
            plugin = plugin.getWidget(self.modelManager, self.mpdclient, self.config, self.library)
            if plugin:
                loadedPlugins[plugin.moduleName] = plugin
        for name in self.config.tabOrder:
            if name in loadedPlugins:
                plugin = loadedPlugins.pop(name)
                self.tabs.addTab(plugin, auxilia.PIcon(plugin.moduleIcon), plugin.moduleName)
        for plugin in loadedPlugins.values():
            self.tabs.addTab(plugin, auxilia.PIcon(plugin.moduleIcon), plugin.moduleName)
            order = self.config.tabOrder
            order.append(plugin.moduleName)
            self.config.tabOrder = order

    def shutdown(self):
        self.shuttingDown = True
        self.app.processEvents()
        self.mpdclient.disconnect()
        self.config.mgrSize = self.size()
        print 'debug: shutdown finished'

    def commitData(self, sessionManager):
        self.hide_window = False
        QApplication.commitData(self.app, sessionManager)

    def showConfig(self):
        self.config.showConfiguration(self)

    def closeEvent(self, event):
        '''Catch MainWindow's close event so we can hide it instead.'''
        if self.hide_window:
            self.hide()
            event.ignore()
        else:
            QMainWindow.closeEvent(self, event)

    def _storeSplitter(self):
        self.config.mgrSplit = self.splitter.sizes()

    def _tabsIndexChanged(self, value):
        self.config.tabsIndex = self.tabs.currentIndex()

    def _tabMoved(self, old, new):
        print "DEBUG: Tab from", old, "moved to", new
        order = self.config.tabOrder
        order.insert(new, order.pop(old))
        self.config.tabOrder = order

    def toggleHideRestore(self):
        '''Show or hide the window based on some parameters. We can detect
        when we are obscured and come to the top. In other cases we hide if
        mapped and show if not.
        '''
        if KDE:
            if KWindowSystem.activeWindow() == self.winId() and self.isVisible():
                self.hide()
            else:
                self.show()
                KWindowSystem.forceActiveWindow(self.winId())
        else:
            if self.isVisible():
                self.hide()
            else: self.show()

    def _playPause(self):
        self.playerForm.play.emit(SIGNAL('clicked(bool)'), True)

    def _buildConnectTo(self):
        self.menuConnect.clear()
        self.menuConnect.addAction(auxilia.PIcon('dialog-cancel'), 'None (disconnect)')
        connected = self.mpdclient.connected()
        for server in self.config.knownHosts:
            if connected and self.config.server and self.config.server[0] == server:
                icon = auxilia.PIcon('network-connect')
            else: icon = auxilia.PIcon('network-disconnect')
            self.menuConnect.addAction(icon, server)

    def _buildOutputs(self):
        self.menuOutputs.clear()
        if self.mpdclient.connected():
            print 'debug: Building output menu.'
            for output in self.mpdclient.outputs():
                action = QAction(output.get('outputname', 'No name'), self.menuOutputs)
                action.setCheckable(True)
                action.setChecked(output.get('outputenabled', '0') == '1')
                action.outputid = output.get('outputid')
                self.menuOutputs.addAction(action)

    def _togglePartymode(self):
        if self.partyMode is None:
            self.partyMode = self.isMaximized()
            self.showFullScreen()
        else:
            if self.partyMode == True:
                self.showNormal()
                self.showMaximized()
            else:
                self.showNormal()
            self.partyMode = None
Example #27
0
class BrowserWindow(QMainWindow):
    def retranslateUi(self):
        self.setWindowTitle(
            QApplication.translate("self", "self", None,
                                   QApplication.UnicodeUTF8))
        self.menuFile.setTitle(
            QApplication.translate("self", "&File", None,
                                   QApplication.UnicodeUTF8))
        self.menuView.setTitle(
            QApplication.translate("self", "&View", None,
                                   QApplication.UnicodeUTF8))
        self.menuEdit.setTitle(
            QApplication.translate("self", "&Edit", None,
                                   QApplication.UnicodeUTF8))
        self.menuHelp.setTitle(
            QApplication.translate("self", "&Help", None,
                                   QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(
            QApplication.translate("self", "toolBar", None,
                                   QApplication.UnicodeUTF8))
        self.actionHome.setText(
            QApplication.translate("self", "&Home", None,
                                   QApplication.UnicodeUTF8))
        self.actionHome.setToolTip(
            QApplication.translate("self", "Go Home", None,
                                   QApplication.UnicodeUTF8))
        self.actionShowMenu.setText(
            QApplication.translate("self", "Show &Menu", None,
                                   QApplication.UnicodeUTF8))
        self.actionShowToolbar.setText(
            QApplication.translate("self", "Show &Toolbar", None,
                                   QApplication.UnicodeUTF8))
        self.actionClose.setText(
            QApplication.translate("self", "&Close", None,
                                   QApplication.UnicodeUTF8))
        self.actionModifyWebapp.setText(
            QApplication.translate("self", "Modify &Webapp", None,
                                   QApplication.UnicodeUTF8))
        self.actionEditPreferences.setText(
            QApplication.translate("self", "Edit &Preferences", None,
                                   QApplication.UnicodeUTF8))
        self.actionPrint.setText(
            QApplication.translate("self", "&Print", None,
                                   QApplication.UnicodeUTF8))
        self.actionAbout.setText(
            QApplication.translate("self", "&About", None,
                                   QApplication.UnicodeUTF8))

    def __init__(self, appid, base, name):
        super(BrowserWindow, self).__init__()

        self.appid = appid
        self.name = name
        self.original_name = name
        self.base = base

        # Main widgets
        self.centralwidget = QWidget(self)
        self.gridLayout_2 = QGridLayout(self.centralwidget)
        self.setCentralWidget(self.centralwidget)
        self.urlLineEdit = QLineEdit(self)
        self.progressBar = QProgressBar(self)

        # Custom webview
        self.page = LocalWebPage()
        self.page.setFeaturePermission(self.page.mainFrame(),
                                       LocalWebPage.Notifications,
                                       LocalWebPage.PermissionGrantedByUser)
        self.webkitNotifications = WebkitNotifications(self)

        self.webViewMain = LocalWebView(self.centralwidget)
        self.webViewMain.setPage(self.page)
        self.gridLayout_2.addWidget(self.webViewMain, 0, 0, 1, 1)

        self.webViewMain.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)

        self.menubar = QMenuBar(self)
        self.menuFile = QMenu(self.menubar)
        self.menuView = QMenu(self.menubar)
        self.menuEdit = QMenu(self.menubar)
        self.menuHelp = QMenu(self.menubar)
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.setStatusBar(self.statusbar)
        self.toolBar = QToolBar(self)
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        self.addToolBar(Qt.TopToolBarArea, self.toolBar)

        # Create actions
        self.actionOpenLinkInNewWindow = self.page.action(
            self.page.OpenLinkInNewWindow)
        self.actionOpenLinkInNewWindow.setText(
            tr('BrowserWindow', 'Open in &Browser'))
        self.actionBack = self.page.action(self.page.Back)
        self.actionForward = self.page.action(self.page.Forward)
        self.actionStop = self.page.action(self.page.Stop)
        self.actionReload = self.page.action(self.page.Reload)
        self.actionHome = QAction(self)
        self.actionShowMenu = QAction(self)
        self.actionShowMenu.setCheckable(True)
        self.actionShowToolbar = QAction(self)
        self.actionShowToolbar.setCheckable(True)
        self.actionClose = QAction(self)
        self.actionModifyWebapp = QAction(self)
        self.actionEditPreferences = QAction(self)
        self.actionPrint = QAction(self)
        self.actionSaveLink = self.page.action(self.page.DownloadLinkToDisk)
        self.actionSaveLink.setEnabled(False)
        self.actionAbout = QAction(self)

        # Populate menu and toolbars
        self.menuFile.addAction(self.actionHome)
        self.menuFile.addAction(self.actionBack)
        self.menuFile.addAction(self.actionForward)
        self.menuFile.addAction(self.actionStop)
        self.menuFile.addAction(self.actionReload)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionPrint)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionClose)
        self.menuView.addAction(self.actionShowMenu)
        self.menuView.addAction(self.actionShowToolbar)
        self.menuView.addSeparator()
        self.menuEdit.addAction(self.actionModifyWebapp)
        #self.menuEdit.addAction(self.actionEditPreferences)
        self.menuHelp.addAction(self.actionAbout)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuView.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())
        self.toolBar.addAction(self.actionHome)
        self.toolBar.addAction(self.actionBack)
        self.toolBar.addAction(self.actionForward)
        self.toolBar.addWidget(self.urlLineEdit)

        self.toolBar.addAction(self.actionStop)
        self.toolBar.addAction(self.actionReload)

        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)

        self.setWindowTitle(self.name)

        # Set up cookie jar that persists sessions
        self.cookieJar = PersistableCookieJar(self, identifier=self.appid)
        self.cookieJar.load()
        self.webViewMain.page().networkAccessManager().setCookieJar(
            self.cookieJar)

        # Set up link delegation so that external links open in web browser.
        self.webViewMain.page().setLinkDelegationPolicy(
            QWebPage.DelegateExternalLinks)

        self.desktopEntry = desktop.getEntry(self.appid)

        # Set icons for actions; this can't be done in the designer, AFAICT
        self.actionHome.setIcon(QIcon.fromTheme('go-home'))
        self.actionAbout.setIcon(QIcon.fromTheme('help-about'))

        # Set up shortcuts
        self.actionStop.setShortcut(Qt.Key_Escape)
        self.actionBack.setShortcut(QKeySequence.Back)
        self.actionForward.setShortcut(QKeySequence.Forward)
        self.actionReload.setShortcut(QKeySequence.Refresh)
        self.actionHome.setShortcut('Ctrl+Home')
        self.actionShowMenu.setShortcut('Ctrl+m')
        self.actionShowToolbar.setShortcut('Ctrl+t')
        self.actionPrint.setShortcut(QKeySequence.Print)

        self.backShortcut = QShortcut(self)
        self.backShortcut.setKey(Qt.Key_Back)
        self.backShortcut.activated.connect(self.webViewMain.back)

        self.forwardShortcut = QShortcut(self)
        self.forwardShortcut.setKey(Qt.Key_Forward)
        self.forwardShortcut.activated.connect(self.webViewMain.forward)

        # Set up context menu
        self.webViewMain.setContextMenuPolicy(Qt.CustomContextMenu)
        self.webViewMain.customContextMenuRequested.connect(self.showMenu)

        # Setup statusbar and toolbar
        for c in self.statusBar().children()[0].children():
            c.removeWidget(c)
        self.statusBar().addPermanentWidget(self.progressBar, 1)

        self.actionShowToolbar.setChecked(True)
        self.actionShowMenu.setChecked(True)

        # Icon
        if self.desktopEntry.hasKey('Icon'):
            self.icon = QIcon(self.desktopEntry.get('Icon'))
            self.setWindowIcon(self.icon)
        else:
            self.webViewMain.iconChanged.connect(self.setWindowIcon)

        # Set up events
        if self.desktopEntry.get('X-%s-menu-enabled' % APP_NAME) == '0':
            self.actionShowMenu.setChecked(False)
        else:
            self.actionShowMenu.setChecked(True)
        if self.desktopEntry.get('X-%s-toolbar-enabled' % APP_NAME) == '0':
            self.actionShowToolbar.setChecked(False)
        else:
            self.actionShowToolbar.setChecked(True)

        self.webViewMain.linkClicked.connect(self._onLinkClick)
        self.webViewMain.titleChanged.connect(self.setWindowTitle)
        self.webViewMain.loadProgress.connect(self._setLoadingStatus)
        self.webViewMain.urlChanged.connect(
            lambda x: self.urlLineEdit.setText(x.toString()))
        self.page.printRequested.connect(self._onPrint)
        self.page.loadFinished.connect(self._loadingFinished)
        self.actionHome.triggered.connect(
            lambda x: self.webViewMain.load(QUrl(self.base)))
        self.actionClose.triggered.connect(self.close)
        self.actionPrint.triggered.connect(self._onPrint)
        self.urlLineEdit.returnPressed.connect(self._onUrlEdit)
        self.actionShowToolbar.triggered.connect(self._onShowToolbar)
        self.actionShowMenu.triggered.connect(self._onShowMenu)
        self.actionAbout.triggered.connect(lambda x: about.show(self))
        self.actionModifyWebapp.triggered.connect(self._onModify)

        self._onShowMenu()
        self._onShowToolbar()

        try:
            self.resize(int(self.desktopEntry.getWindowWidth()),
                        int(self.desktopEntry.getWindowHeight()))
        except (ValueError, TypeError):
            self.resize(800, 600)

        # Load first page
        self.webViewMain.load(QUrl(base))

        self.editor = SiteEditorWindow(self.desktopEntry, isNew=False)

    def _onModify(self):
        self.editor.show()

    def closeEvent(self, qCloseEvent):
        self.desktopEntry.setWindowWidth(self.width())
        self.desktopEntry.setWindowHeight(self.height())
        self.desktopEntry.write()

    def _onPrint(self):
        printer = QPrinter()
        dialog = QPrintDialog(printer, self)
        if dialog.exec_() != QDialog.Accepted:
            return
        self.page.mainFrame().print_(printer)

    def _loadingFinished(self):
        # TODO: Add user scripts here
        # TODO: Add user styles here

        # Override window.webkitNotifications
        self.page.mainFrame().addToJavaScriptWindowObject(
            "_x_webplier_webkitNotifications", self.webkitNotifications)
        self.page.mainFrame().evaluateJavaScript(
            WebkitNotifications.JAVASCRIPT)

    def _setLoadingStatus(self, value):
        if value < 100:
            self.progressBar.setValue(value)
            self.progressBar.show()
            self.statusBar().show()
            self.actionReload.setVisible(False)
            self.actionStop.setVisible(True)
        else:
            self.page.setFeaturePermission(
                self.page.mainFrame(), LocalWebPage.Notifications,
                LocalWebPage.PermissionGrantedByUser)
            self.progressBar.hide()
            self.statusBar().hide()
            self.actionReload.setVisible(True)
            self.actionStop.setVisible(False)

    def _onUrlEdit(self):
        url = unicode(self.urlLineEdit.text())
        qurl = QUrl(url)
        if not qurl.scheme():
            qurl.setScheme('http')

        self.webViewMain.load(qurl)

    def _onLinkClick(self, qurl):
        url = unicode(qurl.toString())
        if not unicode(url).startswith(self.base):
            webbrowser.open(url, 1)
        else:
            self.webViewMain.load(qurl)

    def _onShowToolbar(self):
        if self.actionShowToolbar.isChecked():
            self.toolBar.show()
            self.desktopEntry.set('X-%s-toolbar-enabled' % APP_NAME, '1')
        else:
            self.toolBar.hide()
            self.desktopEntry.set('X-%s-toolbar-enabled' % APP_NAME, '0')

    def _onShowMenu(self):
        if self.actionShowMenu.isChecked():
            self.menubar.show()
            self.desktopEntry.set('X-%s-menu-enabled' % APP_NAME, '1')
        else:
            self.menubar.hide()
            self.desktopEntry.set('X-%s-menu-enabled' % APP_NAME, '0')

    def showMenu(self, point):
        m = self.webViewMain.page().createStandardContextMenu()

        # TODO: Make this less awful and fragile
        for a in m.actions():
            if a == self.actionSaveLink:
                m.removeAction(a)

        m.addSeparator()
        m.addAction(self.actionShowMenu)
        m.addAction(self.actionShowToolbar)
        globalpos = self.mapToParent(point)

        m.exec_(globalpos)
Example #28
0
class MainWindow(QMainWindow):
    def __init__(self, doc):
        QMainWindow.__init__(self, None)
        self.doc = doc
        self.app = doc.app
        
        self._setupUi()
        
        # Create base elements
        self.model = MainWindowModel(document=doc.model)
        self.model2view = {}
        self.apanel = AccountPanel(mainwindow=self)
        self.tpanel = TransactionPanel(mainwindow=self)
        self.mepanel = MassEditionPanel(mainwindow=self)
        self.scpanel = SchedulePanel(mainwindow=self)
        self.bpanel = BudgetPanel(mainwindow=self)
        self.cdrpanel = CustomDateRangePanel(mainwindow=self)
        self.arpanel = AccountReassignPanel(mainwindow=self)
        self.expanel = ExportPanel(mainwindow=self)
        self.alookup = Lookup(self, model=self.model.account_lookup)
        self.clookup = Lookup(self, model=self.model.completion_lookup)
        self.drsel = DateRangeSelector(mainwindow=self, view=self.dateRangeSelectorView)
        self.sfield = SearchField(model=self.model.search_field, view=self.searchLineEdit)
        self.recentDocuments = Recent(self.app, 'recentDocuments')
        self.recentDocuments.addMenu(self.menuOpenRecent)
        
        self.model.view = self
        self.model.connect()
        
        self._updateUndoActions()
        self._bindSignals()
    
    def _setupUi(self): # has to take place *before* base elements creation
        self.setWindowTitle("moneyGuru")
        self.resize(700, 580)
        self.centralwidget = QtGui.QWidget(self)
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setMargin(0)
        self.topBar = QtGui.QWidget(self.centralwidget)
        self.horizontalLayout_2 = QHBoxLayout(self.topBar)
        self.horizontalLayout_2.setContentsMargins(2, 0, 2, 0)
        spacerItem = QtGui.QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.dateRangeSelectorView = DateRangeSelectorView(self.topBar)
        self.dateRangeSelectorView.setMinimumSize(QSize(220, 0))
        self.horizontalLayout_2.addWidget(self.dateRangeSelectorView)
        spacerItem1 = QtGui.QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.searchLineEdit = SearchEdit(self.topBar)
        self.searchLineEdit.setMaximumSize(QSize(240, 16777215))
        self.horizontalLayout_2.addWidget(self.searchLineEdit)
        self.verticalLayout.addWidget(self.topBar)
        self.tabBar = QTabBar(self.centralwidget)
        self.tabBar.setMinimumSize(QSize(0, 20))
        self.verticalLayout.addWidget(self.tabBar)
        self.mainView = QtGui.QStackedWidget(self.centralwidget)
        self.verticalLayout.addWidget(self.mainView)
        
        # Bottom buttons & status label
        self.bottomBar = QtGui.QWidget(self.centralwidget)
        self.horizontalLayout = QHBoxLayout(self.bottomBar)
        self.horizontalLayout.setMargin(2)
        self.horizontalLayout.setMargin(0)
        self.newItemButton = QPushButton(self.bottomBar)
        buttonSizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        buttonSizePolicy.setHorizontalStretch(0)
        buttonSizePolicy.setVerticalStretch(0)
        buttonSizePolicy.setHeightForWidth(self.newItemButton.sizePolicy().hasHeightForWidth())
        self.newItemButton.setSizePolicy(buttonSizePolicy)
        self.newItemButton.setIcon(QIcon(QPixmap(':/plus_8')))
        self.horizontalLayout.addWidget(self.newItemButton)
        self.deleteItemButton = QPushButton(self.bottomBar)
        self.deleteItemButton.setSizePolicy(buttonSizePolicy)
        self.deleteItemButton.setIcon(QIcon(QPixmap(':/minus_8')))
        self.horizontalLayout.addWidget(self.deleteItemButton)
        self.editItemButton = QPushButton(self.bottomBar)
        self.editItemButton.setSizePolicy(buttonSizePolicy)
        self.editItemButton.setIcon(QIcon(QPixmap(':/info_gray_12')))
        self.horizontalLayout.addWidget(self.editItemButton)
        self.horizontalLayout.addItem(horizontalSpacer(size=20))
        self.graphVisibilityButton = QPushButton()
        self.graphVisibilityButton.setSizePolicy(buttonSizePolicy)
        self.graphVisibilityButton.setIcon(QIcon(QPixmap(':/graph_visibility_on_16')))
        self.horizontalLayout.addWidget(self.graphVisibilityButton)
        self.piechartVisibilityButton = QPushButton()
        self.piechartVisibilityButton.setSizePolicy(buttonSizePolicy)
        self.piechartVisibilityButton.setIcon(QIcon(QPixmap(':/piechart_visibility_on_16')))
        self.horizontalLayout.addWidget(self.piechartVisibilityButton)
        self.columnsVisibilityButton = QPushButton()
        self.columnsVisibilityButton.setSizePolicy(buttonSizePolicy)
        self.columnsVisibilityButton.setIcon(QIcon(QPixmap(':/columns_16')))
        self.horizontalLayout.addWidget(self.columnsVisibilityButton)
        
        self.statusLabel = QtGui.QLabel(tr("Status"))
        self.statusLabel.setAlignment(Qt.AlignCenter)
        self.horizontalLayout.addWidget(self.statusLabel)
        self.verticalLayout.addWidget(self.bottomBar)
        
        
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 700, 20))
        self.menuFile = QMenu(tr("File"))
        self.menuOpenRecent = QMenu(tr("Open Recent"))
        self.menuView = QMenu(tr("View"))
        self.menuDateRange = QMenu(tr("Date Range"))
        self.menuEdit = QMenu(tr("Edit"))
        self.menuHelp = QMenu(tr("Help"))
        self.setMenuBar(self.menubar)
        self.actionOpenDocument = QAction(tr("Open..."), self)
        self.actionOpenDocument.setShortcut("Ctrl+O")
        self.actionShowNetWorth = QAction(tr("Net Worth"), self)
        self.actionShowNetWorth.setShortcut("Ctrl+1")
        self.actionShowNetWorth.setIcon(QIcon(QPixmap(':/balance_sheet_48')))
        self.actionShowProfitLoss = QAction(escapeamp(tr("Profit & Loss")), self)
        self.actionShowProfitLoss.setShortcut("Ctrl+2")
        self.actionShowProfitLoss.setIcon(QIcon(QPixmap(':/income_statement_48')))
        self.actionShowTransactions = QAction(tr("Transactions"), self)
        self.actionShowTransactions.setShortcut("Ctrl+3")
        self.actionShowTransactions.setIcon(QIcon(QPixmap(':/transaction_table_48')))
        self.actionShowSelectedAccount = QAction(tr("Show Account"), self)
        self.actionShowSelectedAccount.setShortcut("Ctrl+]")
        self.actionNewItem = QAction(tr("New Item"), self)
        self.actionNewItem.setShortcut("Ctrl+N")
        self.actionDeleteItem = QAction(tr("Remove Selected"), self)
        self.actionEditItem = QAction(tr("Show Info"), self)
        self.actionEditItem.setShortcut("Ctrl+I")
        self.actionToggleGraph = QAction(tr("Toggle Graph"), self)
        self.actionToggleGraph.setShortcut("Ctrl+Alt+G")
        self.actionTogglePieChart = QAction(tr("Toggle Pie Chart"), self)
        self.actionTogglePieChart.setShortcut("Ctrl+Alt+P")
        self.actionMoveUp = QAction(tr("Move Up"), self)
        self.actionMoveUp.setShortcut("Ctrl++")
        self.actionMoveDown = QAction(tr("Move Down"), self)
        self.actionMoveDown.setShortcut("Ctrl+-")
        self.actionNavigateBack = QAction(tr("Go Back"), self)
        self.actionNavigateBack.setShortcut("Ctrl+[")
        self.actionNewAccountGroup = QAction(tr("New Account Group"), self)
        self.actionNewAccountGroup.setShortcut("Ctrl+Shift+N")
        self.actionShowNextView = QAction(tr("Next View"), self)
        self.actionShowNextView.setShortcut("Ctrl+Shift+]")
        self.actionShowPreviousView = QAction(tr("Previous View"), self)
        self.actionShowPreviousView.setShortcut("Ctrl+Shift+[")
        self.actionNewDocument = QAction(tr("New Document"), self)
        self.actionOpenExampleDocument = QAction(tr("Open Example Document"), self)
        self.actionOpenPluginFolder = QAction(tr("Open Plugin Folder"), self)
        self.actionImport = QAction(tr("Import..."), self)
        self.actionImport.setShortcut("Ctrl+Alt+I")
        self.actionExport = QAction(tr("Export..."), self)
        self.actionExport.setShortcut("Ctrl+Alt+E")
        self.actionSave = QAction(tr("Save"), self)
        self.actionSave.setShortcut("Ctrl+S")
        self.actionSaveAs = QAction(tr("Save As..."), self)
        self.actionSaveAs.setShortcut("Ctrl+Shift+S")
        self.actionAbout = QAction(tr("About moneyGuru"), self)
        self.actionToggleReconciliationMode = QAction(tr("Toggle Reconciliation Mode"), self)
        self.actionToggleReconciliationMode.setShortcut("Ctrl+Shift+R")
        self.actionToggleAccountExclusion = QAction(tr("Toggle Exclusion Status of Account"), self)
        self.actionToggleAccountExclusion.setShortcut("Ctrl+Shift+X")
        self.actionShowSchedules = QAction(tr("Schedules"), self)
        self.actionShowSchedules.setShortcut("Ctrl+4")
        self.actionShowSchedules.setIcon(QIcon(QPixmap(':/schedules_48')))
        self.actionShowBudgets = QAction(tr("Budgets"), self)
        self.actionShowBudgets.setShortcut("Ctrl+5")
        self.actionShowBudgets.setIcon(QIcon(QPixmap(':/budget_48')))
        self.actionReconcileSelected = QAction(tr("Reconcile Selection"), self)
        self.actionReconcileSelected.setShortcut("Ctrl+R")
        self.actionMakeScheduleFromSelected = QAction(tr("Make Schedule from Selected"), self)
        self.actionMakeScheduleFromSelected.setShortcut("Ctrl+M")
        self.actionShowPreferences = QAction(tr("Preferences..."), self)
        self.actionPrint = QAction(tr("Print..."), self)
        self.actionPrint.setShortcut("Ctrl+P")
        self.actionQuit = QAction(tr("Quit moneyGuru"), self)
        self.actionQuit.setShortcut("Ctrl+Q")
        self.actionUndo = QAction(tr("Undo"), self)
        self.actionUndo.setShortcut("Ctrl+Z")
        self.actionRedo = QAction(tr("Redo"), self)
        self.actionRedo.setShortcut("Ctrl+Y")
        self.actionShowHelp = QAction(tr("moneyGuru Help"), self)
        self.actionShowHelp.setShortcut("F1")
        self.actionCheckForUpdate = QAction(tr("Check for update"), self)
        self.actionOpenDebugLog = QAction(tr("Open Debug Log"), self)
        self.actionDuplicateTransaction = QAction(tr("Duplicate Transaction"), self)
        self.actionDuplicateTransaction.setShortcut("Ctrl+D")
        self.actionJumpToAccount = QAction(tr("Jump to Account..."), self)
        self.actionJumpToAccount.setShortcut("Ctrl+Shift+A")
        self.actionNewTab = QAction(tr("New Tab"), self)
        self.actionNewTab.setShortcut("Ctrl+T")
        self.actionCloseTab = QAction(tr("Close Tab"), self)
        self.actionCloseTab.setShortcut("Ctrl+W")
        
        self.menuFile.addAction(self.actionNewDocument)
        self.menuFile.addAction(self.actionNewTab)
        self.menuFile.addAction(self.actionOpenDocument)
        self.menuFile.addAction(self.menuOpenRecent.menuAction())
        self.menuFile.addAction(self.actionOpenExampleDocument)
        self.menuFile.addAction(self.actionOpenPluginFolder)
        self.menuFile.addAction(self.actionImport)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionCloseTab)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSaveAs)
        self.menuFile.addAction(self.actionExport)
        self.menuFile.addAction(self.actionPrint)
        self.menuFile.addAction(self.actionQuit)
        self.menuView.addAction(self.actionShowNetWorth)
        self.menuView.addAction(self.actionShowProfitLoss)
        self.menuView.addAction(self.actionShowTransactions)
        self.menuView.addAction(self.actionShowSchedules)
        self.menuView.addAction(self.actionShowBudgets)
        self.menuView.addAction(self.actionShowPreviousView)
        self.menuView.addAction(self.actionShowNextView)
        self.menuView.addAction(self.menuDateRange.menuAction())
        self.menuView.addAction(self.actionShowPreferences)
        self.menuView.addAction(self.actionToggleGraph)
        self.menuView.addAction(self.actionTogglePieChart)
        self.menuEdit.addAction(self.actionNewItem)
        self.menuEdit.addAction(self.actionNewAccountGroup)
        self.menuEdit.addAction(self.actionDeleteItem)
        self.menuEdit.addAction(self.actionEditItem)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionMoveUp)
        self.menuEdit.addAction(self.actionMoveDown)
        self.menuEdit.addAction(self.actionDuplicateTransaction)
        self.menuEdit.addAction(self.actionMakeScheduleFromSelected)
        self.menuEdit.addAction(self.actionReconcileSelected)
        self.menuEdit.addAction(self.actionToggleReconciliationMode)
        self.menuEdit.addAction(self.actionToggleAccountExclusion)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionShowSelectedAccount)
        self.menuEdit.addAction(self.actionNavigateBack)
        self.menuEdit.addAction(self.actionJumpToAccount)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionUndo)
        self.menuEdit.addAction(self.actionRedo)
        self.menuHelp.addAction(self.actionShowHelp)
        self.menuHelp.addAction(self.actionCheckForUpdate)
        self.menuHelp.addAction(self.actionOpenDebugLog)
        self.menuHelp.addAction(self.actionAbout)
        mainmenus = [self.menuFile, self.menuEdit, self.menuView, self.menuHelp]
        for menu in mainmenus:
            self.menubar.addAction(menu.menuAction())
            setAccelKeys(menu)
        setAccelKeys(self.menubar)
        self.tabBar.setMovable(True)
        self.tabBar.setTabsClosable(True)
        
        seq = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right)
        self._shortcutNextTab = QShortcut(seq, self)
        seq = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left)
        self._shortcutPrevTab = QShortcut(seq, self)
        
        # Linux setup
        if ISLINUX:
            self.actionCheckForUpdate.setVisible(False) # This only works on Windows
    
    def _bindSignals(self):
        self.newItemButton.clicked.connect(self.actionNewItem.trigger)
        self.deleteItemButton.clicked.connect(self.actionDeleteItem.trigger)
        self.editItemButton.clicked.connect(self.actionEditItem.trigger)
        self.graphVisibilityButton.clicked.connect(self.actionToggleGraph.trigger)
        self.piechartVisibilityButton.clicked.connect(self.actionTogglePieChart.trigger)
        self.columnsVisibilityButton.clicked.connect(self.columnsVisibilityButtonClicked)
        self.recentDocuments.mustOpenItem.connect(self.doc.open)
        self.doc.documentOpened.connect(self.recentDocuments.insertItem)
        self.doc.documentSavedAs.connect(self.recentDocuments.insertItem)
        self.doc.documentPathChanged.connect(self.documentPathChanged)
        self.tabBar.currentChanged.connect(self.currentTabChanged)
        self.tabBar.tabCloseRequested.connect(self.tabCloseRequested)
        self.tabBar.tabMoved.connect(self.tabMoved)
        
        # Views
        self.actionShowNetWorth.triggered.connect(self.showNetWorthTriggered)        
        self.actionShowProfitLoss.triggered.connect(self.showProfitLossTriggered)        
        self.actionShowTransactions.triggered.connect(self.showTransactionsTriggered)        
        self.actionShowSchedules.triggered.connect(self.showSchedulesTriggered)        
        self.actionShowBudgets.triggered.connect(self.showBudgetsTriggered)        
        self.actionShowPreviousView.triggered.connect(self.showPreviousViewTriggered)        
        self.actionShowNextView.triggered.connect(self.showNextViewTriggered)        
        self.actionShowPreferences.triggered.connect(self.app.showPreferences)
        self.actionToggleGraph.triggered.connect(self.toggleGraphTriggered)
        self.actionTogglePieChart.triggered.connect(self.togglePieChartTriggered)
        
        # Document Edition
        self.actionNewItem.triggered.connect(self.newItemTriggered)
        self.actionNewAccountGroup.triggered.connect(self.newAccountGroupTriggered)
        self.actionDeleteItem.triggered.connect(self.deleteItemTriggered)
        self.actionEditItem.triggered.connect(self.editItemTriggered)
        self.actionMoveUp.triggered.connect(self.moveUpTriggered)
        self.actionMoveDown.triggered.connect(self.moveDownTriggered)
        self.actionDuplicateTransaction.triggered.connect(self.model.duplicate_item)
        self.actionUndo.triggered.connect(self.doc.model.undo)
        self.actionRedo.triggered.connect(self.doc.model.redo)
        
        # Open / Save / Import / Export / New
        self.actionNewDocument.triggered.connect(self.doc.new)
        self.actionOpenDocument.triggered.connect(self.doc.openDocument)
        self.actionOpenExampleDocument.triggered.connect(self.doc.openExampleDocument)
        self.actionOpenPluginFolder.triggered.connect(self.model.app.open_plugin_folder)
        self.actionImport.triggered.connect(self.doc.importDocument)
        self.actionSave.triggered.connect(self.doc.save)
        self.actionSaveAs.triggered.connect(self.doc.saveAs)
        self.actionExport.triggered.connect(self.model.export)
        
        # Misc
        self.actionNewTab.triggered.connect(self.model.new_tab)
        self.actionCloseTab.triggered.connect(self.closeTabTriggered)
        self.actionShowSelectedAccount.triggered.connect(self.model.show_account)
        self.actionNavigateBack.triggered.connect(self.navigateBackTriggered)
        self.actionJumpToAccount.triggered.connect(self.jumpToAccountTriggered)
        self.actionMakeScheduleFromSelected.triggered.connect(self.makeScheduleFromSelectedTriggered)
        self.actionReconcileSelected.triggered.connect(self.reconcileSelectedTriggered)
        self.actionToggleReconciliationMode.triggered.connect(self.toggleReconciliationModeTriggered)
        self.actionToggleAccountExclusion.triggered.connect(self.toggleAccountExclusionTriggered)
        self.actionPrint.triggered.connect(self._print)
        self.actionShowHelp.triggered.connect(self.app.showHelp)
        self.actionCheckForUpdate.triggered.connect(self.checkForUpdateTriggered)
        self.actionAbout.triggered.connect(self.aboutTriggered)
        self.actionOpenDebugLog.triggered.connect(self.openDebugLogTriggered)
        self.actionQuit.triggered.connect(self.close)
        
        # Extra Shortcuts
        self._shortcutNextTab.activated.connect(self.showNextViewTriggered)
        self._shortcutPrevTab.activated.connect(self.showPreviousViewTriggered)
    
    #--- QWidget overrides
    def closeEvent(self, event):
        if self.doc.confirmDestructiveAction():
            event.accept()
        else:
            event.ignore()
    
    #--- Private
    def _print(self):
        dialog = QPrintDialog(self)
        if dialog.exec_() != QPrintDialog.Accepted:
            return
        printer = dialog.printer()
        currentView = self.mainView.currentWidget()
        viewPrinter = ViewPrinter(printer, currentView)
        currentView.fitViewsForPrint(viewPrinter)
        viewPrinter.render()
    
    def _getViewforPane(self, pane_type, pane_view):
        if pane_view in self.model2view:
            view = self.model2view[pane_view]
        else:
            view = PANETYPE2VIEWCLASS[pane_type](model=pane_view)
            self.model2view[pane_view] = view
            self.mainView.addWidget(view)
            view.restoreSubviewsSize()
        return view
    
    def _setTabIndex(self, index):
        if not self.tabBar.count():
            return
        self.tabBar.setCurrentIndex(index)
        self._updateActionsState()
        pane_type = self.model.pane_type(index)
        pane_view = self.model.pane_view(index)
        view = self._getViewforPane(pane_type, pane_view)
        self.mainView.setCurrentWidget(view)
        view.setFocus()
    
    def _activeView(self):
        paneIndex = self.model.current_pane_index
        return self.model.pane_view(paneIndex)
    
    def _updateActionsState(self):
        # Updates enable/disable checked/unchecked state of all actions. These state can change
        # under various conditions: main view change, date range type change and when reconciliation
        # mode is toggled
        
        # Determine what actions are enabled
        view = self._activeView()
        viewType = view.VIEW_TYPE
        isSheet = viewType in {PaneType.NetWorth, PaneType.Profit}
        isTransactionOrEntryTable = viewType in {PaneType.Transaction, PaneType.Account}
        canToggleReconciliation = viewType == PaneType.Account and view.can_toggle_reconciliation_mode
        
        newItemLabel = {
            PaneType.NetWorth: tr("New Account"),
            PaneType.Profit: tr("New Account"),
            PaneType.Transaction: tr("New Transaction"),
            PaneType.Account: tr("New Transaction"),
            PaneType.Schedule: tr("New Schedule"),
            PaneType.Budget: tr("New Budget"),
            PaneType.GeneralLedger: tr("New Transaction"),
        }.get(viewType, tr("New Item")) #XXX make "New Item" disabled
        self.actionNewItem.setText(newItemLabel)
        self.actionNewAccountGroup.setEnabled(isSheet)
        self.actionMoveDown.setEnabled(isTransactionOrEntryTable)
        self.actionMoveUp.setEnabled(isTransactionOrEntryTable)
        self.actionDuplicateTransaction.setEnabled(isTransactionOrEntryTable)
        self.actionMakeScheduleFromSelected.setEnabled(isTransactionOrEntryTable)
        self.actionReconcileSelected.setEnabled(viewType == PaneType.Account and view.reconciliation_mode)
        self.actionShowNextView.setEnabled(self.model.current_pane_index < self.model.pane_count-1)
        self.actionShowPreviousView.setEnabled(self.model.current_pane_index > 0)
        self.actionShowSelectedAccount.setEnabled(isSheet or isTransactionOrEntryTable)
        self.actionNavigateBack.setEnabled(viewType == PaneType.Account)
        self.actionToggleReconciliationMode.setEnabled(canToggleReconciliation)
        self.actionToggleAccountExclusion.setEnabled(isSheet)
    
    def _updateUndoActions(self):
        if self.doc.model.can_undo():
            self.actionUndo.setEnabled(True)
            self.actionUndo.setText(tr("Undo {0}").format(self.doc.model.undo_description()))
        else:
            self.actionUndo.setEnabled(False)
            self.actionUndo.setText(tr("Undo"))
        if self.doc.model.can_redo():
            self.actionRedo.setEnabled(True)
            self.actionRedo.setText(tr("Redo {0}").format(self.doc.model.redo_description()))
        else:
            self.actionRedo.setEnabled(False)
            self.actionRedo.setText(tr("Redo"))
    
    #--- Actions
    # Views
    def showNetWorthTriggered(self):
        self.model.select_pane_of_type(PaneType.NetWorth)
    
    def showProfitLossTriggered(self):
        self.model.select_pane_of_type(PaneType.Profit)
    
    def showTransactionsTriggered(self):
        self.model.select_pane_of_type(PaneType.Transaction)
    
    def showSchedulesTriggered(self):
        self.model.select_pane_of_type(PaneType.Schedule)
    
    def showBudgetsTriggered(self):
        self.model.select_pane_of_type(PaneType.Budget)
    
    def showPreviousViewTriggered(self):
        self.model.select_previous_view()
    
    def showNextViewTriggered(self):
        self.model.select_next_view()
    
    # Document Edition
    def newItemTriggered(self):
        self.model.new_item()
    
    def newAccountGroupTriggered(self):
        self.model.new_group()
    
    def deleteItemTriggered(self):
        self.model.delete_item()
    
    def editItemTriggered(self):
        self.model.edit_item()
    
    def moveUpTriggered(self):
        self.model.move_up()
    
    def moveDownTriggered(self):
        self.model.move_down()
    
    # Misc
    def closeTabTriggered(self):
        self.model.close_pane(self.model.current_pane_index)
    
    def navigateBackTriggered(self):
        self.model.navigate_back()
    
    def jumpToAccountTriggered(self):
        self.model.jump_to_account()
    
    def makeScheduleFromSelectedTriggered(self):
        self.model.make_schedule_from_selected()
    
    def reconcileSelectedTriggered(self):
        self._activeView().etable.toggle_reconciled()
    
    def toggleReconciliationModeTriggered(self):
        self._activeView().toggle_reconciliation_mode()
        self._updateActionsState()
    
    def toggleAccountExclusionTriggered(self):
        viewType = self.model.pane_type(self.model.current_pane_index)
        if viewType in {PaneType.NetWorth, PaneType.Profit}:
            self._activeView().sheet.toggle_excluded()
    
    def toggleGraphTriggered(self):
        self.model.toggle_area_visibility(PaneArea.BottomGraph)
    
    def togglePieChartTriggered(self):
        self.model.toggle_area_visibility(PaneArea.RightChart)
    
    def columnsVisibilityButtonClicked(self):
        items = self.model.column_menu_items()
        if not items:
            return
        menu = QMenu()
        for i, (display, marked) in enumerate(items):
            action = menu.addAction(display)
            action.setCheckable(True)
            action.setChecked(marked)
            action.setData(i)
            action.triggered.connect(self.columnsMenuItemWasClicked)
        self._columnMenuHolder = menu # we need to hold a reference to it while it popups
        button = self.columnsVisibilityButton
        menu.popup(button.parentWidget().mapToGlobal(button.geometry().topLeft()))
    
    def columnsMenuItemWasClicked(self):
        action = self.sender()
        if action is not None:
            index = action.data()
            self.model.toggle_column_menu_item(index)
    
    def checkForUpdateTriggered(self):
        QProcess.execute('updater.exe', ['/checknow'])
    
    def aboutTriggered(self):
        self.app.showAboutBox()
    
    def openDebugLogTriggered(self):
        debugLogPath = op.join(getAppData(), 'debug.log')
        url = QUrl.fromLocalFile(debugLogPath)
        QDesktopServices.openUrl(url)
    
    #--- Other Signals
    def currentTabChanged(self, index):
        self.model.current_pane_index = index
        self._setTabIndex(index)
    
    def documentPathChanged(self):
        if self.doc.documentPath:
            title = "moneyGuru ({})".format(self.doc.documentPath)
        else:
            title = "moneyGuru"
        self.setWindowTitle(title)
    
    def tabCloseRequested(self, index):
        self.model.close_pane(index)
    
    def tabMoved(self, fromIndex, toIndex):
        self.model.move_pane(fromIndex, toIndex)
    
    #--- model --> view
    def change_current_pane(self):
        self._setTabIndex(self.model.current_pane_index)
    
    def refresh_panes(self):
        while self.tabBar.count() < self.model.pane_count:
            self.tabBar.addTab('')
        for i in range(self.model.pane_count):
            pane_label = self.model.pane_label(i)
            pane_label = escapeamp(pane_label)
            self.tabBar.setTabText(i, pane_label)
            pane_type = self.model.pane_type(i)
            pane_view = self.model.pane_view(i)
            # Ensure that the view's "view" has been created and bound
            self._getViewforPane(pane_type, pane_view)
            iconname = PANETYPE2ICON.get(pane_type)
            icon = QIcon(QPixmap(':/{0}'.format(iconname))) if iconname else QIcon()
            self.tabBar.setTabIcon(i, icon)
        # It's important that we proceed with tab removal *after* we've completed tab initialization.
        # We're walking on eggshells here. refresh_panes() can be called in multiple situations, one
        # of them is during the opening of a document. When that happens when another document was
        # previously opened, all views' model are uninitalized and don't have their "view" attribute
        # set yet. If we proceed with the setCurrentIndex() call below before _getViewforPane()
        # could be called above, we get a crash.
        if self.tabBar.currentIndex() < self.model.pane_count:
            # Normally, we don't touch the tabBar index here and wait for change_current_pane,
            # but when we remove tabs, it's possible that currentTabChanged end up being called and
            # then the tab selection is bugged. I tried disconnecting/reconnecting the signal, but
            # this is buggy. So when a selected tab is about to be removed, we change the selection
            # to the model's one immediately.
            self.tabBar.setCurrentIndex(self.model.current_pane_index)
        while self.tabBar.count() > self.model.pane_count:
            self.tabBar.removeTab(self.tabBar.count()-1)
        self.tabBar.setTabsClosable(self.model.pane_count > 1)
    
    def refresh_status_line(self):
        self.statusLabel.setText(self.model.status_line)
    
    def refresh_undo_actions(self):
        self._updateUndoActions()
    
    def restore_window_frame(self, frame):
        self.setGeometry(*frame)
    
    def save_window_frame(self):
        r = self.geometry()
        return (r.x(), r.y(), r.width(), r.height())
    
    def show_message(self, msg):
        title = tr("Warning")
        QMessageBox.warning(self, title, msg)
    
    def update_area_visibility(self):
        hidden = self.model.hidden_areas
        graphimg = ':/graph_visibility_{}_16'.format('off' if PaneArea.BottomGraph in hidden else 'on')
        pieimg = ':/piechart_visibility_{}_16'.format('off' if PaneArea.RightChart in hidden else 'on')
        self.graphVisibilityButton.setIcon(QIcon(QPixmap(graphimg)))
        self.piechartVisibilityButton.setIcon(QIcon(QPixmap(pieimg)))
    
    def view_closed(self, index):
        self.tabBar.removeTab(index)
        self.tabBar.setTabsClosable(self.model.pane_count > 1)
Example #29
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 #30
0
class View(QMainWindow, auxilia.Actions):
    def __init__(self, configuration, mpdclient, app):
        QMainWindow.__init__(self)
        self.app = app
        self.focus = time()
        self.shuttingDown = False
        self.config = configuration
        self.mpdclient = mpdclient
        appIcon = QIcon(DATA_DIR + 'icons/Pythagora.png')
        uic.loadUi(DATA_DIR + 'ui/Pythagora.ui', self)
        self.KDE = KDE
        self.setWindowTitle('Pythagora')
        self.setWindowIcon(appIcon)
        # Load all forms.
        self.createViews()
        # Create 'Connect to' menu.
        self.menuConnect = QMenu('Connect To')
        self.menuConnect.menuAction().setIcon(
            auxilia.PIcon('network-disconnect'))
        self.connectButton = QToolButton()
        self.connectButton.setPopupMode(QToolButton.InstantPopup)
        self.connectButton.setIcon(auxilia.PIcon('network-disconnect'))
        self.connectButton.setMenu(self.menuConnect)
        # Create 'MDP' menu.
        self.menuMPD = QMenu('MPD')
        self.menuMPD.menuAction().setIcon(auxilia.PIcon('network-workgroup'))
        self.mpdButton = QToolButton()
        self.mpdButton.setPopupMode(QToolButton.InstantPopup)
        self.mpdButton.setIcon(auxilia.PIcon('network-workgroup'))
        self.mpdButton.setMenu(self.menuMPD)
        self.reloadLibrary = self.actionLibReload(self.menuMPD,
                                                  self.__libReload)
        self.updateLibrary = self.actionLibUpdate(
            self.menuMPD, lambda: self.mpdclient.send('update'))
        self.rescanLibrary = self.actionLibRescan(
            self.menuMPD, lambda: self.mpdclient.send('rescan'))
        # Fill Toolbar.
        self.toolBar.addWidget(self.connectButton)
        self.toolBar.addWidget(self.mpdButton)
        # Fill Statusbar.
        self.serverLabel = QLabel('Not connected')
        self.numSongsLabel = QLabel('Songs')
        self.playTimeLabel = QLabel('playTime')
        self.statusbar.addWidget(self.serverLabel)
        self.statusbar.addPermanentWidget(self.numSongsLabel)
        self.statusbar.addPermanentWidget(self.playTimeLabel)

        self.connect(self.menuConnect, SIGNAL('aboutToShow()'),
                     self.__buildConnectTo)
        self.connect(self.actionExit, SIGNAL('triggered()'), self.app.quit)
        self.connect(self.actionSettings, SIGNAL('triggered()'),
                     self.showConfig)

        # Set up trayicon and menu.
        if KDE:
            self.trayIcon = KTrayIcon(appIcon, self)
        else:
            self.trayIcon = QTrayIcon(appIcon, self)
        connectMenuAction = self.menuConnect.menuAction()
        self.trayIcon.addMenuItem(connectMenuAction)
        self.trayIcon.addMenuItem(self.actionSettings)
        self.connect(self.trayIcon, SIGNAL('activate()'),
                     self.toggleHideRestore)
        self.connect(self.trayIcon,
                     SIGNAL('secondaryActivateRequested(QPoint)'),
                     self.__playPause)

        self.connect(self.tabs, SIGNAL('currentChanged(int)'),
                     self.__tabsIndexChanged)
        self.connect(self.tabs.tabBar(), SIGNAL('tabMoved(int,int)'),
                     self.__tabMoved)
        self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'),
                     self.__storeSplitter)

        # Apply configuration.
        self.resize(configuration.mgrSize)
        self.splitter.setSizes(configuration.mgrSplit)
        self.tabs.setCurrentIndex(configuration.tabsIndex)

        self.closeEvent = self.closeEvent
        self.connect(self.app, SIGNAL('aboutToQuit()'), self.shutdown)
        self.show()

        #==============================================================================
        # Code for switching tabs on drag & drop. (__init__() continues)
        #==============================================================================

        # Instantiate timer
        self.tabTimer = QTimer()
        self.connect(self.tabTimer, SIGNAL('timeout()'), self.__selectTab)

        # Overload the default dragEvents. (none?)
        self.tabs.dragLeaveEvent = self.dragLeaveEvent
        self.tabs.dragEnterEvent = self.dragEnterEvent
        self.tabs.dragMoveEvent = self.dragMoveEvent

    def dragEnterEvent(self, event):
        '''Starts timer on enter and sets first position.'''
        self.tabPos = event.pos()
        event.accept()
        self.tabTimer.start(500)

    def dragLeaveEvent(self, event):
        '''If the mouse leaves the tabWidget stop the timer.'''
        self.tabTimer.stop()

    def dragMoveEvent(self, event):
        '''Keep track of the mouse and change the position, restarts the timer when moved.'''
        tabPos = event.pos()
        moved = tabPos.manhattanLength() - self.tabPos.manhattanLength()
        if moved > 7 or moved < -7:
            self.tabTimer.start(500)
        self.tabPos = tabPos

    def __selectTab(self):
        '''Changes the view to the tab where the mouse was hovering above.'''
        index = self.tabs.tabBar().tabAt(self.tabPos)
        self.tabs.setCurrentIndex(index)
        self.tabTimer.stop()

    def __libReload(self):
        self.mpdclient.send(
            'listallinfo',
            callback=lambda mainlist: self.emit(SIGNAL('reloadLibrary'),
                                                mpdlibrary.Library(mainlist)))


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

    def createViews(self):
        '''Set up our different view handlers.'''
        # Standard views.
        self.playerForm = PlayerForm(self, self.app, self.mpdclient,
                                     self.config)
        self.currentList = CurrentPlaylistForm.CurrentPlaylistForm(
            self, self.app, self.mpdclient, self.config)
        # Plugin views.
        loadedPlugins = []
        for plugin in plugins.allPlugins:
            loadedPlugins.append(
                plugin.getWidget(self, self.mpdclient, self.config))
        for name in self.config.tabOrder:
            for plugin in loadedPlugins:
                if plugin.moduleName == name:
                    self.tabs.addTab(plugin, auxilia.PIcon(plugin.moduleIcon),
                                     plugin.moduleName)
                    break

    def shutdown(self):
        self.shuttingDown = True
        self.app.processEvents()
        self.mpdclient.disconnect()
        self.config.mgrSize = self.size()
        print 'debug: shutdown finished'

    def showConfig(self):
        self.config.showConfiguration(self)

    def closeEvent(self, event):
        '''Catch MainWindow's close event so we can hide it instead.'''
        self.hide()
        event.ignore()

    def __storeSplitter(self):
        self.config.mgrSplit = self.splitter.sizes()

    def __tabsIndexChanged(self, value):
        self.config.tabsIndex = self.tabs.currentIndex()

    def __tabMoved(self, old, new):
        print "DEBUG: Tab from", old, "moved to", new
        order = self.config.tabOrder
        order.insert(new, order.pop(old))
        self.config.tabOrder = order

    def __toggleShoutCast(self, value):
        self.config.showShoutcast = value
        self.stackedWidget.setCurrentIndex(value)

    def toggleHideRestore(self):
        '''Show or hide the window based on some parameters. We can detect
        when we are obscured and come to the top. In other cases we hide if
        mapped and show if not.
        '''
        if KDE:
            if KWindowSystem.activeWindow() == self.winId() and self.isVisible(
            ):
                self.hide()
            else:
                self.show()
                KWindowSystem.forceActiveWindow(self.winId())
        else:
            if self.isVisible():
                self.hide()
            else:
                self.show()

    def __playPause(self):
        self.playerForm.play.emit(SIGNAL('clicked(bool)'), True)

    def __buildConnectTo(self):
        self.menuConnect.clear()
        self.menuConnect.addAction(auxilia.PIcon('dialog-cancel'),
                                   'None (disconnect)')
        connected = self.mpdclient.connected()
        for server in self.config.knownHosts:
            if connected and self.config.server and self.config.server[
                    0] == server:
                icon = auxilia.PIcon('network-connect')
            else:
                icon = auxilia.PIcon('network-disconnect')
            self.menuConnect.addAction(icon, server)
Example #31
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 #32
0
class CartoDBPlugin(QObject):
    # initialize plugin directory
    PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))

    def __init__(self, iface):
        QObject.__init__(self)
        QgsMessageLog.logMessage('GDAL Version: ' + str(gdal.VersionInfo('VERSION_NUM')), 'CartoDB Plugin', QgsMessageLog.INFO)

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

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

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

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

        # SQLite available?
        driverName = "SQLite"
        self.sqLiteDrv = ogr.GetDriverByName(driverName)
        if self.sqLiteDrv is None:
            QgsMessageLog.logMessage('SQLite driver not found', 'CartoDB Plugin', QgsMessageLog.CRITICAL)
        else:
            QgsMessageLog.logMessage('SQLite driver is found', 'CartoDB Plugin', QgsMessageLog.INFO)
            self.databasePath = CartoDBPlugin.PLUGIN_DIR + '/db/database.sqlite'
            shutil.copyfile(CartoDBPlugin.PLUGIN_DIR + '/db/init_database.sqlite', self.databasePath)
        self.layers = []
        self.countLoadingLayers = 0
        self.countLoadedLayers = 0

        self._cdbMenu = None
        self._mainAction = None
        self._loadDataAction = None
        self._createVizAction = None
        self._addSQLAction = None
        self.toolbar = CartoDBToolbar()
        self._toolbarAction = None
        self._menu = None

    def initGui(self):
        self._cdbMenu = QMenu("CartoDB plugin", self.iface.mainWindow())
        self._cdbMenu.setIcon(QIcon(":/plugins/qgis-cartodb/images/icon.png"))
        self._mainAction = QAction(self.tr('Add CartoDB Layer'), self.iface.mainWindow())
        self._mainAction.setIcon(QIcon(":/plugins/qgis-cartodb/images/icons/add.png"))
        self._loadDataAction = QAction(self.tr('Upload layers to CartoDB'), self.iface.mainWindow())
        self._loadDataAction.setIcon(QIcon(":/plugins/qgis-cartodb/images/icons/upload.png"))
        self._createVizAction = QAction(self.tr('Create New Map'), self.iface.mainWindow())
        self._createVizAction.setIcon(QIcon(":/plugins/qgis-cartodb/images/icons/map.png"))
        self._addSQLAction = QAction(self.tr('Add SQL CartoDB Layer'), self.iface.mainWindow())
        self._addSQLAction.setIcon(QIcon(":/plugins/qgis-cartodb/images/icons/sql.png"))

        self.toolbar.setClick(self.connectionManager)
        self.toolbar.error.connect(self.toolbarError)
        self._toolbarAction = self.iface.addWebToolBarWidget(self.toolbar)
        worker = CartoDBPluginWorker(self.toolbar, 'connectCartoDB')
        worker.start()

        if not self.toolbar.isCurrentUserValid():
            self._mainAction.setEnabled(False)
            self._loadDataAction.setEnabled(False)
            self._createVizAction.setEnabled(False)
            self._addSQLAction.setEnabled(False)

        self._mainAction.triggered.connect(self.run)
        self._loadDataAction.triggered.connect(self.upload)
        self._createVizAction.triggered.connect(self.createNewMap)
        self._addSQLAction.triggered.connect(self.addSQL)

        self._cdbMenu.addAction(self._mainAction)
        self._cdbMenu.addAction(self._loadDataAction)
        self._cdbMenu.addAction(self._createVizAction)
        self._cdbMenu.addAction(self._addSQLAction)
        try:
            self.iface.layerToolBar().addAction(self._mainAction)
        except:
            self.iface.addWebToolBarIcon(self._mainAction)
        self.iface.addWebToolBarIcon(self._loadDataAction)
        self.iface.addWebToolBarIcon(self._createVizAction)
        try:
            self.iface.layerToolBar().addAction(self._addSQLAction)
        except:
            self.iface.addWebToolBarIcon(self._addSQLAction)

        # Create Web menu, if it doesn't exist yet
        tmpAction = QAction("Temporal", self.iface.mainWindow())
        self.iface.addPluginToWebMenu("_tmp", tmpAction)
        self._menu = self.iface.webMenu()
        self._menu.addMenu(self._cdbMenu)
        self.iface.removePluginWebMenu("_tmp", tmpAction)

        # Register plugin layer type
        self.pluginLayerType = CartoDBPluginLayerType(self.iface, self.createLayerCB)
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.pluginLayerType)

    def unload(self):
        self.iface.removeWebToolBarIcon(self._mainAction)
        self.iface.removeWebToolBarIcon(self._loadDataAction)
        self.iface.removeWebToolBarIcon(self._createVizAction)
        self.iface.removeWebToolBarIcon(self._addSQLAction)
        self.iface.webMenu().removeAction(self._cdbMenu.menuAction())
        self.iface.removeWebToolBarIcon(self._toolbarAction)

        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(CartoDBPluginLayer.LAYER_TYPE)

    def connectionManager(self):
        dlg = CartoDBConnectionsManager()
        dlg.notfoundconnections.connect(self.connectionsNotFound)
        dlg.deleteconnetion.connect(self.onDeleteUser)
        dlg.show()

        result = dlg.exec_()
        if result == 1 and dlg.currentUser is not None and dlg.currentApiKey is not None:
            self.toolbar.setUserCredentials(dlg.currentUser, dlg.currentApiKey, dlg.currentMultiuser)
            self._mainAction.setEnabled(True)
            self._loadDataAction.setEnabled(True)
            self._createVizAction.setEnabled(True)
            self._addSQLAction.setEnabled(True)

    def connectionsNotFound(self):
        self.toolbarError("")
        self.toolbar.reset()

    def onDeleteUser(self, user):
        if self.toolbar.currentUser == user:
            self.toolbar.setConnectText()

    def toolbarError(self, error):
        self._mainAction.setEnabled(False)
        self._loadDataAction.setEnabled(False)
        self._createVizAction.setEnabled(False)
        self._addSQLAction.setEnabled(False)

    def run(self):
        # Create and show the dialog
        dlg = CartoDBPluginDialog(self.toolbar)
        dlg.show()

        result = dlg.exec_()
        # See if OK was pressed
        if result == 1 and dlg.currentUser is not None and dlg.currentApiKey is not None:
            selectedItems = dlg.getTablesListSelectedItems()
            countLayers = len(selectedItems)
            self.countLoadingLayers = self.countLoadingLayers + countLayers
            if countLayers > 0:
                self.progressMessageBar, self.progress = self.addLoadingMsg(self.countLoadingLayers)
                self.iface.messageBar().pushWidget(self.progressMessageBar, self.iface.messageBar().INFO)
                self.iface.mainWindow().statusBar().showMessage(self.tr('Processed {} %').format(0))
                for i, table in enumerate(selectedItems):
                    widget = dlg.getItemWidget(table)
                    worker = CartoDBLayerWorker(self.iface, widget.tableName, widget.tableOwner, dlg,
                                                filterByExtent=dlg.filterByExtent(), readonly=widget.readonly,
                                                multiuser=widget.multiuser)
                    worker.finished.connect(self.addLayer)
                    self.worker = worker
                    worker.load()
        elif dlg.loadSQL:
            self.addSQL()


    def addLayer(self, layer):
        try:
            self.worker.deleteLater()
        except Exception, e:
            pass

        self.countLoadedLayers = self.countLoadedLayers + 1

        if layer.readonly:
            self.iface.messageBar().pushMessage(self.tr('Warning'),
                                                self.tr('Layer {}  is loaded in readonly mode').format(layer.layerName),
                                                level=self.iface.messageBar().WARNING, duration=5)
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        self.layers.append(layer)
        self.progressMessageBar.setText(str(self.countLoadedLayers) + '/' + str(self.countLoadingLayers))
        percent = self.countLoadedLayers / float(self.countLoadingLayers) * 100
        self.iface.mainWindow().statusBar().showMessage(self.tr('Processed {}% - Loaded: {}').format(int(percent), layer.cartoTable))
        self.progress.setValue(self.countLoadedLayers)
        if self.countLoadedLayers == self.countLoadingLayers:
            self.iface.mainWindow().statusBar().clearMessage()
            self.iface.messageBar().popWidget(self.progressMessageBar)
            self.countLoadedLayers = 0
            self.countLoadingLayers = 0
Example #33
0
class CartoDBPlugin(QObject):
    # initialize plugin directory
    PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))

    def __init__(self, iface):
        QObject.__init__(self)
        QgsMessageLog.logMessage(
            'GDAL Version: ' + str(gdal.VersionInfo('VERSION_NUM')),
            'CartoDB Plugin', QgsMessageLog.INFO)

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

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

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

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

        # SQLite available?
        driverName = "SQLite"
        self.sqLiteDrv = ogr.GetDriverByName(driverName)
        if self.sqLiteDrv is None:
            QgsMessageLog.logMessage('SQLite driver not found',
                                     'CartoDB Plugin', QgsMessageLog.CRITICAL)
        else:
            QgsMessageLog.logMessage('SQLite driver is found',
                                     'CartoDB Plugin', QgsMessageLog.INFO)
            self.databasePath = CartoDBPlugin.PLUGIN_DIR + '/db/database.sqlite'
            shutil.copyfile(
                CartoDBPlugin.PLUGIN_DIR + '/db/init_database.sqlite',
                self.databasePath)
        self.layers = []
        self.countLoadingLayers = 0
        self.countLoadedLayers = 0

        self._cdbMenu = None
        self._mainAction = None
        self._loadDataAction = None
        self._createVizAction = None
        self._addSQLAction = None
        self.toolbar = CartoDBToolbar()
        self._toolbarAction = None
        self._menu = None

    def initGui(self):
        self._cdbMenu = QMenu("CartoDB plugin", self.iface.mainWindow())
        self._cdbMenu.setIcon(QIcon(":/plugins/qgis-cartodb/images/icon.png"))
        self._mainAction = QAction(self.tr('Add CartoDB Layer'),
                                   self.iface.mainWindow())
        self._mainAction.setIcon(
            QIcon(":/plugins/qgis-cartodb/images/icons/add.png"))
        self._loadDataAction = QAction(self.tr('Upload layers to CartoDB'),
                                       self.iface.mainWindow())
        self._loadDataAction.setIcon(
            QIcon(":/plugins/qgis-cartodb/images/icons/upload.png"))
        self._createVizAction = QAction(self.tr('Create New Map'),
                                        self.iface.mainWindow())
        self._createVizAction.setIcon(
            QIcon(":/plugins/qgis-cartodb/images/icons/map.png"))
        self._addSQLAction = QAction(self.tr('Add SQL CartoDB Layer'),
                                     self.iface.mainWindow())
        self._addSQLAction.setIcon(
            QIcon(":/plugins/qgis-cartodb/images/icons/sql.png"))

        self.toolbar.setClick(self.connectionManager)
        self.toolbar.error.connect(self.toolbarError)
        self._toolbarAction = self.iface.addWebToolBarWidget(self.toolbar)
        worker = CartoDBPluginWorker(self.toolbar, 'connectCartoDB')
        worker.start()

        if not self.toolbar.isCurrentUserValid():
            self._mainAction.setEnabled(False)
            self._loadDataAction.setEnabled(False)
            self._createVizAction.setEnabled(False)
            self._addSQLAction.setEnabled(False)

        self._mainAction.triggered.connect(self.run)
        self._loadDataAction.triggered.connect(self.upload)
        self._createVizAction.triggered.connect(self.createNewMap)
        self._addSQLAction.triggered.connect(self.addSQL)

        self._cdbMenu.addAction(self._mainAction)
        self._cdbMenu.addAction(self._loadDataAction)
        self._cdbMenu.addAction(self._createVizAction)
        self._cdbMenu.addAction(self._addSQLAction)
        try:
            self.iface.layerToolBar().addAction(self._mainAction)
        except:
            self.iface.addWebToolBarIcon(self._mainAction)
        self.iface.addWebToolBarIcon(self._loadDataAction)
        self.iface.addWebToolBarIcon(self._createVizAction)
        try:
            self.iface.layerToolBar().addAction(self._addSQLAction)
        except:
            self.iface.addWebToolBarIcon(self._addSQLAction)

        # Create Web menu, if it doesn't exist yet
        tmpAction = QAction("Temporal", self.iface.mainWindow())
        self.iface.addPluginToWebMenu("_tmp", tmpAction)
        self._menu = self.iface.webMenu()
        self._menu.addMenu(self._cdbMenu)
        self.iface.removePluginWebMenu("_tmp", tmpAction)

        # Register plugin layer type
        self.pluginLayerType = CartoDBPluginLayerType(self.iface,
                                                      self.createLayerCB)
        QgsPluginLayerRegistry.instance().addPluginLayerType(
            self.pluginLayerType)

    def unload(self):
        self.iface.removeWebToolBarIcon(self._mainAction)
        self.iface.removeWebToolBarIcon(self._loadDataAction)
        self.iface.removeWebToolBarIcon(self._createVizAction)
        self.iface.removeWebToolBarIcon(self._addSQLAction)
        self.iface.webMenu().removeAction(self._cdbMenu.menuAction())
        self.iface.removeWebToolBarIcon(self._toolbarAction)

        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(
            CartoDBPluginLayer.LAYER_TYPE)

    def connectionManager(self):
        dlg = CartoDBConnectionsManager()
        dlg.notfoundconnections.connect(self.connectionsNotFound)
        dlg.deleteconnetion.connect(self.onDeleteUser)
        dlg.show()

        result = dlg.exec_()
        if result == 1 and dlg.currentUser is not None and dlg.currentApiKey is not None:
            self.toolbar.setUserCredentials(dlg.currentUser, dlg.currentApiKey,
                                            dlg.currentMultiuser)
            self._mainAction.setEnabled(True)
            self._loadDataAction.setEnabled(True)
            self._createVizAction.setEnabled(True)
            self._addSQLAction.setEnabled(True)

    def connectionsNotFound(self):
        self.toolbarError("")
        self.toolbar.reset()

    def onDeleteUser(self, user):
        if self.toolbar.currentUser == user:
            self.toolbar.setConnectText()

    def toolbarError(self, error):
        self._mainAction.setEnabled(False)
        self._loadDataAction.setEnabled(False)
        self._createVizAction.setEnabled(False)
        self._addSQLAction.setEnabled(False)

    def run(self):
        # Create and show the dialog
        dlg = CartoDBPluginDialog(self.toolbar)
        dlg.show()

        result = dlg.exec_()
        # See if OK was pressed
        if result == 1 and dlg.currentUser is not None and dlg.currentApiKey is not None:
            selectedItems = dlg.getTablesListSelectedItems()
            countLayers = len(selectedItems)
            self.countLoadingLayers = self.countLoadingLayers + countLayers
            if countLayers > 0:
                self.progressMessageBar, self.progress = self.addLoadingMsg(
                    self.countLoadingLayers)
                self.iface.messageBar().pushWidget(
                    self.progressMessageBar,
                    self.iface.messageBar().INFO)
                self.iface.mainWindow().statusBar().showMessage(
                    self.tr('Processed {} %').format(0))
                for i, table in enumerate(selectedItems):
                    widget = dlg.getItemWidget(table)
                    worker = CartoDBLayerWorker(
                        self.iface,
                        widget.tableName,
                        widget.tableOwner,
                        dlg,
                        filterByExtent=dlg.filterByExtent(),
                        readonly=widget.readonly,
                        multiuser=widget.multiuser)
                    worker.finished.connect(self.addLayer)
                    self.worker = worker
                    worker.load()
        elif dlg.loadSQL:
            self.addSQL()

    def addLayer(self, layer):
        try:
            self.worker.deleteLater()
        except Exception, e:
            pass

        self.countLoadedLayers = self.countLoadedLayers + 1

        if layer.readonly:
            self.iface.messageBar().pushMessage(
                self.tr('Warning'),
                self.tr('Layer {}  is loaded in readonly mode').format(
                    layer.layerName),
                level=self.iface.messageBar().WARNING,
                duration=5)
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        self.layers.append(layer)
        self.progressMessageBar.setText(
            str(self.countLoadedLayers) + '/' + str(self.countLoadingLayers))
        percent = self.countLoadedLayers / float(self.countLoadingLayers) * 100
        self.iface.mainWindow().statusBar().showMessage(
            self.tr('Processed {}% - Loaded: {}').format(
                int(percent), layer.cartoTable))
        self.progress.setValue(self.countLoadedLayers)
        if self.countLoadedLayers == self.countLoadingLayers:
            self.iface.mainWindow().statusBar().clearMessage()
            self.iface.messageBar().popWidget(self.progressMessageBar)
            self.countLoadedLayers = 0
            self.countLoadingLayers = 0
Example #34
0
class View(QMainWindow, auxilia.Actions):
    def __init__(self, configuration, mpdclient, app):
        QMainWindow.__init__(self)
        self.app = app
        self.focus = time()
        self.shuttingDown = False
        self.config = configuration
        self.mpdclient = mpdclient
        self.appIcon = os.path.abspath(DATA_DIR+'icons/Pythagora.png')
        uic.loadUi(DATA_DIR+'ui/Pythagora.ui', self)
        self.KDE = KDE
        self.setWindowTitle('Pythagora')
        self.setWindowIcon(QIcon(self.appIcon))
        # Load all forms.
        self.createViews()
        # Create 'Connect to' menu.
        self.menuConnect = QMenu('Connect To')
        self.menuConnect.menuAction().setIcon(auxilia.PIcon('network-disconnect'))
        self.connectButton = QToolButton()
        self.connectButton.setPopupMode(QToolButton.InstantPopup)
        self.connectButton.setIcon(auxilia.PIcon('network-disconnect'))
        self.connectButton.setMenu(self.menuConnect)
        # Create 'MDP' menu.
        self.menuMPD = QMenu('MPD')
        self.menuMPD.menuAction().setIcon(auxilia.PIcon('network-workgroup'))
        self.mpdButton = QToolButton()
        self.mpdButton.setPopupMode(QToolButton.InstantPopup)
        self.mpdButton.setIcon(auxilia.PIcon('network-workgroup'))
        self.mpdButton.setMenu(self.menuMPD)
        self.reloadLibrary = self.actionLibReload(self.menuMPD, self.__libReload)
        self.updateLibrary = self.actionLibUpdate(self.menuMPD, lambda: self.mpdclient.send('update'))
        self.rescanLibrary = self.actionLibRescan(self.menuMPD, lambda: self.mpdclient.send('rescan'))
        # Fill Toolbar.
        self.toolBar.addWidget(self.connectButton)
        self.toolBar.addWidget(self.mpdButton)
        # Fill Statusbar.
        self.serverLabel = QLabel('Not connected')
        self.numSongsLabel = QLabel('Songs')
        self.playTimeLabel = QLabel('playTime')
        self.statusbar.addWidget(self.serverLabel)
        self.statusbar.addPermanentWidget(self.numSongsLabel)
        self.statusbar.addPermanentWidget(self.playTimeLabel)

        self.connect(self.menuConnect, SIGNAL('aboutToShow()'), self.__buildConnectTo)
        self.connect(self.actionExit,SIGNAL('triggered()'),self.app.quit)
        self.connect(self.actionSettings,SIGNAL('triggered()'),self.showConfig)


        # Set up trayicon and menu.
        if KDE:
            self.trayIcon = KTrayIcon(self.appIcon, self)
        else:
            self.trayIcon = QTrayIcon(self.appIcon, self)
        connectMenuAction = self.menuConnect.menuAction()
        self.trayIcon.addMenuItem(connectMenuAction)
        self.trayIcon.addMenuItem(self.actionSettings)
        self.connect(self.trayIcon, SIGNAL('activate()'), self.toggleHideRestore)
        self.connect(self.trayIcon, SIGNAL('secondaryActivateRequested(QPoint)'), self.__playPause)

        self.connect(self.tabs, SIGNAL('currentChanged(int)'), self.__tabsIndexChanged)
        self.connect(self.tabs.tabBar(), SIGNAL('tabMoved(int,int)'), self.__tabMoved)
        self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'), self.__storeSplitter)

        # Apply configuration.
        self.resize(configuration.mgrSize)
        self.splitter.setSizes(configuration.mgrSplit)
        self.tabs.setCurrentIndex(configuration.tabsIndex)

        self.closeEvent = self.closeEvent
        self.connect(self.app,SIGNAL('aboutToQuit()'),self.shutdown)
        self.show()

#==============================================================================
# Code for switching tabs on drag & drop. (__init__() continues)
#==============================================================================

        # Instantiate timer
        self.tabTimer = QTimer()
        self.connect(self.tabTimer, SIGNAL('timeout()'), self.__selectTab)

        # Overload the default dragEvents. (none?)
        self.tabs.dragLeaveEvent = self.dragLeaveEvent
        self.tabs.dragEnterEvent = self.dragEnterEvent
        self.tabs.dragMoveEvent = self.dragMoveEvent

    def dragEnterEvent(self, event):
        '''Starts timer on enter and sets first position.'''
        self.tabPos = event.pos()
        event.accept()
        self.tabTimer.start(500)

    def dragLeaveEvent(self, event):
        '''If the mouse leaves the tabWidget stop the timer.'''
        self.tabTimer.stop()

    def dragMoveEvent(self, event):
        '''Keep track of the mouse and change the position, restarts the timer when moved.'''
        tabPos = event.pos()
        moved = tabPos.manhattanLength() - self.tabPos.manhattanLength()
        if moved > 7 or moved < -7:
            self.tabTimer.start(500)
        self.tabPos = tabPos

    def __selectTab(self):
        '''Changes the view to the tab where the mouse was hovering above.'''
        index = self.tabs.tabBar().tabAt(self.tabPos)
        self.tabs.setCurrentIndex(index)
        self.tabTimer.stop()

    def __libReload(self):
        self.mpdclient.send('listallinfo', callback=
                lambda mainlist: self.emit(SIGNAL('reloadLibrary'), mpdlibrary.Library(mainlist)))

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

    def createViews(self):
        '''Set up our different view handlers.'''
        # Standard views.
        self.playerForm = PlayerForm(self, self.app, self.mpdclient, self.config)
        self.currentList = CurrentPlaylistForm.CurrentPlaylistForm(self, self.app, self.mpdclient, self.config)
        # Plugin views.
        loadedPlugins = {}
        for plugin in plugins.allPlugins:
            plugin = plugin.getWidget(self, self.mpdclient, self.config)
            loadedPlugins[plugin.moduleName] = plugin
        for name in self.config.tabOrder:
            if name in loadedPlugins:
                plugin = loadedPlugins.pop(name)
                self.tabs.addTab(plugin, auxilia.PIcon(plugin.moduleIcon), plugin.moduleName)
        for plugin in loadedPlugins.values():
            self.tabs.addTab(plugin, auxilia.PIcon(plugin.moduleIcon), plugin.moduleName)
            order = self.config.tabOrder
            order.append(plugin.moduleName)
            self.config.tabOrder = order

    def shutdown(self):
        self.shuttingDown = True
        self.app.processEvents()
        self.mpdclient.disconnect()
        self.config.mgrSize = self.size()
        print 'debug: shutdown finished'

    def showConfig(self):
        self.config.showConfiguration(self)

    def closeEvent(self, event):
        '''Catch MainWindow's close event so we can hide it instead.'''
        self.hide()
        event.ignore()

    def __storeSplitter(self):
        self.config.mgrSplit = self.splitter.sizes()

    def __tabsIndexChanged(self, value):
        self.config.tabsIndex = self.tabs.currentIndex()

    def __tabMoved(self, old, new):
        print "DEBUG: Tab from", old, "moved to", new
        order = self.config.tabOrder
        order.insert(new, order.pop(old))
        self.config.tabOrder = order

    def __toggleShoutCast(self, value):
        self.config.showShoutcast = value
        self.stackedWidget.setCurrentIndex(value)

    def toggleHideRestore(self):
        '''Show or hide the window based on some parameters. We can detect
        when we are obscured and come to the top. In other cases we hide if
        mapped and show if not.
        '''
        if KDE:
            if KWindowSystem.activeWindow() == self.winId() and self.isVisible():
                self.hide()
            else:
                self.show()
                KWindowSystem.forceActiveWindow(self.winId())
        else:
            if self.isVisible():
                self.hide()
            else: self.show()

    def __playPause(self):
        self.playerForm.play.emit(SIGNAL('clicked(bool)'), True)

    def __buildConnectTo(self):
        self.menuConnect.clear()
        self.menuConnect.addAction(auxilia.PIcon('dialog-cancel'), 'None (disconnect)')
        connected = self.mpdclient.connected()
        for server in self.config.knownHosts:
            if connected and self.config.server and self.config.server[0] == server:
                icon = auxilia.PIcon('network-connect')
            else: icon = auxilia.PIcon('network-disconnect')
            self.menuConnect.addAction(icon, server)
Example #35
0
class UMEP:
    """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',
                                   'UMEP_{}.qm'.format(locale))

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

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

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

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

        # Main menu
        self.UMEP_Menu = QMenu("UMEP")

        # First-order sub-menus
        self.Pre_Menu = QMenu("Pre-Processor")
        self.UMEP_Menu.addMenu(self.Pre_Menu)
        self.Pro_Menu = QMenu("Processor")
        self.UMEP_Menu.addMenu(self.Pro_Menu)
        self.Pos_Menu = QMenu("Post-Processor")
        self.UMEP_Menu.addMenu(self.Pos_Menu)
        self.About_Menu = QMenu("Help")
        self.UMEP_Menu.addMenu(self.About_Menu)

        # Sub-menus and actions to Pre-processor
        self.MD_Menu = QMenu("Meteorological Data")
        self.Pre_Menu.addMenu(self.MD_Menu)
        self.SP_Menu = QMenu("Spatial Data")
        self.Pre_Menu.addMenu(self.SP_Menu)
        self.UG_Menu = QMenu("Urban Geometry")
        self.Pre_Menu.addMenu(self.UG_Menu)
        self.ULC_Menu = QMenu("Urban Land Cover")
        self.Pre_Menu.addMenu(self.ULC_Menu)
        self.SM_Menu = QMenu("Urban Morphology")
        self.Pre_Menu.addMenu(self.SM_Menu)
        self.SUEWSPrepare_Action = QAction("SUEWS Prepare",
                                           self.iface.mainWindow())
        self.Pre_Menu.addAction(self.SUEWSPrepare_Action)
        self.SUEWSPrepare_Action.triggered.connect(self.SUEWS_Prepare)

        # Sub-actions to Surface Morphology
        self.IMCP_Action = QAction("Morphometric Calculator (Point)",
                                   self.iface.mainWindow())
        self.SM_Menu.addAction(self.IMCP_Action)
        self.IMCP_Action.triggered.connect(self.IMCP)
        self.IMCG_Action = QAction("Morphometric Calculator (Grid)",
                                   self.iface.mainWindow())
        self.SM_Menu.addAction(self.IMCG_Action)
        self.IMCG_Action.triggered.connect(self.IMCG)
        self.FP_Action = QAction("Source Area Model (Point)",
                                 self.iface.mainWindow())
        self.SM_Menu.addAction(self.FP_Action)
        self.FP_Action.triggered.connect(self.FP)

        # Sub-actions to Meteorological Data Preparation
        self.PED_Action = QAction("Prepare Existing Data",
                                  self.iface.mainWindow())
        self.MD_Menu.addAction(self.PED_Action)
        self.PED_Action.triggered.connect(self.PED)
        self.PFD_Action = QAction("Download data (WATCH)",
                                  self.iface.mainWindow())
        self.MD_Menu.addAction(self.PFD_Action)
        self.PFD_Action.triggered.connect(self.WA)

        # Sub-actions to Spatial Data Preparation
        self.SDD_Action = QAction("Spatial Data Downloader",
                                  self.iface.mainWindow())
        self.SP_Menu.addAction(self.SDD_Action)
        self.SDD_Action.triggered.connect(self.UD)
        self.DSMGenerator_Action = QAction("DSM Generator",
                                           self.iface.mainWindow())
        self.SP_Menu.addAction(self.DSMGenerator_Action)
        self.DSMGenerator_Action.triggered.connect(self.DSMG)
        self.TreeGenerator_Action = QAction("Tree Generator",
                                            self.iface.mainWindow())
        self.SP_Menu.addAction(self.TreeGenerator_Action)
        self.TreeGenerator_Action.triggered.connect(self.TG)
        self.WC_Action = QAction("LCZ Converter", self.iface.mainWindow())
        self.SP_Menu.addAction(self.WC_Action)
        self.WC_Action.triggered.connect(self.WC)

        # Sub-actions to Urban Geometry
        self.SVF_Action = QAction("Sky View Factor", self.iface.mainWindow())
        self.UG_Menu.addAction(self.SVF_Action)
        self.SVF_Action.triggered.connect(self.SVF)
        # self.HW_Action = QAction("Height/Width Ratio", self.iface.mainWindow())
        # self.UG_Menu.addAction(self.HW_Action)
        # self.HW_Action.setEnabled(False)
        self.WH_Action = QAction("Wall Height and Aspect",
                                 self.iface.mainWindow())
        self.UG_Menu.addAction(self.WH_Action)
        self.WH_Action.triggered.connect(self.WH)

        # Sub-actions to Urban Land Cover
        self.ULCUEBRC_Action = QAction("Land Cover Reclassifier",
                                       self.iface.mainWindow())
        self.ULC_Menu.addAction(self.ULCUEBRC_Action)
        self.ULCUEBRC_Action.triggered.connect(self.LCRC)
        self.ULCUEBP_Action = QAction("Land Cover Fraction (Point)",
                                      self.iface.mainWindow())
        self.ULC_Menu.addAction(self.ULCUEBP_Action)
        self.ULCUEBP_Action.triggered.connect(self.LCP)
        self.ULCUEBG_Action = QAction("Land Cover Fraction (Grid)",
                                      self.iface.mainWindow())
        self.ULC_Menu.addAction(self.ULCUEBG_Action)
        self.ULCUEBG_Action.triggered.connect(self.LCG)

        # Sub-menus to Processor
        self.OTC_Menu = QMenu("Outdoor Thermal Comfort")
        self.Pro_Menu.addMenu(self.OTC_Menu)
        self.UEB_Menu = QMenu("Urban Energy Balance")
        self.Pro_Menu.addMenu(self.UEB_Menu)
        self.SUN_Menu = QMenu("Solar radiation")
        self.Pro_Menu.addMenu(self.SUN_Menu)
        # self.NUHI_Action = QAction("Nocturnal Urban Heat Island", self.iface.mainWindow())
        # self.Pro_Menu.addAction(self.NUHI_Action)

        # Sub-menus to Outdoor Thermal Comfort
        self.PET_Action = QAction("Comfort Index (PET/UCTI)",
                                  self.iface.mainWindow())
        self.OTC_Menu.addAction(self.PET_Action)
        self.PET_Action.setEnabled(False)
        self.MRT_Action = QAction("Mean Radiant Temperature (SOLWEIG)",
                                  self.iface.mainWindow())
        self.OTC_Menu.addAction(self.MRT_Action)
        self.MRT_Action.triggered.connect(self.SO)
        self.PWS_Action = QAction("Pedestrian Wind Speed",
                                  self.iface.mainWindow())
        self.OTC_Menu.addAction(self.PWS_Action)
        self.PWS_Action.setEnabled(False)
        self.EF_Action = QAction("Extreme Finder", self.iface.mainWindow())
        self.OTC_Menu.addAction(self.EF_Action)
        self.EF_Action.triggered.connect(self.EF)

        # Sub-menus to Urban Energy Balance
        self.QFL_Action = QAction("Antropogenic heat - GQf (Greater Qf)",
                                  self.iface.mainWindow())
        self.UEB_Menu.addAction(self.QFL_Action)
        self.QFL_Action.triggered.connect(self.GF)
        self.QF_Action = QAction("Antropogenic heat - LQf (LUCY)",
                                 self.iface.mainWindow())
        self.UEB_Menu.addAction(self.QF_Action)
        self.QF_Action.triggered.connect(self.LF)
        self.SUEWSSIMPLE_Action = QAction(
            "Urban Energy Balance (SUEWS, Simple)", self.iface.mainWindow())
        self.UEB_Menu.addAction(self.SUEWSSIMPLE_Action)
        self.SUEWSSIMPLE_Action.triggered.connect(self.SUEWS_simple)
        self.SUEWS_Action = QAction(
            "Urban Energy Balance (SUEWS/BLUEWS, Advanced)",
            self.iface.mainWindow())
        self.UEB_Menu.addAction(self.SUEWS_Action)
        self.SUEWS_Action.triggered.connect(self.SUEWS_advanced)
        # self.LUMPS_Action = QAction("Urban Energy Balance (LUMPS)", self.iface.mainWindow())
        # self.UEB_Menu.addAction(self.LUMPS_Action)
        # self.LUMPS_Action.setEnabled(False)
        # self.CBL_Action = QAction("UEB + CBL (BLUEWS/BLUMPS)", self.iface.mainWindow())
        # self.UEB_Menu.addAction(self.CBL_Action)
        # self.CBL_Action.setEnabled(False)

        # Sub-menus to Solar radiation
        self.SEBE_Action = QAction("Solar Energy on Building Envelopes (SEBE)",
                                   self.iface.mainWindow())
        self.SUN_Menu.addAction(self.SEBE_Action)
        self.SEBE_Action.triggered.connect(self.SE)
        self.DSP_Action = QAction("Daily Shadow Pattern",
                                  self.iface.mainWindow())
        self.SUN_Menu.addAction(self.DSP_Action)
        self.DSP_Action.triggered.connect(self.SH)

        # Sub-menus to Post-processing
        self.SUNpos_Menu = QMenu("Solar Radiation")
        self.Pos_Menu.addMenu(self.SUNpos_Menu)
        self.OTCpos_Menu = QMenu("Outdoor Thermal Comfort")
        self.Pos_Menu.addMenu(self.OTCpos_Menu)
        self.UEBpos_Menu = QMenu("Urban Energy Balance")
        self.Pos_Menu.addMenu(self.UEBpos_Menu)
        self.BSS_Action = QAction("Benchmarking System",
                                  self.iface.mainWindow())
        self.Pos_Menu.addAction(self.BSS_Action)
        self.BSS_Action.triggered.connect(self.BSS)

        # Sub-menus to Solar radiation, post processing
        self.SEBEv_Action = QAction("SEBE (Visualisation)",
                                    self.iface.mainWindow())
        self.SUNpos_Menu.addAction(self.SEBEv_Action)
        self.SEBEv_Action.triggered.connect(self.SEv)

        # Sub-menus to Outdoor thermal comfort, post processing
        self.SOLWEIGa_Action = QAction("SOLWEIG Analyzer",
                                       self.iface.mainWindow())
        self.OTCpos_Menu.addAction(self.SOLWEIGa_Action)
        self.SOLWEIGa_Action.triggered.connect(self.SOv)

        # Sub-menus to Urban Energy Balance, post processing
        self.SUEWSa_Action = QAction("SUEWS Analyzer", self.iface.mainWindow())
        self.UEBpos_Menu.addAction(self.SUEWSa_Action)
        self.SUEWSa_Action.triggered.connect(self.SUv)

        # Sub-menus to About
        self.About_Action = QAction("About", self.iface.mainWindow())
        self.About_Menu.addAction(self.About_Action)
        self.Manual_Action = QAction("UMEP on the web",
                                     self.iface.mainWindow())
        self.About_Menu.addAction(self.Manual_Action)
        self.Manual_Action.triggered.connect(self.help)

        # Icons
        self.SUEWSPrepare_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/SuewsLogo.png"))
        self.SUEWSSIMPLE_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/SuewsLogo.png"))
        self.SUEWS_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/SuewsLogo.png"))
        self.SVF_Action.setIcon(QIcon(self.plugin_dir + "/Icons/icon_svf.png"))
        self.IMCG_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/ImageMorphIcon.png"))
        self.IMCP_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/ImageMorphIconPoint.png"))
        self.DSP_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/ShadowIcon.png"))
        self.ULCUEBG_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/LandCoverFractionGridIcon.png"))
        self.ULCUEBP_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/LandCoverFractionPointIcon.png"))
        self.ULCUEBRC_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/LandCoverReclassifierIcon.png"))
        self.WH_Action.setIcon(QIcon(self.plugin_dir + "/Icons/WallsIcon.png"))
        self.SEBE_Action.setIcon(QIcon(self.plugin_dir +
                                       "/Icons/sebeIcon.png"))
        self.SEBEv_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/sebeIcon.png"))
        self.FP_Action.setIcon(QIcon(self.plugin_dir + "/Icons/FootPrint.png"))
        self.About_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_umep.png"))
        self.Manual_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_umep.png"))
        self.PED_Action.setIcon(QIcon(self.plugin_dir + "/Icons/metdata.png"))
        self.PFD_Action.setIcon(QIcon(self.plugin_dir + "/Icons/watch.png"))
        self.MRT_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_solweig.png"))
        self.SOLWEIGa_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_solweig.png"))
        self.SUEWSa_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/SuewsLogo.png"))
        self.TreeGenerator_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_tree.png"))
        self.DSMGenerator_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/DSMGeneratorIcon.png"))
        self.EF_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_extreme.png"))
        self.WC_Action.setIcon(QIcon(self.plugin_dir + "/Icons/LCZ_icon.png"))
        self.SDD_Action.setIcon(
            QIcon(self.plugin_dir + "/Icons/icon_spatialdownloader.png"))
        self.QFL_Action.setIcon(QIcon(self.plugin_dir + "/Icons/icon_GQF.png"))
        self.QF_Action.setIcon(QIcon(self.plugin_dir + "/Icons/icon_LQF.png"))
        self.BSS_Action.setIcon(QIcon(self.plugin_dir + "/Icons/icon_BSS.png"))

        self.iface.mainWindow().menuBar().insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.UMEP_Menu)
        self.dlgAbout = UMEPDialogAbout()

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

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

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

        icon_path = ':/plugins/UMEP/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'UMEP'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        # Code to show the about dialog
        QObject.connect(self.About_Action, SIGNAL("triggered()"),
                        self.dlgAbout, SLOT("show()"))

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

    def PED(self):
        sg = MetdataProcessor(self.iface)
        sg.run()

    def SH(self):
        sg = ShadowGenerator(self.iface)
        sg.run()

    def IMCG(self):
        sg = ImageMorphParam(self.iface)
        sg.run()

    def IMCP(self):
        sg = ImageMorphParmsPoint(self.iface)
        sg.run()

    def SVF(self):
        sg = SkyViewFactorCalculator(self.iface)
        sg.run()

    def SUEWS_simple(self):
        sg = SuewsSimple(self.iface)
        sg.run()

    def SUEWS_advanced(self):
        sg = SUEWS(self.iface)
        sg.run()

    def SUEWS_Prepare(self):
        sg = SUEWSPrepare(self.iface)
        sg.run()

    def LCG(self):
        sg = LandCoverFractionGrid(self.iface)
        sg.run()

    def LCP(self):
        sg = LandCoverFractionPoint(self.iface)
        sg.run()

    def LCRC(self):
        sg = LandCoverReclassifier(self.iface)
        sg.run()

    def WH(self):
        sg = WallHeight(self.iface)
        # pydevd.settrace('localhost', port=53100, stdoutToServer=True, stderrToServer=True)  #used for debugging
        sg.run()

    def SE(self):
        sg = SEBE(self.iface)
        sg.run()

    def SEv(self):
        sg = Sun(self.iface)
        sg.run()

    def FP(self):
        sg = FootprintModel(self.iface)
        sg.run()

    def WA(self):
        sg = WATCHData(self.iface)
        sg.run()

    def GF(self):
        sg = GreaterQF(self.iface)
        sg.run()

    def SO(self):
        sg = SOLWEIG(self.iface)
        sg.run()

    def TG(self):
        sg = TreeGenerator(self.iface)
        sg.run()

    def DSMG(self):
        sg = DSMGenerator(self.iface)
        sg.run()

    def EF(self):
        sg = ExtremeFinder(self.iface)
        sg.run()

    def SOv(self):
        sg = SolweigAnalyzer(self.iface)
        sg.run()

    def SUv(self):
        sg = SUEWSAnalyzer(self.iface)
        sg.run()

    def UD(self):
        sg = UMEP_Data_Download(self.iface)
        sg.run()

    def WC(self):
        sg = LCZ_test(self.iface)
        sg.run()

    def LF(self):
        sg = LQF(self.iface)
        sg.run()

    def BSS(self):
        sg = BenchMarking(self.iface)
        sg.run()

    def run(self):
        # This function starts the plugin
        self.dlg.show()
        self.dlg.exec_()

    def help(self):
        url = "http://umep-docs.readthedocs.io/en/latest/index.html"
        webbrowser.open_new_tab(url)
class QuickMapServices:
    """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
        self.translator = QTranslator()

        self.locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)


        # Create the dialog (after translation) and keep reference
        self.settings_dlg = SettingsDialog()
        self.info_dlg = AboutDialog()

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None

        # TileLayer assets
        self.crs3857 = None
        self.downloadTimeout = 30  # TODO: settings
        self.navigationMessagesEnabled = Qt.Checked  # TODO: settings
        self.pluginName = 'QuickMapServices'


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


    def initGui(self):
        #import pydevd
        #pydevd.settrace('localhost', port=9921, stdoutToServer=True, stderrToServer=True, suspend=False)

        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        # Main Menu
        icon_path = self.plugin_dir + '/icons/mActionAddLayer.png'
        self.menu = QMenu(self.tr(u'QuickMapServices'))
        self.menu.setIcon(QIcon(icon_path))

        # DataSources Actions

        # Register plugin layer type
        self.tileLayerType = TileLayerType(self)
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.tileLayerType)

        self.groups_list = DsGroupsList(self.locale, self.custom_translator)
        self.ds_list = DataSourcesList(self.locale, self.custom_translator)

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        for ds in data_sources:
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path), self.tr('Set proper scale'), self.iface.mainWindow())
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path), self.tr('Set SlippyMap scales'), self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        #self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + '/icons/mActionSettings.png'
        settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'), self.iface.mainWindow())
        self.service_actions.append(settings_act)
        #self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + '/icons/mActionAbout.png'
        info_act = QAction(QIcon(icon_about_path), self.tr('About'), self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)

        # add to QGIS menu
        self.iface.addPluginToWebMenu("_tmp", info_act)
        self.iface.webMenu().addMenu(self.menu)
        self.iface.removePluginWebMenu("_tmp", info_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        self.tb_action = self.iface.webToolBar().addWidget(toolbutton)


    def _load_scales_list(self):
        scales_filename = os.path.join(self.plugin_dir, 'scales.xml')
        scales_list = []
        # TODO: remake when fix: http://hub.qgis.org/issues/11915
        # QgsScaleUtils.loadScaleList(scales_filename, scales_list, importer_message)
        xml_root = ET.parse(scales_filename).getroot()
        for scale_el in xml_root.findall('scale'):
            scales_list.append(scale_el.get('value'))
        return scales_list

    @property
    def scales_list(self):
        if not self._scales_list:
            self._scales_list = self._load_scales_list()
        return self._scales_list

    def set_nearest_scale(self):
        #get current scale
        curr_scale = self.iface.mapCanvas().scale()
        #find nearest
        nearest_scale = sys.maxint
        for scale_str in self.scales_list:
            scale = scale_str.split(':')[1]
            scale_int = int(scale)
            if abs(scale_int-curr_scale) < abs(nearest_scale - curr_scale):
                nearest_scale = scale_int

        #set new scale
        if nearest_scale != sys.maxint:
            self.iface.mapCanvas().zoomScale(nearest_scale)

    def set_tms_scales(self):
        res = QMessageBox.question(
            self.iface.mainWindow(),
            self.tr('QuickMapServices'),
            self.tr('Set SlippyMap scales for current project? \nThe previous settings will be overwritten!'),
            QMessageBox.Yes | QMessageBox.No)
        if res == QMessageBox.Yes:
            # set scales
            QgsProject.instance().writeEntry('Scales', '/ScalesList', self.scales_list)
            # activate
            QgsProject.instance().writeEntry('Scales', '/useProjectScales', True)
            # update in main window
            # ???? no way to update: http://hub.qgis.org/issues/11917


    def insert_layer(self):
        #TODO: need factory!
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias), ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            layer = TileLayer(self, service_info, False)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u''
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(',')
                if layers:
                    if ds.wms_turn_over:
                        layers.reverse()
                    qgis_wms_uri += '&layers='+'&layers='.join(layers)+'&styles='*len(layers)
            qgis_wms_uri += '&url=' + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias), KNOWN_DRIVERS.WMS.lower())

        if not layer.isValid():
            error_message = self.tr('Layer %s can\'t be added to the map!') % ds.alias
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)
            QgsMessageLog.logMessage(error_message, level=QgsMessageLog.CRITICAL)
        else:
            # Set attribs
            layer.setAttribution(ds.copyright_text)
            layer.setAttributionUrl(ds.copyright_link)
            # Insert to bottom
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            toc_root = QgsProject.instance().layerTreeRoot()
            toc_root.insertLayer(len(toc_root.children()), layer)
            # Save link
            self.service_layers.append(layer)


    def unload(self):
        # remove menu
        self.iface.webMenu().removeAction(self.menu.menuAction())
        # remove toolbar button
        self.iface.webToolBar().removeAction(self.tb_action)
        # clean vars
        self.menu = None
        self.toolbutton = None
        self.service_actions = None
        self.ds_list = None
        self.groups_list = None
        self.service_layers = None
        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(TileLayer.LAYER_TYPE)
Example #37
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 #38
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 #39
0
class QuickMapServices:
    """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
        self.translator = QTranslator()

        self.locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.settings_dlg = SettingsDialog()
        self.info_dlg = AboutDialog()

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None

        # TileLayer assets
        self.crs3857 = None
        self.downloadTimeout = 30  # TODO: settings
        self.navigationMessagesEnabled = Qt.Checked  # TODO: settings
        self.pluginName = 'QuickMapServices'

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

    def initGui(self):
        #import pydevd
        #pydevd.settrace('localhost', port=9921, stdoutToServer=True, stderrToServer=True, suspend=False)
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        # Main Menu
        icon_path = self.plugin_dir + '/icons/mActionAddLayer.png'
        self.menu = QMenu(self.tr(u'QuickMapServices'))
        self.menu.setIcon(QIcon(icon_path))

        # DataSources Actions

        # Register plugin layer type
        self.tileLayerType = TileLayerType(self)
        QgsPluginLayerRegistry.instance().addPluginLayerType(
            self.tileLayerType)

        self.groups_list = DsGroupsList(self.locale, self.custom_translator)
        self.ds_list = DataSourcesList(self.locale, self.custom_translator)

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        for ds in data_sources:
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path),
                                        self.tr('Set proper scale'),
                                        self.iface.mainWindow())
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path),
                             self.tr('Set SlippyMap scales'),
                             self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        #self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + '/icons/mActionSettings.png'
        settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'),
                               self.iface.mainWindow())
        self.service_actions.append(settings_act)
        #self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + '/icons/mActionAbout.png'
        info_act = QAction(QIcon(icon_about_path), self.tr('About'),
                           self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)

        # add to QGIS menu
        self.iface.addPluginToWebMenu("_tmp", info_act)
        self.iface.webMenu().addMenu(self.menu)
        self.iface.removePluginWebMenu("_tmp", info_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        self.tb_action = self.iface.webToolBar().addWidget(toolbutton)

    def _load_scales_list(self):
        scales_filename = os.path.join(self.plugin_dir, 'scales.xml')
        scales_list = []
        # TODO: remake when fix: http://hub.qgis.org/issues/11915
        # QgsScaleUtils.loadScaleList(scales_filename, scales_list, importer_message)
        xml_root = ET.parse(scales_filename).getroot()
        for scale_el in xml_root.findall('scale'):
            scales_list.append(scale_el.get('value'))
        return scales_list

    @property
    def scales_list(self):
        if not self._scales_list:
            self._scales_list = self._load_scales_list()
        return self._scales_list

    def set_nearest_scale(self):
        #get current scale
        curr_scale = self.iface.mapCanvas().scale()
        #find nearest
        nearest_scale = sys.maxint
        for scale_str in self.scales_list:
            scale = scale_str.split(':')[1]
            scale_int = int(scale)
            if abs(scale_int - curr_scale) < abs(nearest_scale - curr_scale):
                nearest_scale = scale_int

        #set new scale
        if nearest_scale != sys.maxint:
            self.iface.mapCanvas().zoomScale(nearest_scale)

    def set_tms_scales(self):
        res = QMessageBox.question(
            self.iface.mainWindow(), self.tr('QuickMapServices'),
            self.
            tr('Set SlippyMap scales for current project? \nThe previous settings will be overwritten!'
               ), QMessageBox.Yes | QMessageBox.No)
        if res == QMessageBox.Yes:
            # set scales
            QgsProject.instance().writeEntry('Scales', '/ScalesList',
                                             self.scales_list)
            # activate
            QgsProject.instance().writeEntry('Scales', '/useProjectScales',
                                             True)
            # update in main window
            # ???? no way to update: http://hub.qgis.org/issues/11917

    def insert_layer(self):
        #TODO: need factory!
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias),
                                           ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            layer = TileLayer(self, service_info, False)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u''
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(',')
                if layers:
                    qgis_wms_uri += '&layers=' + '&layers='.join(
                        layers) + '&styles=' * len(layers)
            qgis_wms_uri += '&url=' + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias),
                                   KNOWN_DRIVERS.WMS.lower())

        if not layer.isValid():
            error_message = self.tr(
                'Layer %s can\'t be added to the map!') % ds.alias
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)
            QgsMessageLog.logMessage(error_message,
                                     level=QgsMessageLog.CRITICAL)
        else:
            # Set attribs
            layer.setAttribution(ds.copyright_text)
            layer.setAttributionUrl(ds.copyright_link)
            # Insert to bottom
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            toc_root = QgsProject.instance().layerTreeRoot()
            toc_root.insertLayer(len(toc_root.children()), layer)
            # Save link
            self.service_layers.append(layer)

    def unload(self):
        # remove menu
        self.iface.webMenu().removeAction(self.menu.menuAction())
        # remove toolbar button
        self.iface.webToolBar().removeAction(self.tb_action)
        # clean vars
        self.menu = None
        self.toolbutton = None
        self.service_actions = None
        self.ds_list = None
        self.groups_list = None
        self.service_layers = None
        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(
            TileLayer.LAYER_TYPE)
Example #40
0
class DirectoriesDialog(QMainWindow):
    def __init__(self, parent, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self.lastAddedFolder = platform.INITIAL_FOLDER_IN_DIALOGS
        self.recentFolders = Recent(self.app, 'recentFolders')
        self._setupUi()
        self.directoriesModel = DirectoriesModel(self.app.model.directory_tree,
                                                 view=self.treeView)
        self.directoriesDelegate = DirectoriesDelegate()
        self.treeView.setItemDelegate(self.directoriesDelegate)
        self._setupColumns()
        self.app.recentResults.addMenu(self.menuLoadRecent)
        self.app.recentResults.addMenu(self.menuRecentResults)
        self.recentFolders.addMenu(self.menuRecentFolders)
        self._updateAddButton()
        self._updateRemoveButton()
        self._updateLoadResultsButton()
        self._setupBindings()

    def _setupBindings(self):
        self.scanButton.clicked.connect(self.scanButtonClicked)
        self.loadResultsButton.clicked.connect(self.actionLoadResults.trigger)
        self.addFolderButton.clicked.connect(self.actionAddFolder.trigger)
        self.removeFolderButton.clicked.connect(self.removeFolderButtonClicked)
        self.treeView.selectionModel().selectionChanged.connect(
            self.selectionChanged)
        self.app.recentResults.itemsChanged.connect(
            self._updateLoadResultsButton)
        self.recentFolders.itemsChanged.connect(self._updateAddButton)
        self.recentFolders.mustOpenItem.connect(self.app.model.add_directory)
        self.directoriesModel.foldersAdded.connect(
            self.directoriesModelAddedFolders)
        self.app.willSavePrefs.connect(self.appWillSavePrefs)

    def _setupActions(self):
        # (name, shortcut, icon, desc, func)
        ACTIONS = [
            ('actionLoadResults', 'Ctrl+L', '', tr("Load Results..."),
             self.loadResultsTriggered),
            ('actionShowResultsWindow', '', '', tr("Results Window"),
             self.app.showResultsWindow),
            ('actionAddFolder', '', '', tr("Add Folder..."),
             self.addFolderTriggered),
        ]
        createActions(ACTIONS, self)

    def _setupMenu(self):
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 42, 22))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setTitle(tr("File"))
        self.menuView = QMenu(self.menubar)
        self.menuView.setTitle(tr("View"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setTitle(tr("Help"))
        self.menuLoadRecent = QMenu(self.menuFile)
        self.menuLoadRecent.setTitle(tr("Load Recent Results"))
        self.setMenuBar(self.menubar)

        self.menuFile.addAction(self.actionLoadResults)
        self.menuFile.addAction(self.menuLoadRecent.menuAction())
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.app.actionQuit)
        self.menuView.addAction(self.app.actionPreferences)
        self.menuView.addAction(self.actionShowResultsWindow)
        self.menuView.addAction(self.app.actionIgnoreList)
        self.menuHelp.addAction(self.app.actionShowHelp)
        self.menuHelp.addAction(self.app.actionRegister)
        self.menuHelp.addAction(self.app.actionCheckForUpdate)
        self.menuHelp.addAction(self.app.actionOpenDebugLog)
        self.menuHelp.addAction(self.app.actionAbout)

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

        # Recent folders menu
        self.menuRecentFolders = QMenu()
        self.menuRecentFolders.addAction(self.actionAddFolder)
        self.menuRecentFolders.addSeparator()

        # Recent results menu
        self.menuRecentResults = QMenu()
        self.menuRecentResults.addAction(self.actionLoadResults)
        self.menuRecentResults.addSeparator()

    def _setupUi(self):
        self.setWindowTitle(self.app.NAME)
        self.resize(420, 338)
        self.centralwidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.promptLabel = QLabel(
            tr("Select folders to scan and press \"Scan\"."),
            self.centralwidget)
        self.verticalLayout.addWidget(self.promptLabel)
        self.treeView = QTreeView(self.centralwidget)
        self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.treeView.setAcceptDrops(True)
        triggers = QAbstractItemView.DoubleClicked|QAbstractItemView.EditKeyPressed\
            |QAbstractItemView.SelectedClicked
        self.treeView.setEditTriggers(triggers)
        self.treeView.setDragDropOverwriteMode(True)
        self.treeView.setDragDropMode(QAbstractItemView.DropOnly)
        self.treeView.setUniformRowHeights(True)
        self.verticalLayout.addWidget(self.treeView)
        self.horizontalLayout = QHBoxLayout()
        self.removeFolderButton = QPushButton(self.centralwidget)
        self.removeFolderButton.setIcon(QIcon(QPixmap(":/minus")))
        self.removeFolderButton.setShortcut("Del")
        self.horizontalLayout.addWidget(self.removeFolderButton)
        self.addFolderButton = QPushButton(self.centralwidget)
        self.addFolderButton.setIcon(QIcon(QPixmap(":/plus")))
        self.horizontalLayout.addWidget(self.addFolderButton)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.loadResultsButton = QPushButton(self.centralwidget)
        self.loadResultsButton.setText(tr("Load Results"))
        self.horizontalLayout.addWidget(self.loadResultsButton)
        self.scanButton = QPushButton(self.centralwidget)
        self.scanButton.setText(tr("Scan"))
        self.scanButton.setDefault(True)
        self.horizontalLayout.addWidget(self.scanButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.setCentralWidget(self.centralwidget)

        self._setupActions()
        self._setupMenu()

        if self.app.prefs.directoriesWindowRect is not None:
            self.setGeometry(self.app.prefs.directoriesWindowRect)
        else:
            moveToScreenCenter(self)

    def _setupColumns(self):
        header = self.treeView.header()
        header.setStretchLastSection(False)
        header.setResizeMode(0, QHeaderView.Stretch)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.resizeSection(1, 100)

    def _updateAddButton(self):
        if self.recentFolders.isEmpty():
            self.addFolderButton.setMenu(None)
        else:
            self.addFolderButton.setMenu(self.menuRecentFolders)

    def _updateRemoveButton(self):
        indexes = self.treeView.selectedIndexes()
        if not indexes:
            self.removeFolderButton.setEnabled(False)
            return
        self.removeFolderButton.setEnabled(True)

    def _updateLoadResultsButton(self):
        if self.app.recentResults.isEmpty():
            self.loadResultsButton.setMenu(None)
        else:
            self.loadResultsButton.setMenu(self.menuRecentResults)

    #--- QWidget overrides
    def closeEvent(self, event):
        event.accept()
        if self.app.model.results.is_modified:
            title = tr("Unsaved results")
            msg = tr("You have unsaved results, do you really want to quit?")
            if not self.app.confirm(title, msg):
                event.ignore()
        if event.isAccepted():
            QApplication.quit()

    #--- Events
    def addFolderTriggered(self):
        title = tr("Select a folder to add to the scanning list")
        flags = QFileDialog.ShowDirsOnly
        dirpath = str(
            QFileDialog.getExistingDirectory(self, title, self.lastAddedFolder,
                                             flags))
        if not dirpath:
            return
        self.lastAddedFolder = dirpath
        self.app.model.add_directory(dirpath)
        self.recentFolders.insertItem(dirpath)

    def appWillSavePrefs(self):
        self.app.prefs.directoriesWindowRect = self.geometry()

    def directoriesModelAddedFolders(self, folders):
        for folder in folders:
            self.recentFolders.insertItem(folder)

    def loadResultsTriggered(self):
        title = tr("Select a results file to load")
        files = ';;'.join(
            [tr("dupeGuru Results (*.dupeguru)"),
             tr("All Files (*.*)")])
        destination = QFileDialog.getOpenFileName(self, title, '', files)
        if destination:
            self.app.model.load_from(destination)
            self.app.recentResults.insertItem(destination)

    def removeFolderButtonClicked(self):
        self.directoriesModel.model.remove_selected()

    def scanButtonClicked(self):
        if self.app.model.results.is_modified:
            title = tr("Start a new scan")
            msg = tr(
                "You have unsaved results, do you really want to continue?")
            if not self.app.confirm(title, msg):
                return
        self.app.model.start_scanning()

    def selectionChanged(self, selected, deselected):
        self._updateRemoveButton()
Example #41
0
class QuickMapServices:
    """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__).decode(
            sys.getfilesystemencoding())

        # initialize locale
        self.translator = QTranslator()

        self.locale = Locale.get_locale()
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.info_dlg = AboutDialog()

        # Check Contrib and User dirs
        try:
            ExtraSources.check_extra_dirs()
        except:
            error_message = self.tr(
                'Extra dirs for %s can\'t be created: %s %s') % (
                    PluginSettings.product_name(), sys.exc_type, sys.exc_value)
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None

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

    def initGui(self):
        #import pydevd
        #pydevd.settrace('localhost', port=9921, stdoutToServer=True, stderrToServer=True, suspend=False)

        # Register plugin layer type
        self.tileLayerType = TileLayerType(self)
        QgsPluginLayerRegistry.instance().addPluginLayerType(
            self.tileLayerType)

        # Create menu
        icon_path = self.plugin_dir + '/icons/mActionAddLayer.png'
        self.menu = QMenu(self.tr(u'QuickMapServices'))
        self.menu.setIcon(QIcon(icon_path))

        self.build_menu_tree()

        # add to QGIS menu/toolbars
        self.append_menu_buttons()

    def _load_scales_list(self):
        scales_filename = os.path.join(self.plugin_dir, 'scales.xml')
        scales_list = []
        # TODO: remake when fix: http://hub.qgis.org/issues/11915
        # QgsScaleUtils.loadScaleList(scales_filename, scales_list, importer_message)
        xml_root = ET.parse(scales_filename).getroot()
        for scale_el in xml_root.findall('scale'):
            scales_list.append(scale_el.get('value'))
        return scales_list

    @property
    def scales_list(self):
        if not self._scales_list:
            self._scales_list = self._load_scales_list()
        return self._scales_list

    def set_nearest_scale(self):
        #get current scale
        curr_scale = self.iface.mapCanvas().scale()
        #find nearest
        nearest_scale = sys.maxint
        for scale_str in self.scales_list:
            scale = scale_str.split(':')[1]
            scale_int = int(scale)
            if abs(scale_int - curr_scale) < abs(nearest_scale - curr_scale):
                nearest_scale = scale_int

        #set new scale
        if nearest_scale != sys.maxint:
            self.iface.mapCanvas().zoomScale(nearest_scale)

    def set_tms_scales(self):
        res = QMessageBox.question(
            self.iface.mainWindow(), self.tr('QuickMapServices'),
            self.
            tr('Set SlippyMap scales for current project? \nThe previous settings will be overwritten!'
               ), QMessageBox.Yes | QMessageBox.No)
        if res == QMessageBox.Yes:
            # set scales
            QgsProject.instance().writeEntry('Scales', '/ScalesList',
                                             self.scales_list)
            # activate
            QgsProject.instance().writeEntry('Scales', '/useProjectScales',
                                             True)
            # update in main window
            # ???? no way to update: http://hub.qgis.org/issues/11917

    def insert_layer(self):
        #TODO: need factory!
        layers4add = []
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias),
                                           ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            if ds.tms_y_origin_top is not None:
                service_info.yOriginTop = ds.tms_y_origin_top
            service_info.epsg_crs_id = ds.tms_epsg_crs_id
            service_info.postgis_crs_id = ds.tms_postgis_crs_id
            service_info.custom_proj = ds.tms_custom_proj
            layer = TileLayer(self, service_info, False)
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u''
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(',')
                if layers:
                    if ds.wms_turn_over:
                        layers.reverse()
                    qgis_wms_uri += '&layers=' + '&layers='.join(
                        layers) + '&styles=' * len(layers)
            qgis_wms_uri += '&url=' + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias),
                                   KNOWN_DRIVERS.WMS.lower())
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WFS:
            qgis_wfs_uri_base = ds.wfs_url
            o = urlparse.urlparse(qgis_wfs_uri_base)
            request_attrs = dict(urlparse.parse_qsl(o.query))

            layers_str = request_attrs.get('TYPENAME', '')
            layers = layers_str.split(',')
            for layer_name in layers:
                new_request_attrs = request_attrs
                new_request_attrs['TYPENAME'] == layer_name

                url_parts = list(o)
                url_parts[4] = "&".join(
                    ["%s=%s" % (k, v) for k, v in new_request_attrs.items()])

                qgis_wfs_uri = urlparse.urlunparse(url_parts)

                layer = QgsVectorLayer(
                    qgis_wfs_uri, "%s - %s" % (self.tr(ds.alias), layer_name),
                    "WFS")
                layers4add.append(layer)

        for layer in layers4add:
            if not layer.isValid():
                error_message = self.tr(
                    'Layer %s can\'t be added to the map!') % ds.alias
                self.iface.messageBar().pushMessage(
                    self.tr('Error'),
                    error_message,
                    level=QgsMessageBar.CRITICAL)
                QgsMessageLog.logMessage(error_message,
                                         level=QgsMessageLog.CRITICAL)
            else:
                # Set attribs
                layer.setAttribution(ds.copyright_text)
                layer.setAttributionUrl(ds.copyright_link)
                # Insert to bottom
                QgsMapLayerRegistry.instance().addMapLayer(layer, False)
                toc_root = QgsProject.instance().layerTreeRoot()
                toc_root.insertLayer(len(toc_root.children()), layer)
                # Save link
                self.service_layers.append(layer)
                # Set OTF CRS Transform for map
                if PluginSettings.enable_otf_3857(
                ) and ds.type == KNOWN_DRIVERS.TMS:
                    self.iface.mapCanvas().setCrsTransformEnabled(True)
                    self.iface.mapCanvas().setDestinationCrs(
                        TileLayer.CRS_3857)

    def unload(self):
        # remove menu/
        self.remove_menu_buttons()

        # clean vars
        self.menu = None
        self.toolbutton = None
        self.service_actions = None
        self.ds_list = None
        self.groups_list = None
        self.service_layers = None
        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(
            TileLayer.LAYER_TYPE)

    def build_menu_tree(self):
        # Main Menu
        self.menu.clear()

        self.groups_list = GroupsList()
        self.ds_list = DataSourcesList()

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        ds_hide_list = PluginSettings.get_hide_ds_id_list()

        for ds in data_sources:
            if ds.id in ds_hide_list:
                continue
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        self.menu.addSeparator()
        icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path),
                                        self.tr('Set proper scale'),
                                        self.iface.mainWindow())
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path),
                             self.tr('Set SlippyMap scales'),
                             self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        #self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + '/icons/mActionSettings.png'
        settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'),
                               self.iface.mainWindow())
        self.service_actions.append(settings_act)
        settings_act.triggered.connect(self.show_settings_dialog)
        self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + '/icons/mActionAbout.png'
        info_act = QAction(QIcon(icon_about_path), self.tr('About'),
                           self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)

    def remove_menu_buttons(self):
        """
        Remove menus/buttons from all toolbars and main submenu
        :return:
        None
        """
        # remove menu
        if self.menu:
            self.iface.webMenu().removeAction(self.menu.menuAction())
            self.iface.addLayerMenu().removeAction(self.menu.menuAction())
        # remove toolbar button
        if self.tb_action:
            self.iface.webToolBar().removeAction(self.tb_action)
            self.iface.layerToolBar().removeAction(self.tb_action)

    def append_menu_buttons(self):
        """
        Append menus and buttons to appropriate toolbar
        :return:
        """
        # add to QGIS menu
        if PluginSettings.move_to_layers_menu():
            self.iface.addLayerMenu().addMenu(self.menu)
        else:
            # need workaround for WebMenu
            _temp_act = QAction('temp', self.iface.mainWindow())
            self.iface.addPluginToWebMenu("_tmp", _temp_act)
            self.iface.webMenu().addMenu(self.menu)
            self.iface.removePluginWebMenu("_tmp", _temp_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        if PluginSettings.move_to_layers_menu():
            self.tb_action = self.iface.layerToolBar().addWidget(toolbutton)
        else:
            self.tb_action = self.iface.webToolBar().addWidget(toolbutton)

    def show_settings_dialog(self):
        settings_dlg = SettingsDialog()
        settings_dlg.exec_()
        # apply settings
        # self.remove_menu_buttons()
        self.build_menu_tree()
Example #42
0
class qosm:
    """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',
            'qosm_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.dlg_settings = None #TODO: add settings dialog

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&QOSM')
        
        self.toolbar = self.iface.addToolBar(u'QOSM')
        self.toolbar.setObjectName(u'QOSM')
        
        self.layers = []

    # 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('qosm', 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.menuObject.addAction(action)

        self.actions.append(action)

        return action

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

        #start logging
        qosmlogging.initialize_logging()
        qosmlogging.log("Initizlizing GUI")
        
        self.settingsdialog = DialogSettings(None)
        
        #add menu to web
        self.menuObject = QMenu(self.menu)
        self.menuObject.setIcon(QIcon(":/plugins/qosm/icon.png"))
        
        tmpAction = QAction("_tmp", self.iface.mainWindow())
        self.iface.addPluginToWebMenu("_tmp", tmpAction)
        self._menu = self.iface.webMenu()
        self._menu.addMenu(self.menuObject)
        self.iface.removePluginWebMenu("_tmp", tmpAction)        
        
        self.add_action(
            ':/plugins/qosm/icon_newlayer.png',
            text=self.tr(u'Add OSM tile layer'),
            callback=self.addOSMLayer,
            parent=self.iface.mainWindow())
        
        self.add_action(
            ':/plugins/qosm/icon_refresh.png',
            text=self.tr(u'Refresh OSM tile layers'),
            callback=self.refreshOSMLayers,
            parent=self.iface.mainWindow())
        
        self.add_action(
            ':/plugins/qosm/icon_settings.png',
            text=self.tr(u'QOSM Settings'),
            callback=self.qosmSettings,
            parent=self.iface.mainWindow())
        
        self.pluginLayerType = QOSMTileLayerType(self, self.onAddOSMLayer)
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.pluginLayerType)
        QgsMapLayerRegistry.instance().layersWillBeRemoved["QStringList"].connect(self.cleanLayerResources)


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginWebMenu(
                self.menu,
                action)
            self.iface.removeToolBarIcon(action)
            
        self.iface.webMenu().removeAction(self.menuObject.menuAction())
            
        # remove the toolbar
        del self.toolbar
        del self.menuObject
        
        QgsPluginLayerRegistry.instance().removePluginLayerType(QOSMTileLayer.LAYER_TYPE)
        QgsMapLayerRegistry.instance().layersWillBeRemoved["QStringList"].disconnect(self.cleanLayerResources)

    @pyqtSlot()
    def cleanLayerResources(self, layers):
        reg = QgsMapLayerRegistry.instance()
        for layerid in layers:
            layer = reg.mapLayer(layerid)
            if isinstance(layer, QOSMTileLayer):
                layer.cleantiles()
                #remove from internal cache of layers
                for i in range(len(self.layers)):
                    if self.layers[i].id() == layerid:
                        self.layers.pop(i)
                        break
        
    
    def addOSMLayer(self):
        """Adds a new OSM layer and opens the properties dialog to default settings"""
        # add a new qosmtilelayer
        layer = self.pluginLayerType.createLayer()
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        self.pluginLayerType.showLayerProperties(layer, newlayer=True)
    
    def refreshOSMLayers(self):
        #manual refresh OSM Layers
        for layer in self.layers:
            layer.refreshtiles()
    
    def qosmSettings(self):
        self.settingsdialog.sync_dialog()
        self.settingsdialog.show()
    
    def onAddOSMLayer(self, layer):
        self.layers.append(layer)
Example #43
0
class FragmentFrame(QFrame):

    # Signals:
    SIG_REMOVE_FRAGMENT = 'removeFragment()'
    # Fragment edition switch
    FRAGMENT_EDITION = False

    view = None
    fetcher = None

    def __init__(self, fragment, args, client, animation_manager=None, parent=None, has_menu_pos=True):
        """
            @fragment [Fragment] user_settings.Fragment object to describe fragment
            @client [RpcdClient] client
            @parent [QWidget] parent widget
        """

        #assert isinstance(client, RpcdClient)
        assert frag_types.has_key(fragment.type)

        QFrame.__init__(self, parent)

        self.animation_manager = animation_manager
        self.has_menu_pos = has_menu_pos
        self.fragment = fragment
        self.fetcher = frag_types[fragment.type].fetcher(fragment, args, client)
        self.connect(self.fetcher, SIGNAL(self.fetcher.ERROR_SIGNAL), self.errorHandler)
        self.window = parent
        self.cumulative_mode = False
        self.interval = Interval('daily')

        self.setFragmentColor()

        self.setFrameShadow(QFrame.Sunken)
        self.setFrameShape(QFrame.StyledPanel)
        self.setContextMenuPolicy(Qt.ActionsContextMenu)

        self.toolspace = None
        self.vbox = QVBoxLayout()
#        self.vbox.setContentsMargins(9,0,9,9)
        self.vbox.setContentsMargins(9,0,9,0)
        self.setLayout(self.vbox)

        self.stacked = QStackedWidget(self)
        updating_label = QLabel("<img src=\":/icons/refresh.png\" /><br />%s" % self.tr("Updating..."))
        updating_label.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
        self.stacked.addWidget(updating_label)

        # Create all actions for the rightclick context menu
        self.action_list = []
        self.switch_actions = {}

        self.viewlayout = QHBoxLayout()
        self.viewlayout.setContentsMargins(0,0,0,0)
        self.viewlayout.setSpacing(2)
        self.viewlayout.addStretch()
        widget = QWidget()
        widget.setLayout(self.viewlayout)
        self.vbox.addWidget(widget)

        self.line = QFrame(self)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")

        # Menu to choose position of fragment
        if self.has_menu_pos:
            self.pos_menu = QMenu(tr('Position'), self)
#        self.pos_action = QAction(tr('Position'), self.pos_menu)

        def make_lambda(l):
            """ usefull to create the lambda function with a copied parameter. or it'll bug """
            return lambda: QTimer.singleShot(0, lambda: self.setView(l))

        self.buttons = []

        button = QToolButton()
        button.visible = True
        button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored)
        button.setMinimumSize(0,16)
        button.setIcon(QIcon(":/icons/refresh.png"))
        button.setFixedHeight(16)
        button.setToolTip(tr("Refresh"))
        self.connect(button, SIGNAL("clicked()"), self.updateData)
        self.viewlayout.addWidget(button)
        self.buttons.append(button)

        # All of the views available for this kind of fragment.
        if len(frag_types[fragment.type].views) > 1:
            for label in frag_types[fragment.type].views:

                try:
                    item_name = views_list_label[label]
                except KeyError:
                    continue

                # item_name returns a unicode string, but PyQT (Qt 4.2.1) won't convert it to a char*
                # unless we convert it to a non-unicode string ....
                action = QAction(QIcon(':/icons/%s' % label),
                                 tr("Switch to %s") % self.tr(unicode(item_name)), self)
                self.connect(action, SIGNAL("triggered()"), make_lambda(label))
                self.action_list += [action]
                self.switch_actions[label] = action

                button = QToolButton()
                button.visible = True
                button.setBackgroundRole(QPalette.Button)
                button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Minimum)
                button.setMinimumSize(0,16)
                button.setFixedHeight(16)
                button.setIcon(QIcon(":/icons/%s" % label))
                button.setToolTip(tr("Switch to %s") % self.tr(unicode(item_name)))
                self.connect(button, SIGNAL("clicked()"), make_lambda(label))
                self.viewlayout.addWidget(button)
                self.buttons.append(button)

            # Separator
            action = QAction(self)
            action.setSeparator(True)
            self.action_list += [action]

        # Refresh
        action = QAction(QIcon(':/icons/refresh.png'), tr('Refresh'), self)
        self.connect(action, SIGNAL('triggered()'), self.updateData)
        self.action_list += [action]
        if self.FRAGMENT_EDITION:
            # Edit
            action = QAction(QIcon(':/icons/edit.png'), tr('Edit this fragment...'), self)
            self.connect(action, SIGNAL('triggered()'), self.editFragment)
            self.action_list += [action]
            # Delete
            action = QAction(QIcon(':/icons/moins.png'), tr('Delete this fragment'), self)
            self.connect(action, SIGNAL('triggered()'), self.removeFragment)
            self.action_list += [action]

        self.setView(fragment.view, update=False)

        self.setAcceptDrops(True)
        self.pos = -1

    def mouseMoveEvent(self, event):
        if event.buttons() != Qt.LeftButton:
            return

        mimeData = QMimeData()
        if self.pos == -1:
            return
        mimeData.setData("splitter/fragment", QByteArray.number(self.pos))
        drag = QDrag(self)
        drag.setMimeData(mimeData)
        drag.setHotSpot(event.pos() - self.rect().topLeft())

        dropAction = drag.start(Qt.MoveAction)

        if dropAction == Qt.MoveAction:
            self.close()

    def dragEnterEvent(self, event):
        event.accept()

    def dropEvent(self, event):

        data = event.mimeData().data("splitter/fragment").toInt()
        if not data[1]:
            return

        frame_pos = data[0]

        if frame_pos == self.pos:
            return

        event.setDropAction(Qt.MoveAction)
        event.accept()

        self.window.changedPositionFragment(self.pos, frame_pos)

#    def __del__(self):
#        self.destructor()

    def destructor(self):
        if self.view:
            self.freeView()
        if self.fetcher:
            self.disconnect(self.fetcher, SIGNAL(self.fetcher.ERROR_SIGNAL), self.errorHandler)
            self.fetcher.destructor()
            self.fetcher = None

    def getView(self):
        return self.view

    def getFragment(self):
        return self.fragment

    def setCumulative(self, cumulative):
        self.cumulative_mode = cumulative
        if self.view:
            self.view.setCumulative(cumulative)

    def setInterval(self, interval):
        self.interval = interval
        if self.view:
            self.view.setInterval(interval)

    def setFragmentColor(self):

        # XXX: We have to put classes which we colorize, because some objects bug
        # when we try to put a background on them. For example, do NOT colorize
        # QScrollBar, it'll not work anyway:
        # http://doc.trolltech.com/4.4/stylesheet-examples.html#customizing-qscrollbar
        # "The QScrollBar can be styled using its subcontrols like handle,
        # add-line, sub-line, and so on. Note that if one property or
        # sub-control is customized, all the other properties or sub-controls
        # must be customized as well."
        self.setStyleSheet("""
         QFrame, QPushButton, QTableCornerButton, QAbstractSpinBox, QLineEdit {
             background-color: #%06X;
         }

         """ % self.fragment.background_color)

    def editFragment(self):
        if AddFragDialog(self.window, self.fragment, self).run():
            self.setFragmentColor()
            self.setView(self.fragment.view, update=True)

    def removeFragment(self):
        reply = QMessageBox.question(self, self.tr("Delete a fragment"),
                                           unicode(self.tr('Are you sure to delete the fragment "%s" from the view?')) % self.fragment.title,
                                           QMessageBox.Yes|QMessageBox.No)

        if reply == QMessageBox.Yes:
            QTimer.singleShot(0, self._removeFragment_emit)

    def _removeFragment_emit(self):
        self.emit(SIGNAL(self.SIG_REMOVE_FRAGMENT))

#    def resizeEvent(self, event):
#        QFrame.resizeEvent(self, event)
#        self.view.resize(event.size())

    def freeView(self):
        if self.view:
            self.view.destructor()
            self.disconnect(self.view, SIGNAL('open_page'), self._open_page)
            self.disconnect(self.view, SIGNAL('add_filter'), self._add_filter)
            self.disconnect(self.view, SIGNAL('updating'), self._show_animation)
            self.disconnect(self.view, SIGNAL('updated'), self._show_view)
            self.disconnect(self.view, SIGNAL('EAS_Message'), self.EAS_SendMessage)
            self.stacked.removeWidget(self.view)
            self.vbox.removeWidget(self.stacked)
            self.vbox.removeWidget(self.line)
            self.view.setParent(None)
            self.view.hide()
            self.view.deleteLater()
        if self.toolspace:
            self.viewlayout.removeWidget(self.toolspace)
            self.toolspace.setParent(None)
            self.toolspace.hide()
            self.toolspace.deleteLater()

        if self.view and hasattr(self.view, "uuid"):
            if self.animation_manager:
                self.animation_manager.remove(self.view.uuid)
            self.view = None
        self.toolspace = None

    def setView(self, label, update=True):

        # If there isn't any view for this fragment, use the first available view
        # of this kind of fragment.
        if not label:
            assert frag_types.has_key(self.fragment.type)
            assert len(frag_types[self.fragment.type].views) > 0

            label = frag_types[self.fragment.type].views[0]


        for button in self.buttons:
            if label in button.toolTip():
                button.visible = False
            else:
                if not button.isEnabled():
                    button.visible = True
#        assert views_list.has_key(label)

        self.freeView()

        # Create the view object.
        self.view = views_list[label](self.fetcher, self)
        if label == "histo" or label == 'pie':
            self.view.is_graphics_view = True
            if label == 'histo':
                self.view.chart_type = BARCHART
            else:
                self.view.chart_type = PIECHART
        else:
            self.view.is_graphics_view = False

        if label != "error":
            self.connect(self, SIGNAL("closed"), self.setClosed)
            if self.animation_manager:
                if self.view.is_graphics_view:
                    self.connect(self.view, SIGNAL("animation_done(QString)"), self, SIGNAL("animation_done(QString)"))
                self.animation_manager.addView(self.view)

        self.connect(self.view, SIGNAL("showButtons"), self.showButtonsSlot)
        self.connect(self.view, SIGNAL("autoRefresh"), self.updateData)
                
        self.view.setCumulative(self.cumulative_mode)
        self.view.setInterval(self.interval)
        self.stacked.insertWidget(0, self.view)
        self._show_view()
        self.connect(self.view, SIGNAL('open_page'), self._open_page)
        self.connect(self.view, SIGNAL('add_filter'), self._add_filter)
        self.connect(self.view, SIGNAL('updating'), self._show_animation)
        self.connect(self.view, SIGNAL('updated'), self._show_view)
        self.connect(self.view, SIGNAL('EAS_Message'), self.EAS_SendMessage)

        # Set some features if there are available on each or each type of widget.
        if hasattr(self.view, 'setFrameShape'):
            self.view.setFrameShape(QFrame.NoFrame)
        self.view.setContextMenuPolicy(Qt.ActionsContextMenu)

        # All views can ask me to display a toolspace (a widget with all kind of
        # things in).
        self.view.title.setText(self.view.getTitle())
        self.fragment.view = label

        self.toolspace = self.view.getToolspace()
        self.viewlayout.insertWidget(0, self.toolspace)
        self.vbox.addWidget(self.line)
        self.vbox.addWidget(self.stacked)

        # Set the new menu.
        for action in self.actions():
            self.removeAction(action)

        for view_label, action in self.switch_actions.items():
            action.setEnabled(view_label != self.fragment.view)

        for action in self.action_list:
            self.addAction(action)
            self.view.addAction(action)

        # Add view's eventual menu.
        view_actions = self.view.getActions()
        if view_actions:
            separator = QAction(self)
            separator.setSeparator(True)
            view_actions = [separator] + view_actions

            for action in view_actions:
                self.view.addAction(action)
                self.addAction(action)

        if self.has_menu_pos:
            self.view.addAction(self.pos_menu.menuAction())
            self.addAction(self.pos_menu.menuAction())

        if update:
            self.updateData()

    def setClosed(self):
        if self.view:
            self.view.setClosed()
        self.destructor()

    def errorHandler(self, e):
        """ This method is called when fetcher raises an error. """

        # Store error in fragment, and the ErrorFragmentView will able to
        # load it

        error = exceptionAsUnicode(e)
        self.fragment.error = error

        # We keep last view in the fragment, to prevent setView() method to
        # put 'error' in the fragment.view string attribute.
        last_view = self.fragment.view
        self.setView('error', update=False) # load the error fragment
        self.fragment.view = last_view

    def showButtonsSlot(self):
        for button in self.buttons:
            if hasattr(button, 'visible'):
                if button.visible:
                    button.setEnabled(True)
                else:
                    button.setEnabled(False)

    def updateData(self):

        if hasattr(self.fragment, 'error'):
            self.setView(self.fragment.view, update=False)
            del self.fragment.error

        for button in self.buttons:
            button.setEnabled(False)

        self.view.requestData()

    def _open_page(self, *args, **kwargs):
        self.emit(SIGNAL('open_page'), *args, **kwargs)

    def _add_filter(self, *args, **kwargs):
        self.emit(SIGNAL('add_filter'), *args, **kwargs)

    def EAS_SendMessage(self, *args, **kwargs):
        self.emit(SIGNAL('EAS_Message'), *args, **kwargs)

    def _show_animation(self):
        self.stacked.setCurrentIndex(1)

    def _show_view(self):
        self.stacked.setCurrentIndex(0)