Example #1
0
    def add_custom_menu_items_for_node(self, node, menu):
        if node.get('type') == 'scenario':
            node_executable = (node.get('executable') == 'True')
            menu.addAction(self.actExecutable)

            # Workaround: disabled items do not show check marks
            if node.get('inherited') is None:
                self.actExecutable.setEnabled(True)
                self.actExecutable.setText('Executable')
                self.actExecutable.setChecked(node_executable)
            else:
                self.actExecutable.setDisabled(True)
                self.actExecutable.setText(
                    'Executable: %s' % ('Yes' if node_executable else 'No'))

            if node_executable:
                menu.addAction(self.actRunScenario)
            if node.find('models_to_run') is None:
                #if there isn't a child node models_to_run
                menu.addAction(self.actModelsToRun)
        elif node.get('type') in ['selectable', 'model_choice']:
            menu.addAction(self.actMoveNodeUp)
            menu.addAction(self.actMoveNodeDown)
        elif node.tag == 'models_to_run':  # special case of a selectable list
            models_menu = QMenu(menu)
            models_menu.setTitle('Add model to run')
            models_menu.setIcon(IconLibrary.icon('add'))
            available_model_names = get_model_names(self.project)
            for model_name in available_model_names:
                cb = lambda x=model_name, y=self.selected_index(
                ): self.addModel(y, x)
                action = self.create_action('model', model_name, cb)
                models_menu.addAction(action)
            menu.addMenu(models_menu)
Example #2
0
 def createMenu( self, parent ):
     """
     Creates a new menu for the inputed parent item.
     
     :param      parent | <QMenu>
     """
     menu = QMenu(parent)
     menu.setTitle('&View')
     
     act = menu.addAction('Lock/Unlock Layout')
     act.setIcon(QIcon(projexui.resources.find('img/view/lock.png')))
     act.triggered.connect(self.toggleLocked)
     
     menu.addSeparator()
     act = menu.addAction('Export Layout as...')
     act.setIcon(QIcon(projexui.resources.find('img/view/export.png')))
     act.triggered.connect(self.exportProfile)
     
     act = menu.addAction('Import Layout from...')
     act.setIcon(QIcon(projexui.resources.find('img/view/import.png')))
     act.triggered.connect(self.importProfile)
     
     menu.addSeparator()
     act = menu.addAction('Reset Layout')
     act.setIcon(QIcon(projexui.resources.find('img/view/remove.png')))
     act.triggered.connect(self.reset)
     
     return menu
Example #3
0
 def contextMenuEvent(self, e):
     menu = QMenu(self)
     subMenu = QMenu(menu)
     titleHistoryMenu = QCoreApplication.translate("PythonConsole", "Command History")
     subMenu.setTitle(titleHistoryMenu)
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Show"),
         self.showHistory, 'Ctrl+Shift+SPACE')
     subMenu.addSeparator()
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Save"),
         self.writeHistoryFile)
     subMenu.addSeparator()
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Clear File"),
         self.clearHistory)
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Clear Session"),
         self.clearHistorySession)
     menu.addMenu(subMenu)
     menu.addSeparator()
     copyAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Copy"),
         self.copy, QKeySequence.Copy)
     pasteAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Paste"),
         self.paste, QKeySequence.Paste)
     copyAction.setEnabled(False)
     pasteAction.setEnabled(False)
     if self.hasSelectedText():
         copyAction.setEnabled(True)
     if QApplication.clipboard().text():
         pasteAction.setEnabled(True)
     menu.exec_(self.mapToGlobal(e.pos()))
Example #4
0
    def createMenu(self, parent):
        """
        Creates a new menu for the inputed parent item.
        
        :param      parent | <QMenu>
        """
        menu = QMenu(parent)
        menu.setTitle('&View')

        act = menu.addAction('Lock/Unlock Layout')
        act.setIcon(QIcon(projexui.resources.find('img/view/lock.png')))
        act.triggered.connect(self.toggleLocked)

        menu.addSeparator()
        act = menu.addAction('Export Layout as...')
        act.setIcon(QIcon(projexui.resources.find('img/view/export.png')))
        act.triggered.connect(self.exportProfile)

        act = menu.addAction('Import Layout from...')
        act.setIcon(QIcon(projexui.resources.find('img/view/import.png')))
        act.triggered.connect(self.importProfile)

        menu.addSeparator()
        act = menu.addAction('Reset Layout')
        act.setIcon(QIcon(projexui.resources.find('img/view/remove.png')))
        act.triggered.connect(self.reset)

        return menu
Example #5
0
def menu_edit(parent):
    m = QMenu(parent)
    m.setTitle(_("menu title", "&Edit"))
    role = QAction.PreferencesRole if use_osx_menu_roles() else QAction.NoRole
    m.addAction(icons.get('preferences-system'), _("Pr&eferences..."),
                edit_preferences).setMenuRole(role)
    return m
 def add_custom_menu_items_for_node(self, node, menu):
     if node.get('type') == 'scenario':
         node_executable = (node.get('executable') == 'True')
         menu.addAction(self.actExecutable)
         
         # Workaround: disabled items do not show check marks
         if node.get('inherited') is None:
             self.actExecutable.setEnabled(True)
             self.actExecutable.setText('Executable')
             self.actExecutable.setChecked(node_executable)
         else:
             self.actExecutable.setDisabled(True)
             self.actExecutable.setText('Executable: %s' % ('Yes' if node_executable else 'No'))
             
         if node_executable:
             menu.addAction(self.actRunScenario)
         if node.find('models_to_run') is None:  
             #if there isn't a child node models_to_run
             menu.addAction(self.actModelsToRun)                
     elif node.get('type') in ['selectable', 'model_choice']:
         menu.addAction(self.actMoveNodeUp)
         menu.addAction(self.actMoveNodeDown)
     elif node.tag == 'models_to_run': # special case of a selectable list
         models_menu = QMenu(menu)
         models_menu.setTitle('Add model to run')
         models_menu.setIcon(IconLibrary.icon('add'))
         available_model_names = get_model_names(self.project)
         for model_name in available_model_names:
             cb = lambda x = model_name, y = self.selected_index(): self.addModel(y, x)
             action = self.create_action('model', model_name, cb)
             models_menu.addAction(action)
         menu.addMenu(models_menu)
Example #7
0
class Tray(QObject):
    activated = pyqtSignal()

    def __init__(self, parent, title, icon):
        QObject.__init__(self)

        # Setup contextual menu
        if kde:
            self.menu = KMenu(parent)
            self.tray = KStatusNotifierItem(parent)
            self.tray.setStatus(KStatusNotifierItem.Passive)
            self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
            self.tray.setAssociatedWidget(parent)
            self.tray.setStandardActionsEnabled(False)
            self.tray.activateRequested.connect(self._activateRequested)
        else:
            self.menu = QMenu()
            self.tray = QSystemTrayIcon()
            self.tray.activated.connect(self._activated)
        self.setIcon(icon)
        self.setTitle(title)
        if not kde:
            self.tray.show()
        self.tray.setContextMenu(self.menu)

    def setActive(self, active=True):
        if kde:
            self.tray.setStatus(KStatusNotifierItem.Active if active else KStatusNotifierItem.Passive)

    def setTitle(self, title):
        if kde:
            self.tray.setTitle(title)
            self.tray.setToolTipTitle(title)
        else:
            self.tray.setToolTip(title)
        self.menu.setTitle(title)

    def setToolTipSubTitle(self, subtitle):
        if kde:
            self.tray.setToolTipSubTitle(subtitle)

    def setIcon(self, icon):
        if kde:
            self.tray.setIconByPixmap(icon)
            self.tray.setToolTipIconByPixmap(icon)
        else:
            self.tray.setIcon(icon)

    def showMessage(self, title, message, icon=None):
        if kde:
            self.tray.showMessage(title, message, "network-server")
        else:
            self.tray.showMessage(title, message, QSystemTrayIcon.Information if icon is None else icon)

    def _activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.activated.emit()

    def _activateRequested(self, active, pos):
        self.activated.emit()
    def process_custom_menu(self, point):
        ''' See XmlController for documentation '''
        item = self.select_item_at(point)
        if not item:
            return
        menu = QMenu()
        node = item.node

        if node.get('executable') == 'True':
            menu.addAction(self.actRunScenario)
        elif node.get('type') in ['selectable', 'model_choice']:
            menu.addAction(self.actMoveNodeUp)
            menu.addAction(self.actMoveNodeDown)
        elif node.tag == 'models_to_run': # special case of a selectable list
            models_menu = QMenu(menu)
            models_menu.setTitle('Add model to run')
            models_menu.setIcon(IconLibrary.icon('add'))
            available_model_names = get_model_names(self.project)
            for model_name in available_model_names:
                cb = lambda x = model_name, y = self.selected_index(): self.addModel(y, x)
                action = self.create_action('model', model_name, cb)
                models_menu.addAction(action)
            menu.addMenu(models_menu)

        self.add_default_menu_items_for_node(node, menu)

        if not menu.isEmpty():
            menu.exec_(QCursor.pos())
Example #9
0
class LocationLab:

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

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

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

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

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

    def unload(self):
        self.menu.deleteLater()
Example #10
0
    def showContextMenu(self, point):
        scipos = self.SendScintilla(
                QsciScintilla.SCI_POSITIONFROMPOINT, point.x(), point.y())
        point = self.mapToGlobal(point)
        exp, _ = self.getWordOrSelectionAndRangeFromPosition(scipos)

        # self.lineIndexFromPosition(..) returns tuple. first element is line
        self.lastContextMenuLine = int(self.lineIndexFromPosition(scipos)[0])

        self.__popupMenu = QMenu(self)
        self.__popupMenu.addAction(self.distributedObjects.actions.ToggleTrace)

        if exp:
            self.__popupMenu.addAction(self.distributedObjects.actions.getAddToWatchAction(exp, self.signalProxy.addWatch))
            self.__popupMenu.addAction(self.distributedObjects.actions.getAddToDatagraphAction(exp, self.distributedObjects.datagraphController.addWatch))
            self.__popupMenu.addAction(self.distributedObjects.actions.getAddWatchpointAction(exp, self.distributedObjects.breakpointModel.insertWatchpoint))

            listOfTracepoints = self.tracepointController.getTracepointsFromModel()
            if listOfTracepoints:
                subPopupMenu = QMenu(self)
                subPopupMenu.setTitle("Add variable " + exp + " to tracepoint...")

                for tp in listOfTracepoints:
                    subPopupMenu.addAction(self.distributedObjects.actions.getAddToTracepointAction(exp, tp.name, tp.addVar))

                self.__popupMenu.addSeparator()
                self.__popupMenu.addMenu(subPopupMenu)

        self.__popupMenu.popup(point)

        # disable the tooltips while the menu is shown
        self.__enableToolTip(False)
        self.__popupMenu.aboutToHide.connect(lambda: self.__enableToolTip(True))
Example #11
0
    def process_custom_menu(self, point):
        ''' See XmlController for documentation '''
        item = self.select_item_at(point)
        if not item:
            return
        menu = QMenu()
        node = item.node

        if node.get('executable') == 'True':
            menu.addAction(self.actRunScenario)
        elif node.get('type') in ['selectable', 'model_choice']:
            menu.addAction(self.actMoveNodeUp)
            menu.addAction(self.actMoveNodeDown)
        elif node.tag == 'models_to_run':  # special case of a selectable list
            models_menu = QMenu(menu)
            models_menu.setTitle('Add model to run')
            models_menu.setIcon(IconLibrary.icon('add'))
            available_model_names = get_model_names(self.project)
            for model_name in available_model_names:
                cb = lambda x=model_name, y=self.selected_index(
                ): self.addModel(y, x)
                action = self.create_action('model', model_name, cb)
                models_menu.addAction(action)
            menu.addMenu(models_menu)

        self.add_default_menu_items_for_node(node, menu)

        if not menu.isEmpty():
            menu.exec_(QCursor.pos())
Example #12
0
 def contextMenuEvent(self, e):
     menu = QMenu(self)
     subMenu = QMenu(menu)
     titleHistoryMenu = QCoreApplication.translate("PythonConsole",
                                                   "Command History")
     subMenu.setTitle(titleHistoryMenu)
     subMenu.addAction(QCoreApplication.translate("PythonConsole", "Show"),
                       self.showHistory, 'Ctrl+Shift+SPACE')
     subMenu.addSeparator()
     subMenu.addAction(QCoreApplication.translate("PythonConsole", "Save"),
                       self.writeHistoryFile)
     subMenu.addSeparator()
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Clear File"),
         self.clearHistory)
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Clear Session"),
         self.clearHistorySession)
     menu.addMenu(subMenu)
     menu.addSeparator()
     copyAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Copy"), self.copy,
         QKeySequence.Copy)
     pasteAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Paste"), self.paste,
         QKeySequence.Paste)
     copyAction.setEnabled(False)
     pasteAction.setEnabled(False)
     if self.hasSelectedText():
         copyAction.setEnabled(True)
     if QApplication.clipboard().text():
         pasteAction.setEnabled(True)
     menu.exec_(self.mapToGlobal(e.pos()))
Example #13
0
def menu_help(parent):
    m = QMenu(parent)
    m.setTitle(_('menu title', '&Help'))
    role = QAction.AboutRole if use_osx_menu_roles() else QAction.NoRole
    m.addAction(icons.get('help-about'),
                _("&About {appname}...").format(appname=appinfo.appname),
                help_about).setMenuRole(role)
    return m
Example #14
0
def menu_sessions(parent):
    m = QMenu(parent)
    m.setTitle(_('menu title', '&Session'))
    m.triggered.connect(slot_session_action)
    import sessions
    for name in sessions.sessionNames():
        a = m.addAction(name.replace('&', '&&'))
        a.setObjectName(name)
    qutil.addAccelerators(m.actions())
    return m    
Example #15
0
def menu_sessions(parent):
    m = QMenu(parent)
    m.setTitle(_('menu title', '&Session'))
    m.triggered.connect(slot_session_action)
    import sessions
    for name in sessions.sessionNames():
        a = m.addAction(name.replace('&', '&&'))
        a.setObjectName(name)
    qutil.addAccelerators(m.actions())
    return m
Example #16
0
 def addMenu(self, parent, name, title, icon_path):
     """
     Adds a QMenu
     """
     child = QMenu(parent)
     child.setObjectName(name)
     child.setTitle(self.tr(title))
     child.setIcon(QIcon(icon_path))
     parent.addMenu(child)
     return child
Example #17
0
def menu_file_open_recent(parent):
    m = QMenu(parent)
    m.setTitle(_("Open &Recent"))
    m.triggered.connect(slot_file_open_recent_action)
    import recentfiles
    for url in recentfiles.urls():
        f = url.toLocalFile()
        dirname, basename = os.path.split(f)
        text = "{0}  ({1})".format(basename, util.homify(dirname))
        m.addAction(text).url = url
    qutil.addAccelerators(m.actions())
    return m
Example #18
0
def menu_file_open_recent(parent):
    m = QMenu(parent)
    m.setTitle(_("Open &Recent"))
    m.triggered.connect(slot_file_open_recent_action)
    import recentfiles
    for url in recentfiles.urls():
        f = url.toLocalFile()
        dirname, basename = os.path.split(f)
        text = "{0}  ({1})".format(basename, util.homify(dirname))
        m.addAction(text).url = url
    qutil.addAccelerators(m.actions())
    return m
Example #19
0
    def createCtxMenu(self, value, isLink, evt):
        'Creates and configures the menu itself'
        
        m = QMenu(self)
        sub = QMenu(Label.BROWSER_ASSIGN_TO, m)
        m.setTitle(Label.BROWSER_ASSIGN_TO)
        for index, label in self._fields.items():
            act = QAction(label, m, 
                triggered=self._makeMenuAction(index, value, isLink))
            sub.addAction(act)

        m.addMenu(sub)
        action = m.exec_(self.mapToGlobal(evt.pos()))
Example #20
0
def menu_file(parent):
    m = QMenu(parent)
    m.setTitle(_("menu title", "&File"))
    m.addAction(icons.get('document-new'), _("action: new document", "&New"), file_new)
    m.addMenu(menu_file_new_from_template(m))
    m.addAction(icons.get('tools-score-wizard'), _("New Score with &Wizard..."), file_new_with_wizard)
    m.addSeparator()
    m.addAction(icons.get('document-open'), _("&Open..."), file_open)
    m.addMenu(menu_file_open_recent(m))
    m.addSeparator()
    m.addMenu(menu_file_import(m))
    m.addSeparator()
    role = QAction.QuitRole if use_osx_menu_roles() else QAction.NoRole
    m.addAction(icons.get('application-exit'), _("&Quit"), app.qApp.quit).setMenuRole(role)
    return m
    def process_custom_menu(self, point):
        ''' See XmlConfig.processCustomMenu for documentation '''
        index = self.select_item_at(point)
        if not index:
            return

        node = self.selected_item().node
        menu = QMenu(self.view)

        if node.tag == 'models':
            submenu = QMenu(menu) # to populate with templates
            submenu.setTitle('Create model from template')
            for action in self.create_from_template_actions:
                submenu.addAction(action)
            menu.addMenu(submenu)

        if node.tag == 'model':
            # If the users right clicks a model, give them the option to
            # estimate it only if the model has a (non empty) specification
            # subnode. If the model holds subgroups -- inform the user how to
            # estimate them.
            spec_node = node.find('specification')

            submodels = None
            if spec_node is not None:
                submodels = spec_node.getchildren()
            if spec_node is not None and submodels:
                # check if its groups by type checking the first node
                # note: this is not a reliable method if models can have mixed
                # submodels and submodel groups.
                if submodels[0].tag == 'submodel':
                    menu.addAction(self.action_run_estimation)
                else:
                    menu.addAction(self.action_show_how_to_estimate_groups)

        if node.tag == 'submodel' and not node.get('inherited'):
            menu.addAction(self.action_edit_submodel)

        if node.tag == 'submodel_group':
            menu.addAction(self.action_run_estimation_group)

        self.add_default_menu_items_for_node(node, menu)

        if not menu.isEmpty():
            menu.exec_(QCursor.pos())
Example #22
0
    def process_custom_menu(self, point):
        ''' See XmlConfig.processCustomMenu for documentation '''
        index = self.select_item_at(point)
        if not index:
            return

        node = self.selected_item().node
        menu = QMenu(self.view)

        if node.tag == 'models':
            submenu = QMenu(menu)  # to populate with templates
            submenu.setTitle('Create model from template')
            for action in self.create_from_template_actions:
                submenu.addAction(action)
            menu.addMenu(submenu)

        if node.tag == 'model':
            # If the users right clicks a model, give them the option to
            # estimate it only if the model has a (non empty) specification
            # subnode. If the model holds subgroups -- inform the user how to
            # estimate them.
            spec_node = node.find('specification')

            submodels = None
            if spec_node is not None:
                submodels = spec_node.getchildren()
            if spec_node is not None and submodels:
                # check if its groups by type checking the first node
                # note: this is not a reliable method if models can have mixed
                # submodels and submodel groups.
                if submodels[0].tag == 'submodel':
                    menu.addAction(self.action_run_estimation)
                else:
                    menu.addAction(self.action_show_how_to_estimate_groups)

        if node.tag == 'submodel' and not node.get('inherited'):
            menu.addAction(self.action_edit_submodel)

        if node.tag == 'submodel_group':
            menu.addAction(self.action_run_estimation_group)

        self.add_default_menu_items_for_node(node, menu)

        if not menu.isEmpty():
            menu.exec_(QCursor.pos())
Example #23
0
def menu_file_new_from_template(parent):
    m = QMenu(parent)
    m.setTitle(_("New from &Template"))
    m.triggered.connect(slot_file_new_from_template_action)
    from snippet import model, actions, snippets
    groups = {}
    for name in sorted(model.model().names()):
        variables = snippets.get(name).variables
        group = variables.get('template')
        if group:
            action = actions.action(name, m)
            if action:
                groups.setdefault(group, []).append(action)
    for group in sorted(groups):
        for action in groups[group]:
            m.addAction(action)
        m.addSeparator()
    qutil.addAccelerators(m.actions())
    return m
Example #24
0
def menu_file_new_from_template(parent):
    m = QMenu(parent)
    m.setTitle(_("New from &Template"))
    m.triggered.connect(slot_file_new_from_template_action)
    from snippet import model, actions, snippets
    groups = {}
    for name in sorted(model.model().names()):
        variables = snippets.get(name).variables
        group = variables.get('template')
        if group:
            action = actions.action(name, m)
            if action:
                groups.setdefault(group, []).append(action)
    for group in sorted(groups):
        for action in groups[group]:
            m.addAction(action)
        m.addSeparator()
    qutil.addAccelerators(m.actions())
    return m
Example #25
0
    def on_classifyBtn_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        #raise NotImplementedError
        if self.showGroupBtn.isChecked():
            self.showGroupBtn.setChecked(False)
            self.on_showGroupBtn_clicked()
        if self.classifyMenu is None:
            self.classifyMenu = QMenu(self)
            subMenu = QMenu(self)
            subMenu.setTitle(u'地区板块')
            self.classifyMenuGroup = QActionGroup(self)
            for key in myGlobal.area2ids:
                if len(key) != 0:
                    action = MyAction(key, myGlobal.area2ids[key],
                                      self.changeIds, self)
                    subMenu.addAction(action)
                    self.classifyMenuGroup.addAction(action)
            self.classifyMenu.addMenu(subMenu)
            subMenu = QMenu(self)
            subMenu.setTitle(u'行业板块')
            for key in myGlobal.industry2ids:
                if len(key) != 0:
                    action = MyAction(key, myGlobal.industry2ids[key],
                                      self.changeIds, self)
                    subMenu.addAction(action)
                    self.classifyMenuGroup.addAction(action)
            self.classifyMenu.addMenu(subMenu)
            subMenu = MyMenu(u'向上版块', 'FLAG_UP', self, self.classifyMenuGroup)
            self.classifyMenu.addMenu(subMenu)
            subMenu = MyMenu(u'向下版块', 'FLAG_DOWN', self,
                             self.classifyMenuGroup)
            self.classifyMenu.addMenu(subMenu)

        self.classifyBtn.setChecked(True)
        pos = QPoint()
        pos.setX(0)
        pos.setY(-self.classifyMenu.sizeHint().height())
        self.classifyMenu.exec_(self.classifyBtn.mapToGlobal(pos))
Example #26
0
    def _create_menu(self):
        mbar = self._ui.menubar
        menu = QMenu(mbar)
        menu.setTitle("File")

        menu.addAction(self._actions['data_new'])
        menu.addAction(self._actions['session_save'])
        menu.addAction(self._actions['session_restore'])

        menu.addAction(self._actions['tab_new'])
        menu.addAction(self._actions['window_new'])
        mbar.addMenu(menu)

        menu = QMenu(mbar)
        menu.setTitle("Tab")
        menu.addAction(self._actions['tab_new'])
        menu.addAction(self._actions['window_new'])
        menu.addSeparator()
        menu.addAction(self._actions['cascade'])
        menu.addAction(self._actions['tile'])
        menu.addAction(self._actions['tab_rename'])
        mbar.addMenu(menu)

        menu = QMenu(mbar)
        menu.setTitle("Layers")
        menu.addActions(self._ui.layerWidget.actions())
        a = act("Define new component", self,
                tip="Define a new component using python expressions")
        a.triggered.connect(self._create_component)
        menu.addAction(a)

        mbar.addMenu(menu)
Example #27
0
    def add_custom_menu_items_for_node(self, node, menu):
        if node.tag == 'models':
            submenu = QMenu(menu) # to populate with templates
            submenu.setTitle('Create model from template')
            for action in self.create_from_template_actions:
                submenu.addAction(action)
            menu.addMenu(submenu)

        if node.tag == 'model':
            # If the users right clicks a model, give them the option to
            # estimate it only if the model has a (non empty) specification
            # subnode. If the model holds subgroups -- inform the user how to
            # estimate them.
            spec_node = node.find('specification')

            submodels = None
            if spec_node is not None:
                submodels = spec_node.getchildren()
            if spec_node is not None and submodels:
                # check if its groups by type checking the first node
                # note: this is not a reliable method if models can have mixed
                # submodels and submodel groups.
                if submodels[0].tag == 'submodel':
                    menu.addAction(self.action_run_estimation)
                else:
                    menu.addAction(self.action_show_how_to_estimate_groups)

        if node.tag == 'submodel' and not node.get('inherited'):
            menu.addAction(self.action_edit_submodel)

        if node.tag == 'submodel_group':
            menu.addAction(self.action_run_estimation_group)

        # In this menu, the first custom action is always the default action        
        if not menu.isEmpty():
            menu.setDefaultAction(menu.actions()[0])
Example #28
0
    def _create_menu(self):
        mbar = self._ui.menubar
        menu = QMenu(mbar)
        menu.setTitle("File")

        menu.addAction(self._actions['data_new'])
        #menu.addAction(self._actions['data_save'])  # XXX add this
        menu.addAction(self._actions['session_restore'])
        menu.addAction(self._actions['session_save'])

        mbar.addMenu(menu)

        menu = QMenu(mbar)
        menu.setTitle("Canvas")
        menu.addAction(self._actions['tab_new'])
        menu.addAction(self._actions['viewer_new'])
        menu.addSeparator()
        menu.addAction(self._actions['cascade'])
        menu.addAction(self._actions['tile'])
        menu.addAction(self._actions['tab_rename'])
        mbar.addMenu(menu)

        menu = QMenu(mbar)
        menu.setTitle("Data Manager")
        menu.addActions(self._ui.layerWidget.actions())

        mbar.addMenu(menu)

        menu = QMenu(mbar)
        menu.setTitle("Toolbars")
        tbar = EditSubsetModeToolBar()
        self._mode_toolbar = tbar
        self.addToolBar(tbar)
        tbar.hide()
        a = QAction("Selection Mode Toolbar", menu)
        a.setCheckable(True)
        a.toggled.connect(tbar.setVisible)
        try:
            tbar.visibilityChanged.connect(a.setChecked)
        except AttributeError:  # Qt < 4.7. Signal not supported
            pass

        menu.addAction(a)
        menu.addActions(tbar.actions())
        mbar.addMenu(menu)
Example #29
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 #30
0
def menu_window(parent):
    m = QMenu(parent)
    m.setTitle(_('menu title', '&Window'))
    m.addAction(icons.get('window-new'), _("New &Window"), file_new)
    return m
Example #31
0
 def setTitle(self, title):
     self._title.setText(title)
     QMenu.setTitle(title)
Example #32
0
    def load_menus(self, profile=None, schema=None):
        """
        Load menus in the main windows qgis bar
        """
        if not schema:
            schema = self.combo_schema.currentText()
        if not profile:
            profile = self.combo_profile.currentText()
        # remove previous menus
        for menu in self.uiparent.menus:
            self.uiparent.iface.mainWindow().menuBar().removeAction(
                menu.menuAction())

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

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

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

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

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

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

            layer.setData(uri_struct.uri)
            layer.setWhatsThis(uri_struct.providerKey)
            layer.triggered.connect(self.layer_handler[uri_struct.layerType])
            menu.addAction(layer)
class ProfilesPlugin:

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

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

        self.userProfileAction = None
        self.profilesMenu = None

        iface.initializationCompleted.connect(self.initProfile)

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

    def initGui(self):
        self.addMenus()

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

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

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

        self.profilesMenu.addSeparator()

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

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

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

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


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

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

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

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

    def tr(self, text):
        return QCoreApplication.translate('Profiles', text)
Example #34
0
    def OnSelect(self, x0, x1, y0, y1):
        x0, x1 = min(x0, x1), max(x0, x1)
        y0, y1 = min(y0, y1), max(y0, y1)
        objets_dans_la_zone = []
        for objet in self.feuille_actuelle.liste_objets():
            espace = objet.espace_vital
            if espace is not None:
                xmin, xmax, ymin, ymax = espace
                if x0 <= xmin <= xmax <= x1 and y0 <= ymin <= ymax <= y1:
                    objets_dans_la_zone.append(objet)
        self.feuille_actuelle.objets_en_gras(*objets_dans_la_zone)

        def exporte():
            actuelle = self.feuille_actuelle # feuille de travail courante
##            if actuelle.sauvegarde["export"]:
##                dir, fichier = os.path.split(actuelle.sauvegarde["export"]) # on exporte sous le même nom qu'avant par défaut
##            elif actuelle.sauvegarde["nom"]:
##                fichier = actuelle.sauvegarde["nom"] # le nom par defaut est le nom de sauvegarde
##                dir = actuelle.sauvegarde["repertoire"]
##            else:
##                if param.rep_export is None:
##                    dir = param.repertoire
##                else:
##                    dir = param.rep_export

            filename = self.parent.parent.ExportFile(exporter = False)
            # ne pas faire l'export, mais récupérer juste le nom

            if filename:
                self.exporter(nom = filename, zone = (x0, x1, y0, y1))
                actuelle.sauvegarde["export"] = filename

        menu = QMenu(self)
        menu.setTitle(u"Zone sélectionnée")
        action = menu.addAction(u'Exporter la zone comme image')
        action.triggered.connect(exporte)

        if objets_dans_la_zone:
            action = menu.addAction(u"Supprimer les objets")
            def supprimer():
                noms = ','.join(obj.nom for obj in objets_dans_la_zone)
                self.executer(u'supprimer(%s)' %noms)
            action.triggered.connect(supprimer)

            action = menu.addAction(u'Masquer les objets')
            def masquer():
                with self.geler_affichage(actualiser=True):
                    for objet in objets_dans_la_zone:
                        self.executer(u"%s.cacher()" % objet.nom)
            action.triggered.connect(masquer)

            action = menu.addAction(u'Éditer les objets')
            def editer():
                win = Proprietes(self, objets_dans_la_zone)
                win.show()
            action.triggered.connect(editer)

        ##app.processEvents()
        menu.exec_(QCursor.pos())

        with self.geler_affichage(): # ?
            self.selection_en_gras()
        self.rafraichir_affichage()
Example #35
0
class ProcessingPlugin:
    def __init__(self, iface):
        self.iface = iface

    def initGui(self):
        Processing.initialize()

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

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

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

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

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

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

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

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

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

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

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

        self.iface.unregisterMainWindowAction(self.commanderAction)

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

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

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

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

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

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

    def tr(self, message):
        return QCoreApplication.translate('ProcessingPlugin', message)
Example #36
0
    def addMyActions(self):
        self.addMyAction(self, u'全部', 'CLASS_6_0')
        self.addMyAction(self, u'开盘=收盘=最高=最低', 'CLASS_0_0')

        subMenu = QMenu(self)
        subMenu.setTitle(u'振幅分档')
        self.addMyAction(subMenu, u'振幅 < 2%', 'CLASS_1_0')
        self.addMyAction(subMenu, u'振幅 = 0', 'CLASS_1_1')
        self.addMenu(subMenu)
        
        subMenu = QMenu(self)
        subMenu.setTitle(u'涨幅分档')
        self.addMyAction(subMenu, u'卖价 = 0, 涨幅 > 4.9%', 'CLASS_2_0')
        self.addMyAction(subMenu, u'买价 = 0, 涨幅 < -4.9%', 'CLASS_2_1')
        self.addMenu(subMenu)
        
        subMenu = QMenu(self)
        subMenu.setTitle(u'总金额分档')
        self.addMyAction(subMenu, u'总金额 < 0.9999亿', 'CLASS_3_0')
        self.addMyAction(subMenu, u'总金额 1 ~ 1.9999亿', 'CLASS_3_1')
        self.addMyAction(subMenu, u'总金额 2 ~ 4.9999亿', 'CLASS_3_2')
        self.addMyAction(subMenu, u'总金额 >= 5亿', 'CLASS_3_3')
        self.addMyAction(subMenu, u'总金额 >  9亿', 'CLASS_3_4')
        self.addMyAction(subMenu, u'总金额 >  15亿', 'CLASS_3_5')
        self.addMyAction(subMenu, u'总金额 >  20亿', 'CLASS_3_6')
        self.addMyAction(subMenu, u'总金额 >  25亿', 'CLASS_3_7')
        self.addMyAction(subMenu, u'总金额 >  30亿', 'CLASS_3_8')
        self.addMyAction(subMenu, u'总金额 >  40亿', 'CLASS_3_9')
        self.addMenu(subMenu)
        
        subMenu = QMenu(self)
        subMenu.setTitle(u'换手率分档')
        self.addMyAction(subMenu, u'换手率 < 0.9999%', 'CLASS_4_0')
        self.addMyAction(subMenu, u'换手率 1% ~ 2.9999%', 'CLASS_4_1')
        self.addMyAction(subMenu, u'换手率 3% ~ 4.9999%', 'CLASS_4_2')
        self.addMyAction(subMenu, u'换手率 5% ~ 6.9999%', 'CLASS_4_3')
        self.addMyAction(subMenu, u'换手率 7% ~ 9.9999%', 'CLASS_4_4')
        self.addMyAction(subMenu, u'换手率 >= 10%', 'CLASS_4_5')
        self.addMyAction(subMenu, u'换手率 > 15%', 'CLASS_4_6')
        self.addMyAction(subMenu, u'换手率 > 20%', 'CLASS_4_7')
        self.addMyAction(subMenu, u'换手率 > 25%', 'CLASS_4_8')
        self.addMyAction(subMenu, u'换手率 > 30%', 'CLASS_4_9')
        self.addMyAction(subMenu, u'换手率 > 35%', 'CLASS_4_10')
        self.addMyAction(subMenu, u'换手率 > 40%', 'CLASS_4_11')
        self.addMyAction(subMenu, u'换手率 > 45%', 'CLASS_4_12')
        self.addMyAction(subMenu, u'换手率 > 50%', 'CLASS_4_13')
        self.addMyAction(subMenu, u'换手率 > 60%', 'CLASS_4_14')
        self.addMenu(subMenu)
        
        
        subMenu = QMenu(self)
        subMenu.setTitle(u'时间分档')
        for year in range(2008, 2015):
            tmpCount = 0
            ssubMenu = QMenu(self)
            ssubMenu.setTitle(str(year))
            sssubMenu = QMenu(ssubMenu)
            sssubMenu.setTitle(u'季度分档')
            for i in range(1, 5):
                self.addMyAction(sssubMenu, u'第 %d 季度' %i, 'CLASS_5_%d.%d' %(tmpCount, year))
                tmpCount += 1
            ssubMenu.addMenu(sssubMenu)
            sssubMenu = QMenu(ssubMenu)
            sssubMenu.setTitle(u'月份分档')
            for month in range(1, 13):
                self.addMyAction(sssubMenu, u'%d 月' %month, 'CLASS_5_%d.%d' %(tmpCount, year))
                tmpCount += 1
            ssubMenu.addMenu(sssubMenu)
            subMenu.addMenu(ssubMenu)
        self.addMenu(subMenu)
Example #37
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 #38
0
    def doMenu(self, pos):
        index = self.indexAt(pos)

        if not index.isValid():
            return

        item = self.itemAt(pos)
        menu = QMenu(self)
        action_Folder = QAction(Icons.newfolder,'New Folder', self)
        action_Folder.triggered.connect(lambda:self.newFolder(item))
        action_File = QAction(Icons.new_file,'New File', self)
        action_File.triggered.connect(lambda:self.newFile(item))
        action_Open = QAction('Open', self)
        action_Open.triggered.connect(lambda:self.openProject(item))
        action_Close = QAction('Close', self)
        action_Close.triggered.connect(lambda:self.closeProject(item))
        
        action_OpenFile = QAction(Icons.open,'Open', self)
        action_OpenFile.triggered.connect(lambda:self.openFile(item))
        action_RunFile = QAction(Icons.go,'Python Run', self)
        action_RunFile.triggered.connect(lambda:self.runFile(item))
        action_SendFile = QAction(Icons.file_obj,'Send to SDcard', self)
        action_SendFile.triggered.connect(lambda:self.sendFile(item))
        action_Copy = QAction(Icons.file_obj,'Copy', self)
        action_Copy.triggered.connect(lambda:self.copy(item))
        action_Paste = QAction(Icons.paste_edit,'Paste', self)
        action_Paste.triggered.connect(lambda:self.paste(item))
        if(self.clipboard == []):
            action_Paste.setEnabled(False)
            
        action_RefreshProject = QAction(Icons.refresh_tab,'Refresh', self)
        action_RefreshProject.triggered.connect(lambda:self.refreshProject(item))
        action_RemoveProject = QAction('Remove', self)
        action_RemoveProject.triggered.connect(lambda:self.removeProject(item))
        action_RenameProject = QAction('Rename...', self)
        action_RenameProject.triggered.connect(lambda:self.renameProject(item))
        action_RenameDir = QAction('Rename...', self)
        action_RenameDir.triggered.connect(lambda:self.renameDir(item))
        action_RenameFile = QAction('Rename...', self)
        action_RenameFile.triggered.connect(lambda:self.renameFile(item))
        action_DeleteFile = QAction(Icons.trash,'Delete', self)
        action_DeleteFile.triggered.connect(lambda:self.deleteFile(item))
        action_DeleteDir = QAction(Icons.trash,'Delete', self)
        action_DeleteDir.triggered.connect(lambda:self.deleteDir(item))
        action_DeleteProject = QAction(Icons.trash,'Delete', self)
        action_DeleteProject.triggered.connect(lambda:self.deleteProject(item))
        
        action_CreateProject = QAction('Create Android', self)
        action_CreateProject.triggered.connect(lambda:self.create(item))
        action_BuildProject = QAction('Build', self)
        action_BuildProject.triggered.connect(lambda:self.build(item))
        action_BuildRunProject = QAction('Build and Install', self)
        action_BuildRunProject.triggered.connect(lambda:self.buildRun(item))
        action_CleanProject = QAction('Clean', self)
        action_CleanProject.triggered.connect(lambda:self.clean(item))
        action_RunProject = QAction('Install', self)
        action_RunProject.triggered.connect(lambda:self.run(item))
        if(item.isProject()):
            if not(item.isClosed()):
                menu.addAction(action_Folder)
                menu.addAction(action_File)
                menu.addSeparator()
                menu.addAction(action_CreateProject)
                menu.addAction(action_BuildProject)
                menu.addAction(action_BuildRunProject)
                menu.addAction(action_RunProject)
                menu.addAction(action_CleanProject)
                menu.addSeparator()
                menu.addAction(action_RenameProject)
                menu.addAction(action_RemoveProject)
                menu.addAction(action_DeleteProject)
                menu.addSeparator()
                menu.addAction(action_RefreshProject)
                menu.addAction(action_Close)
            else:
                menu.addAction(action_Open)
        else:
            if(item.isDir()):
                menu.addAction(action_Folder)
                menu.addAction(action_File)
                menu.addSeparator()
                #menu.addAction(action_Copy)
                menu.addAction(action_Paste)
                menu.addAction(action_RenameDir)
                menu.addAction(action_DeleteDir)      
            else:
                menu1 = QMenu(self)
                menu1.setTitle("Run As")
                menu1.addAction(action_RunFile)
                menu.addMenu(menu1)
                menu.addAction(action_OpenFile)
                menu.addSeparator()
                menu.addAction(action_SendFile)
                menu.addSeparator()
                menu.addAction(action_Copy)
                
                menu.addAction(action_Paste)
                menu.addAction(action_RenameFile)
                menu.addAction(action_DeleteFile)
                
        menu.popup(QCursor.pos())
Example #39
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 #40
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())
Example #41
0
class ProcessingPlugin:

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

    def initGui(self):
        Processing.initialize()

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

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

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

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

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

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

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

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

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

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

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

        self.iface.unregisterMainWindowAction(self.commanderAction)

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

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

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

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

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

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

    def tr(self, message):
        return QCoreApplication.translate('ProcessingPlugin', message)
Example #42
0
 def initStyleMenu(self):
     editStyle = config.readStyle()
     self.action_Style = QAction(Icons.style, 'Style', self) 
     men = QMenu(self)
     men1 = QMenu()
     self.base = StyleWidget(self,"base",editStyle["base"])
     self.back = StyleWidget(self,"back",editStyle["back"])
     self.caret = StyleWidget(self,"caret",editStyle["caret"])
     self.margin = StyleWidget(self,"margin",editStyle["margin"])
     self.marker = StyleWidget(self,"marker",editStyle["marker"])
     self.comment = StyleWidget(self,"comment",editStyle["comment"])
     self.number = StyleWidget(self,"number",editStyle["number"])
     self.keyword = StyleWidget(self,"keyword",editStyle["keyword"])
     self.string = StyleWidget(self,"string",editStyle["string"])
     self.operator = StyleWidget(self,"operator",editStyle["operator"])
     self.connect(self.base, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.back, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.caret, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.margin, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.marker, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.comment, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.number, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.keyword, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.string, SIGNAL("colorChange"),self.colorChange)
     self.connect(self.operator, SIGNAL("colorChange"),self.colorChange)
     self.baseMenu = QWidgetAction(men)
     self.baseMenu.setDefaultWidget(self.base)
     self.backMenu = QWidgetAction(men)
     self.backMenu.setDefaultWidget(self.back)
     self.caretMenu = QWidgetAction(men)
     self.caretMenu.setDefaultWidget(self.caret)
     self.marginMenu = QWidgetAction(men)
     self.marginMenu.setDefaultWidget(self.margin)
     self.markerMenu = QWidgetAction(men)
     self.markerMenu.setDefaultWidget(self.marker)
     self.commentMenu = QWidgetAction(men)
     self.commentMenu.setDefaultWidget(self.comment)
     self.numberMenu = QWidgetAction(men)
     self.numberMenu.setDefaultWidget(self.number)
     self.keywordMenu = QWidgetAction(men)
     self.keywordMenu.setDefaultWidget(self.keyword)
     self.stringMenu = QWidgetAction(men)
     self.stringMenu.setDefaultWidget(self.string)
     self.operatorMenu = QWidgetAction(men)
     self.operatorMenu.setDefaultWidget(self.operator)
     self.styleGroup = QActionGroup(self)
     self.styleGroup.setExclusive(True)
     self.styleGroup.selected.connect(self.setColors)
     self.style1 = QAction("All Hallow's Eve",self.styleGroup)
     self.style1.setCheckable(True)
     self.style2 = QAction("Amy",self.styleGroup)
     self.style2.setCheckable(True)
     self.style3 = QAction("Aptana Studio",self.styleGroup)
     self.style3.setCheckable(True)
     self.style4 = QAction("Bespin",self.styleGroup)
     self.style4.setCheckable(True)
     self.style5 = QAction("Blackboard",self.styleGroup)
     self.style5.setCheckable(True)
     self.style6 = QAction("Choco",self.styleGroup)
     self.style6.setCheckable(True)
     self.style7 = QAction("Cobalt",self.styleGroup)
     self.style7.setCheckable(True)
     self.style8 = QAction("Dawn",self.styleGroup)
     self.style8.setCheckable(True)
     self.style9 = QAction("Eclipse",self.styleGroup)
     self.style9.setCheckable(True)
     self.styleGroup.addAction(self.style1)
     self.styleGroup.addAction(self.style2)
     self.styleGroup.addAction(self.style3)
     self.styleGroup.addAction(self.style4)
     self.styleGroup.addAction(self.style5)
     self.styleGroup.addAction(self.style6)
     self.styleGroup.addAction(self.style7)
     self.styleGroup.addAction(self.style8)
     self.styleGroup.addAction(self.style9)
     men1.addAction(self.baseMenu)
     men1.addAction(self.backMenu)
     men1.addAction(self.caretMenu)
     men1.addAction(self.marginMenu)
     men1.addAction(self.markerMenu)
     men1.addAction(self.commentMenu)
     men1.addAction(self.numberMenu)
     men1.addAction(self.keywordMenu)
     men1.addAction(self.stringMenu)
     men1.addAction(self.operatorMenu)
     men1.addSeparator()
     men2 = QMenu(self)
     men2.setTitle("Styles")
     men2.addActions(self.styleGroup.actions())
     men1.addMenu(men2)
     self.action_Style.setMenu(men1)
     self.addAction(self.action_Style)
Example #43
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 #44
0
class GlobalSysTray(object):
    def __init__(self, parent, name, icon):
        object.__init__(self)

        self._app    = None
        self._parent = parent
        self._gtk_running = False
        self._quit_added  = False

        self.act_indexes  = []
        self.sep_indexes  = []
        self.menu_indexes = []

        if TrayEngine == "KDE":
            self.menu = KMenu(parent)
            self.menu.setTitle(name)
            self.tray = KStatusNotifierItem()
            self.tray.setAssociatedWidget(parent)
            self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
            self.tray.setContextMenu(self.menu)
            self.tray.setIconByPixmap(getIcon(icon))
            self.tray.setTitle(name)
            self.tray.setToolTipTitle(" ")
            self.tray.setToolTipIconByPixmap(getIcon(icon))
            # Double-click is managed by KDE

        elif TrayEngine == "AppIndicator":
            self.menu = Gtk.Menu()
            self.tray = AppIndicator.Indicator.new(name, icon, AppIndicator.IndicatorCategory.APPLICATION_STATUS)
            self.tray.set_menu(self.menu)
            # Double-click is not possible with App-Indicators

        elif TrayEngine == "Qt":
            self.menu = QMenu(parent)
            self.tray = QSystemTrayIcon(getIcon(icon))
            self.tray.setContextMenu(self.menu)
            self.tray.setParent(parent)
            self.tray.connect(self.tray, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.qt_systray_clicked)

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

    def addAction(self, act_name_id, act_name_string, is_check=False):
        if TrayEngine == "KDE":
            act_widget = KAction(act_name_string, self.menu)
            act_widget.setCheckable(is_check)
            self.menu.addAction(act_widget)

        elif TrayEngine == "AppIndicator":
            if is_check:
                act_widget = Gtk.CheckMenuItem(act_name_string)
            else:
                act_widget = Gtk.ImageMenuItem(act_name_string)
                act_widget.set_image(None)
            act_widget.show()
            self.menu.append(act_widget)

        elif TrayEngine == "Qt":
            act_widget = QAction(act_name_string, self.menu)
            act_widget.setCheckable(is_check)
            self.menu.addAction(act_widget)

        else:
            act_widget = None

        act_obj = [None, None, None, None]
        act_obj[iActNameId] = act_name_id
        act_obj[iActWidget] = act_widget

        self.act_indexes.append(act_obj)

    def addSeparator(self, sep_name_id):
        if TrayEngine == "KDE":
            sep_widget = self.menu.addSeparator()

        elif TrayEngine == "AppIndicator":
            sep_widget = Gtk.SeparatorMenuItem()
            sep_widget.show()
            self.menu.append(sep_widget)

        elif TrayEngine == "Qt":
            sep_widget = self.menu.addSeparator()

        else:
            sep_widget = None

        sep_obj = [None, None, None]
        sep_obj[iSepNameId] = sep_name_id
        sep_obj[iSepWidget] = sep_widget

        self.sep_indexes.append(sep_obj)

    def addMenu(self, menu_name_id, menu_name_string):
        if TrayEngine == "KDE":
            menu_widget = KMenu(menu_name_string, self.menu)
            self.menu.addMenu(menu_widget)

        elif TrayEngine == "AppIndicator":
            menu_widget = Gtk.MenuItem(menu_name_string)
            menu_parent = Gtk.Menu()
            menu_widget.set_submenu(menu_parent)
            menu_widget.show()
            self.menu.append(menu_widget)

        elif TrayEngine == "Qt":
            menu_widget = QMenu(menu_name_string, self.menu)
            self.menu.addMenu(menu_widget)

        else:
            menu_widget = None

        menu_obj = [None, None, None]
        menu_obj[iMenuNameId] = menu_name_id
        menu_obj[iMenuWidget] = menu_widget

        self.menu_indexes.append(menu_obj)

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

    def addMenuAction(self, menu_name_id, act_name_id, act_name_string, is_check=False):
        i = self.get_menu_index(menu_name_id)
        if i < 0: return

        menu_widget = self.menu_indexes[i][iMenuWidget]

        if TrayEngine == "KDE":
            act_widget = KAction(act_name_string, menu_widget)
            act_widget.setCheckable(is_check)
            menu_widget.addAction(act_widget)

        elif TrayEngine == "AppIndicator":
            menu_widget = menu_widget.get_submenu()
            if is_check:
                act_widget = Gtk.CheckMenuItem(act_name_string)
            else:
                act_widget = Gtk.ImageMenuItem(act_name_string)
                act_widget.set_image(None)
            act_widget.show()
            menu_widget.append(act_widget)

        elif TrayEngine == "Qt":
            act_widget = QAction(act_name_string, menu_widget)
            act_widget.setCheckable(is_check)
            menu_widget.addAction(act_widget)

        else:
            act_widget = None

        act_obj = [None, None, None, None]
        act_obj[iActNameId] = act_name_id
        act_obj[iActWidget] = act_widget
        act_obj[iActParentMenuId] = menu_name_id

        self.act_indexes.append(act_obj)

    def addMenuSeparator(self, menu_name_id, sep_name_id):
        i = self.get_menu_index(menu_name_id)
        if i < 0: return

        menu_widget = self.menu_indexes[i][iMenuWidget]

        if TrayEngine == "KDE":
            sep_widget = menu_widget.addSeparator()

        elif TrayEngine == "AppIndicator":
            menu_widget = menu_widget.get_submenu()
            sep_widget = Gtk.SeparatorMenuItem()
            sep_widget.show()
            menu_widget.append(sep_widget)

        elif TrayEngine == "Qt":
            sep_widget = menu_widget.addSeparator()

        else:
            sep_widget = None

        sep_obj = [None, None, None]
        sep_obj[iSepNameId] = sep_name_id
        sep_obj[iSepWidget] = sep_widget
        sep_obj[iSepParentMenuId] = menu_name_id

        self.sep_indexes.append(sep_obj)

    #def addSubMenu(self, menu_name_id, new_menu_name_id, new_menu_name_string):
        #menu_index = self.get_menu_index(menu_name_id)
        #if menu_index < 0: return
        #menu_widget = self.menu_indexes[menu_index][1]
        ##if TrayEngine == "KDE":
            ##new_menu_widget = KMenu(new_menu_name_string, self.menu)
            ##menu_widget.addMenu(new_menu_widget)
        ##elif TrayEngine == "AppIndicator":
            ##new_menu_widget = Gtk.MenuItem(new_menu_name_string)
            ##new_menu_widget.show()
            ##menu_widget.get_submenu().append(new_menu_widget)
            ##parent_menu_widget = Gtk.Menu()
            ##new_menu_widget.set_submenu(parent_menu_widget)
        ##else:
        #if (1):
            #new_menu_widget = QMenu(new_menu_name_string, self.menu)
            #menu_widget.addMenu(new_menu_widget)
        #self.menu_indexes.append([new_menu_name_id, new_menu_widget, menu_name_id])

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

    def connect(self, act_name_id, act_func):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            self.tray.connect(act_widget, SIGNAL("triggered()"), act_func)

        elif TrayEngine == "AppIndicator":
            act_widget.connect("activate", self.gtk_call_func, act_name_id)

        elif TrayEngine == "Qt":
            self.tray.connect(act_widget, SIGNAL("triggered()"), act_func)

        self.act_indexes[i][iActFunc] = act_func

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

    #def setActionChecked(self, act_name_id, yesno):
        #index = self.get_act_index(act_name_id)
        #if index < 0: return
        #act_widget = self.act_indexes[index][1]
        ##if TrayEngine == "KDE":
            ##act_widget.setChecked(yesno)
        ##elif TrayEngine == "AppIndicator":
            ##if type(act_widget) != Gtk.CheckMenuItem:
                ##return # Cannot continue
            ##act_widget.set_active(yesno)
        ##else:
        #if (1):
            #act_widget.setChecked(yesno)

    def setActionEnabled(self, act_name_id, yesno):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            act_widget.setEnabled(yesno)

        elif TrayEngine == "AppIndicator":
            act_widget.set_sensitive(yesno)

        elif TrayEngine == "Qt":
            act_widget.setEnabled(yesno)

    def setActionIcon(self, act_name_id, icon):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            act_widget.setIcon(KIcon(icon))

        elif TrayEngine == "AppIndicator":
            if not isinstance(act_widget, Gtk.ImageMenuItem):
                # Cannot use icons here
                return

            act_widget.set_image(Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.MENU))
            #act_widget.set_always_show_image(True)

        elif TrayEngine == "Qt":
            act_widget.setIcon(getIcon(icon))

    def setActionText(self, act_name_id, text):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            act_widget.setText(text)

        elif TrayEngine == "AppIndicator":
            if isinstance(act_widget, Gtk.ImageMenuItem):
                # Fix icon reset
                last_icon = act_widget.get_image()
                act_widget.set_label(text)
                act_widget.set_image(last_icon)
            else:
                act_widget.set_label(text)

        elif TrayEngine == "Qt":
            act_widget.setText(text)

    def setIcon(self, icon):
        if TrayEngine == "KDE":
            self.tray.setIconByPixmap(getIcon(icon))
            #self.tray.setToolTipIconByPixmap(getIcon(icon))

        elif TrayEngine == "AppIndicator":
            self.tray.set_icon(icon)

        elif TrayEngine == "Qt":
            self.tray.setIcon(getIcon(icon))

    def setToolTip(self, text):
        if TrayEngine == "KDE":
            self.tray.setToolTipSubTitle(text)

        elif TrayEngine == "AppIndicator":
            # ToolTips are disabled in App-Indicators by design
            pass

        elif TrayEngine == "Qt":
            self.tray.setToolTip(text)

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

    #def removeAction(self, act_name_id):
        #index = self.get_act_index(act_name_id)
        #if index < 0: return
        #act_widget = self.act_indexes[index][1]
        #parent_menu_widget = self.get_parent_menu_widget(self.act_indexes[index][2])
        ##if TrayEngine == "KDE":
            ##parent_menu_widget.removeAction(act_widget)
        ##elif TrayEngine == "AppIndicator":
            ##act_widget.hide()
            ##parent_menu_widget.remove(act_widget)
        ##else:
        #if (1):
            #parent_menu_widget.removeAction(act_widget)
        #self.act_indexes.pop(index)

    #def removeSeparator(self, sep_name_id):
        #index = self.get_sep_index(sep_name_id)
        #if index < 0: return
        #sep_widget = self.sep_indexes[index][1]
        #parent_menu_widget = self.get_parent_menu_widget(self.sep_indexes[index][2])
        ##if TrayEngine == "KDE":
            ##parent_menu_widget.removeAction(sep_widget)
        ##elif TrayEngine == "AppIndicator":
            ##sep_widget.hide()
            ##parent_menu_widget.remove(sep_widget)
        ##else:
        #if (1):
            #parent_menu_widget.removeAction(sep_widget)
        #self.sep_indexes.pop(index)

    #def removeMenu(self, menu_name_id):
        #index = self.get_menu_index(menu_name_id)
        #if index < 0: return
        #menu_widget = self.menu_indexes[index][1]
        #parent_menu_widget = self.get_parent_menu_widget(self.menu_indexes[index][2])
        ##if TrayEngine == "KDE":
            ##parent_menu_widget.removeAction(menu_widget.menuAction())
        ##elif TrayEngine == "AppIndicator":
            ##menu_widget.hide()
            ##parent_menu_widget.remove(menu_widget.get_submenu())
        ##else:
        #if (1):
            #parent_menu_widget.removeAction(menu_widget.menuAction())
        #self.remove_actions_by_menu_name_id(menu_name_id)
        #self.remove_separators_by_menu_name_id(menu_name_id)
        #self.remove_submenus_by_menu_name_id(menu_name_id)

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

    #def clearAll(self):
        ##if TrayEngine == "KDE":
            ##self.menu.clear()
        ##elif TrayEngine == "AppIndicator":
            ##for child in self.menu.get_children():
                ##self.menu.remove(child)
        ##else:
        #if (1):
            #self.menu.clear()

        #self.act_indexes = []
        #self.sep_indexes = []
        #self.menu_indexes = []

    #def clearMenu(self, menu_name_id):
        #menu_index = self.get_menu_index(menu_name_id)
        #if menu_index < 0: return
        #menu_widget = self.menu_indexes[menu_index][1]
        ##if TrayEngine == "KDE":
            ##menu_widget.clear()
        ##elif TrayEngine == "AppIndicator":
            ##for child in menu_widget.get_submenu().get_children():
                ##menu_widget.get_submenu().remove(child)
        ##else:
        #if (1):
            #menu_widget.clear()
        #list_of_submenus = [menu_name_id]
        #for x in range(0, 10): # 10x level deep, should cover all cases...
            #for this_menu_name_id, menu_widget, parent_menu_id in self.menu_indexes:
                #if parent_menu_id in list_of_submenus and this_menu_name_id not in list_of_submenus:
                    #list_of_submenus.append(this_menu_name_id)
        #for this_menu_name_id in list_of_submenus:
            #self.remove_actions_by_menu_name_id(this_menu_name_id)
            #self.remove_separators_by_menu_name_id(this_menu_name_id)
            #self.remove_submenus_by_menu_name_id(this_menu_name_id)

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

    def getTrayEngine(self):
        return TrayEngine

    def isTrayAvailable(self):
        if TrayEngine in ("KDE", "Qt"):
            return QSystemTrayIcon.isSystemTrayAvailable()
        elif TrayEngine == "AppIndicator":
            # Ubuntu/Unity always has a systray
            return True
        else:
            return False

    def handleQtCloseEvent(self, event):
        if self.isTrayAvailable() and self._parent.isVisible():
            event.accept()
            self.__hideShowCall()
            return

        self.close()
        QMainWindow.closeEvent(self._parent, event)

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

    def show(self):
        if not self._quit_added:
            self._quit_added = True

            if TrayEngine != "KDE":
                self.addSeparator("_quit")
                self.addAction("show", self._parent.tr("Minimize"))
                self.addAction("quit", self._parent.tr("Quit"))
                self.setActionIcon("quit", "application-exit")
                self.connect("show", self.__hideShowCall)
                self.connect("quit", self.__quitCall)

        if TrayEngine == "KDE":
            self.tray.setStatus(KStatusNotifierItem.Active)
        elif TrayEngine == "AppIndicator":
            self.tray.set_status(AppIndicator.IndicatorStatus.ACTIVE)
        elif TrayEngine == "Qt":
            self.tray.show()

    def hide(self):
        if TrayEngine == "KDE":
            self.tray.setStatus(KStatusNotifierItem.Passive)
        elif TrayEngine == "AppIndicator":
            self.tray.set_status(AppIndicator.IndicatorStatus.PASSIVE)
        elif TrayEngine == "Qt":
            self.tray.hide()

    def close(self):
        if TrayEngine == "KDE":
            self.menu.close()
        elif TrayEngine == "AppIndicator":
            if self._gtk_running:
                self._gtk_running = False
                Gtk.main_quit()
        elif TrayEngine == "Qt":
            self.menu.close()

    def exec_(self, app):
        self._app = app
        if TrayEngine == "AppIndicator":
            self._gtk_running = True
            return Gtk.main()
        else:
            return app.exec_()

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

    def get_act_index(self, act_name_id):
        for i in range(len(self.act_indexes)):
            if self.act_indexes[i][iActNameId] == act_name_id:
                return i
        else:
            print("systray.py - Failed to get action index for %s" % act_name_id)
            return -1

    def get_sep_index(self, sep_name_id):
        for i in range(len(self.sep_indexes)):
            if self.sep_indexes[i][iSepNameId] == sep_name_id:
                return i
        else:
            print("systray.py - Failed to get separator index for %s" % sep_name_id)
            return -1

    def get_menu_index(self, menu_name_id):
        for i in range(len(self.menu_indexes)):
            if self.menu_indexes[i][iMenuNameId] == menu_name_id:
                return i
        else:
            print("systray.py - Failed to get menu index for %s" % menu_name_id)
            return -1

    #def get_parent_menu_widget(self, parent_menu_id):
        #if parent_menu_id != None:
            #menu_index = self.get_menu_index(parent_menu_id)
            #if menu_index >= 0:
                #return self.menu_indexes[menu_index][1]
            #else:
                #print("systray.py::Failed to get parent Menu widget for", parent_menu_id)
                #return None
        #else:
            #return self.menu

    #def remove_actions_by_menu_name_id(self, menu_name_id):
        #h = 0
        #for i in range(len(self.act_indexes)):
            #act_name_id, act_widget, parent_menu_id, act_func = self.act_indexes[i - h]
            #if parent_menu_id == menu_name_id:
                #self.act_indexes.pop(i - h)
                #h += 1

    #def remove_separators_by_menu_name_id(self, menu_name_id):
        #h = 0
        #for i in range(len(self.sep_indexes)):
            #sep_name_id, sep_widget, parent_menu_id = self.sep_indexes[i - h]
            #if parent_menu_id == menu_name_id:
                #self.sep_indexes.pop(i - h)
                #h += 1

    #def remove_submenus_by_menu_name_id(self, submenu_name_id):
        #h = 0
        #for i in range(len(self.menu_indexes)):
            #menu_name_id, menu_widget, parent_menu_id = self.menu_indexes[i - h]
            #if parent_menu_id == submenu_name_id:
                #self.menu_indexes.pop(i - h)
                #h += 1

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

    def gtk_call_func(self, gtkmenu, act_name_id):
        i = self.get_act_index(act_name_id)
        if i < 0: return None

        return self.act_indexes[i][iActFunc]

    def qt_systray_clicked(self, reason):
        if reason in (QSystemTrayIcon.DoubleClick, QSystemTrayIcon.Trigger):
            self.__hideShowCall()

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

    def __hideShowCall(self):
        if self._parent.isVisible():
            self.setActionText("show", self._parent.tr("Restore"))
            self._parent.hide()

            if self._app:
                self._app.setQuitOnLastWindowClosed(False)

        else:
            self.setActionText("show", self._parent.tr("Minimize"))

            if self._parent.isMaximized():
                self._parent.showMaximized()
            else:
                self._parent.showNormal()

            if self._app:
                self._app.setQuitOnLastWindowClosed(True)

            QTimer.singleShot(500, self.__raiseWindow)

    def __quitCall(self):
        if self._app:
            self._app.setQuitOnLastWindowClosed(True)

        self._parent.hide()
        self._parent.close()

    def __raiseWindow(self):
        self._parent.activateWindow()
        self._parent.raise_()
Example #45
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()
class NgiiDataUtils:
    """QGIS Plugin Implementation."""
    mainMenuTitle = u"NGII"
    mainMenu = None
    menuBar = None

    menuActions = []
    toolbarActions = []

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

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'NgiiDataUtils_{}.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.pluginIsActive = False
        self.dockwidget = None

    def initGui(self):
        # 메뉴와 툴바에 추가할 항목 정의
        menuIcons = ['icon.png']
        menuTexts = [u'국토지리정보원 공간정보 중첩 검사']
        menuActions = [self.togglePanel]

        assert (len(menuIcons) == len(menuTexts))
        assert (len(menuTexts) == len(menuActions))

        # 기존 NGII 메뉴가 있으면 재사용. 없으면 추가
        self.addNgiiMenu(menuIcons, menuTexts, menuActions)
        # self.togglePanel()

    def addNgiiMenu(self, menuIcons, menuTexts, menuActions):
        # https://gis.stackexchange.com/questions/227876/finding-name-of-qgis-toolbar-in-python
        qgisMenuBar = self.iface.mainWindow().menuBar()

        # 이미 NGII 메뉴 있는지 찾아보기
        ngiiMenu = None
        for action in qgisMenuBar.actions():
            if action.text() == self.mainMenuTitle:
                ngiiMenu = action.menu()
                break

        # 없음 만들고 있음 그냥 사용
        if ngiiMenu is None:
            self.mainMenu = QMenu(self.iface.mainWindow())
            self.mainMenu.setTitle(self.mainMenuTitle)
            qgisMenuBar.insertMenu(
                self.iface.firstRightStandardMenu().menuAction(),
                self.mainMenu)
        else:
            self.mainMenu = ngiiMenu

        # 이미 NGII 툴바 있는지 찾아보기
        ngiiToolbar = None
        for toolbar in self.iface.mainWindow().findChildren(QToolBar):
            # if toolbar.objectName() == self.mainMenuTitle:
            if toolbar.windowTitle() == self.mainMenuTitle:
                ngiiToolbar = toolbar
                break

        # 없음 만들고 있음 그냥 사용
        if ngiiToolbar is None:
            self.toolbar = self.iface.addToolBar(self.mainMenuTitle)
            self.toolbar.setObjectName(self.mainMenuTitle)
        else:
            self.toolbar = ngiiToolbar

        # 세부 메뉴, 버튼 추가
        self.menuActions = []
        self.toolbarActions = []
        for i in range(0, len(menuTexts)):
            icon = QIcon(
                os.path.join(os.path.dirname(__file__), 'icons', menuIcons[i]))
            text = menuTexts[i]
            action = QAction(icon, text, self.iface.mainWindow())
            self.mainMenu.addAction(action)
            action.triggered.connect(menuActions[i])
            button = self.toolbar.addAction(icon, text, menuActions[i])

            self.menuActions.append(action)
            self.toolbarActions.append(button)

    def removeNgiiMenu(self):
        if self.toolbar is not None:
            # 내가 등록한 툴바 아이템 제거
            for action in self.toolbarActions:
                self.toolbar.removeAction(action)
            # 더이상 항목이 없으면 부모 제거
            if len(self.toolbar.actions()) == 0:
                self.toolbar.deleteLater()

        if self.mainMenu is not None:
            for action in self.menuActions:
                self.mainMenu.removeAction(action)
            # print len(self.mainMenu.actions())
            if len(self.mainMenu.actions()) == 0:
                self.mainMenu.deleteLater()

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

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

        # print "** CLOSING NgiiDataUtils"

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

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

        self.pluginIsActive = False

    def unload(self):
        if self.dockwidget:
            self.iface.removeDockWidget(self.dockwidget)
        self.removeNgiiMenu()

    #--------------------------------------------------------------------------
    def togglePanel(self):
        if not self.pluginIsActive:
            self.pluginIsActive = True

            # print "** STARTING NgiiDataUtils"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = NgiiDataUtilsDockWidget(self.iface)

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

            # show the dockwidget
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
            # 좌우로 붙게 수정
            self.dockwidget.setAllowedAreas(Qt.LeftDockWidgetArea
                                            | Qt.RightDockWidgetArea)

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

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

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

        self.profilesMenu.addSeparator()

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

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

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

        self.showHelpAction = QAction(self.tr('Help'), self.iface.mainWindow())
        self.showHelpAction.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.showHelpAction.setObjectName('mProfilesPluginShowHelp')
        self.showHelpAction.triggered.connect(self.showHelp)
        self.profilesMenu.addAction(self.showHelpAction)
    def createMenu(self):
        self.categories = self.config.get_categories()
        self.category_lists = self.config.get_category_lists()
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

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

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

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

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

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

        menu_bar = self.iface.mainWindow().menuBar()
        menu_bar.insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.menu
        )
Example #49
0
class ProcessingManager:
    """ Processing plugin
    """
    def __init__(self, iface):
        self._iface = iface
        self.panel = None
        self.settings = None
        self.aboutDialog = None
        self.workflowBuilder = None
        
    def initGui(self):
        from PyQt4.QtCore import QObject, SIGNAL
        from PyQt4.QtGui import QMenu
        self.menu = QMenu()
        self.menu.setTitle(self.menu.tr("&Processing", "Processing"))

        # We only generate the panel & populate the menu when needed,
        # to increase our chances that the framework has been loaded.
        QObject.connect(self.menu, SIGNAL("aboutToShow()"),
            self.populateMenu)
        
        menuBar = self._iface.mainWindow().menuBar()   
        menuBar.insertMenu(menuBar.actions()[-1], self.menu)

    def populateMenu(self):
        from panel import Panel
        from PyQt4.QtCore import QObject, SIGNAL
        from PyQt4.QtGui import QAction
        
        if not self.panel:
            self.panel = Panel(self._iface)
            self.panel.setVisible(False)
            self.panelAction = self.panel.toggleViewAction()

            self.menu.addAction(self.panelAction)
            
            self.settingsAction = QAction(
                self.menu.tr("&Settings", "Processing"),
                self._iface.mainWindow())
            self.menu.addAction(self.settingsAction)
            QObject.connect(self.settingsAction,
                SIGNAL("triggered()"), self.showSettings)

            self.workflowBuilderAction= QAction(
                self.menu.tr("&Workflow builder", "Processing"),
                self._iface.mainWindow())
            self.menu.addAction(self.workflowBuilderAction)
            QObject.connect(self.workflowBuilderAction,
                SIGNAL("triggered()"), self.showWorkflowBuilder)

            self.aboutAction = QAction(
                self.menu.tr("&About", "Processing"),
                self._iface.mainWindow())
            self.menu.addAction(self.aboutAction)
            QObject.connect(self.aboutAction,
                SIGNAL("triggered()"), self.showAboutDialog)
    
    def unload(self):
        if self.panel:
            self.panel.setVisible(False)
            
    def showSettings(self):
        from settings import Settings
        if not self.settings:
            self.settings = Settings(self._iface.mainWindow())
        self.settings.setVisible(True)
    
    def showAboutDialog(self):
        from aboutdialog import AboutDialog
        if not self.aboutDialog:
            self.aboutDialog = AboutDialog(self._iface.mainWindow())
        self.aboutDialog.setVisible(True)
        
    def showWorkflowBuilder(self):
        from workflowBuilder import WorkflowBuilder
        if not self.workflowBuilder:
            self.workflowBuilder = WorkflowBuilder(self._iface)
        self.workflowBuilder.setVisible(True)
Example #50
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 #51
0
class SurveyingCalculation:
    """SurveyingCalculation 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 (QgsInterface)
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QDir().cleanPath(QFileInfo(__file__).absolutePath())
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        print locale
        locale_path = QDir.cleanPath(self.plugin_dir + QDir.separator() +
                                     'i18n' + QDir.separator() +
                                     '{}.qm'.format(locale))
        print locale_path
        if QFileInfo(locale_path).exists():
            print "exists"
            self.translator = QTranslator()
            self.translator.load(locale_path)

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

        # init result log
        log_path_2 = QSettings().value("SurveyingCalculation/log_path",
                                       config.log_path)

        if len(log_path_2) > 0:
            log_path = log_path_2
        else:
            log_path = QDir.cleanPath(self.plugin_dir + QDir.separator() +
                                      'log' + QDir.separator() + 'log.txt')
        self.log = ResultLog(log_path)

        self.newp_dlg = NewPointDialog()
        self.single_dlg = SingleDialog(self.log)
        self.traverse_dlg = TraverseDialog(self.log)
        self.network_dlg = NetworkDialog(self.log)
        self.transformation_dlg = TransformationDialog(self.log)
        self.plotbytemplate_dlg = BatchPlottingDialog(self.iface, False)
        self.batchplotting_dlg = BatchPlottingDialog(self.iface, True)

        # Declare instance attributes

    # 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 (str, QString)
    #    :returns: translated version of message (QString)
    #    """
    # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
    #return QCoreApplication.translate('SurveyingCalculation', message)
    #    return tr(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 (str)
        :param text: text that should be shown in menu items for this action (str)
        :param callback: function to be called when the action is triggered (function)
        :param enabled_flag: a flag indicating if the action should be enabled by default (bool). Defaults to True.
        :param add_to_menu: flag indicating whether the action should also be added to the menu (bool). Defaults to True.
        :param add_to_toolbar: flag indicating whether the action should also be added to the toolbar (bool). Defaults to True.
        :param status_tip: optional text to show in a popup when mouse pointer hovers over the action (str)
        :param parent: parent widget for the new action (QWidget). Defaults None.
        :param whats_this: optional text to show in the status bar when the mouse pointer hovers over the action (str)
        :returns: the action that was created (Qaction). Note that the action is also added to self.actions list.
        """
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

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

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

        if add_to_toolbar:
            self.toolbar.addAction(action)

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

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

        icon_path = ':/plugins/SurveyingCalculation/icon.png'

        icon_dir = QDir.cleanPath(self.plugin_dir + QDir.separator() + 'icons')
        # build menu
        self.actions = []
        self.menu = QMenu()
        self.menu.setTitle(tr(u'&SurveyingCalculation'))
        self.sc_coord = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('new_coord.png')),
            tr("New coordinate list ..."), self.iface.mainWindow())
        self.sc_fb = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('new_fb.png')),
            tr("New fieldbook ..."), self.iface.mainWindow())
        self.sc_load = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('import_fieldbook.png')),
            tr("Import fieldbook ..."), self.iface.mainWindow())
        self.sc_addp = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('addp.png')),
            tr("Add new point ..."), self.iface.mainWindow())
        self.sc_calc = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('single_calc.png')),
            tr("Single point calculations ..."), self.iface.mainWindow())
        self.sc_trav = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('traverse_calc.png')),
            tr("Traverse calculations ..."), self.iface.mainWindow())
        self.sc_netw = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('network_calc.png')),
            tr("Network adjustment ..."), self.iface.mainWindow())
        self.sc_tran = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('coord_calc.png')),
            tr("Coordinate transformation ..."), self.iface.mainWindow())
        self.sc_pdiv = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('poly_div.png')),
            tr("Polygon division ..."), self.iface.mainWindow())
        self.sc_plot = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('plot.png')),
            tr("Plot by template ..."), self.iface.mainWindow())
        self.sc_batchplot = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('batch_plot.png')),
            tr("Batch plotting ..."), self.iface.mainWindow())
        self.sc_settings = QAction(tr("Settings ..."), self.iface.mainWindow())
        self.sc_help = QAction(tr("Help"), self.iface.mainWindow())
        self.sc_about = QAction(tr("About"), self.iface.mainWindow())
        self.menu.addActions([
            self.sc_coord, self.sc_fb, self.sc_load, self.sc_addp,
            self.sc_calc, self.sc_trav, self.sc_netw, self.sc_tran,
            self.sc_plot, self.sc_batchplot, self.sc_settings, self.sc_help,
            self.sc_about
        ])
        self.menu.insertSeparator(self.sc_calc)
        self.menu.insertSeparator(self.sc_plot)
        self.menu.insertSeparator(self.sc_settings)
        self.menu.insertSeparator(self.sc_help)
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()
        lastAction = actions[len(actions) - 1]
        menu_bar.insertMenu(lastAction, self.menu)

        self.sc_coord.triggered.connect(self.create_coordlist)
        self.sc_fb.triggered.connect(self.create_fb)
        self.sc_load.triggered.connect(self.load_fieldbook)
        self.sc_addp.triggered.connect(self.addp)
        self.sc_calc.triggered.connect(self.calculations)
        self.sc_trav.triggered.connect(self.traverses)
        self.sc_netw.triggered.connect(self.networks)
        self.sc_tran.triggered.connect(self.transformation)
        self.sc_pdiv.setCheckable(True)
        self.tool_pdiv = LineMapTool(self.iface)
        self.tool_pdiv.setAction(self.sc_pdiv)
        self.sc_pdiv.triggered.connect(self.polygon_division)
        self.sc_plot.triggered.connect(self.plot_by_temp)
        self.sc_batchplot.triggered.connect(self.batch_plotting)
        self.sc_settings.triggered.connect(self.settings)
        self.sc_about.triggered.connect(self.about)
        self.sc_help.triggered.connect(self.help)

        # add icons to toolbar
        self.toolbar = self.iface.addToolBar(u'SurveyingCalculation')
        self.toolbar.setObjectName(u'SurveyingCalculation')
        self.toolbar.addActions([
            self.sc_load, self.sc_addp, self.sc_calc, self.sc_trav,
            self.sc_netw, self.sc_tran, self.sc_pdiv, self.sc_plot,
            self.sc_batchplot
        ])
        self.toolbar.insertSeparator(self.sc_calc)
        self.toolbar.insertSeparator(self.sc_plot)

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

    def create_coordlist(self):
        """ Create a new coordinate list from template and add to layer list. Layer/file name changed to start with 'coord\_' if neccessary.
        """
        ofname = QFileDialog.getSaveFileName(self.iface.mainWindow(),
                                             tr('QGIS co-ordinate list'),
                                             filter=tr('Shape file (*.shp)'))
        if not ofname:
            return
        if QRegExp('coord_').indexIn(QFileInfo(ofname).baseName()):
            ofname = QDir.cleanPath(
                QFileInfo(ofname).absolutePath() + QDir().separator() +
                'coord_' + QFileInfo(ofname).fileName())
        ofbase = QDir.cleanPath(
            QFileInfo(ofname).absolutePath() + QDir().separator() +
            QFileInfo(ofname).baseName())
        tempbase = QDir.cleanPath(self.plugin_dir + QDir().separator() +
                                  'template' + QDir().separator() +
                                  'coord_template')
        for ext in ['.shp', '.shx', '.dbf']:
            QFile(tempbase + ext).copy(ofbase + ext)
        coord = QgsVectorLayer(ofbase + '.shp',
                               QFileInfo(ofbase).baseName(), "ogr")
        if coord.isValid():
            QgsMapLayerRegistry.instance().addMapLayer(coord)

    def create_fb(self):
        """ Create a new empty fieldbook from template and add to layer list. Layer/file name changed to start with 'fb\_' if neccessary.
        """
        ofname = QFileDialog.getSaveFileName(
            self.iface.mainWindow(),
            tr('New fieldbook'),
            filter=tr('Fieldbook file (*.dbf)'))
        if not ofname:
            return
        if QRegExp('fb_').indexIn(QFileInfo(ofname).baseName()):
            ofname = QDir.cleanPath(
                QFileInfo(ofname).absolutePath() + QDir().separator() + 'fb_' +
                QFileInfo(ofname).fileName())
        ofbase = QDir.cleanPath(
            QFileInfo(ofname).absolutePath() + QDir().separator() +
            QFileInfo(ofname).baseName())
        tempbase = QDir.cleanPath(self.plugin_dir + QDir().separator() +
                                  'template' + QDir().separator() +
                                  'fb_template')
        for ext in ['.dbf']:
            QFile(tempbase + ext).copy(ofbase + ext)
        fb = QgsVectorLayer(ofbase + '.dbf',
                            QFileInfo(ofbase).baseName(), "ogr")
        if fb.isValid():
            QgsMapLayerRegistry.instance().addMapLayer(fb)

    def load_fieldbook(self):
        """ Import an electric fieldbook from file (GSI, JOB/ARE, ...)
        """
        if get_coordlist() is None:
            QMessageBox.warning(
                self.iface.mainWindow(), tr("Warning"),
                tr("No coordinate list is opened, coordinates will be lost from the fieldbook"
                   ))
        homedir = QSettings().value("SurveyingCalculation/homedir",
                                    config.homedir)
        fname = QFileDialog.getOpenFileName(self.iface.mainWindow(), \
            tr('Electric fieldbook'), homedir, \
            filter = tr('Leica GSI (*.gsi);;Geodimeter JOB/ARE (*.job *.are);;Sokkia CRD (*.crd);;SurvCE RW5 (*.rw5);;STONEX DAT (*.dat)'))
        if fname:
            # file selected
            # make a copy of dbf template if not are is loaded
            if QRegExp('\.are$', Qt.CaseInsensitive).indexIn(fname) == -1:
                # ask for table name
                ofname = QFileDialog.getSaveFileName(
                    self.iface.mainWindow(),
                    tr('QGIS fieldbook'),
                    QFileInfo(fname).absolutePath(),
                    filter=tr('DBF file (*.dbf)'))
                if not ofname:
                    return
                # remember last input dir
                QSettings().setValue("SurveyingCalculation/homedir",
                                     QFileInfo(fname).absolutePath())
                QSettings().sync()

                if QRegExp('fb_').indexIn(QFileInfo(ofname).baseName()):
                    ofname = QDir.cleanPath(
                        QFileInfo(ofname).absolutePath() + QDir().separator() +
                        'fb_' + QFileInfo(ofname).fileName())

                tempname = QDir.cleanPath(self.plugin_dir +
                                          QDir().separator() + 'template' +
                                          QDir().separator() +
                                          'fb_template.dbf')
                QFile(tempname).copy(ofname)

                fb_dbf = QgsVectorLayer(ofname,
                                        QFileInfo(ofname).baseName(), "ogr")
                QgsMapLayerRegistry.instance().addMapLayer(fb_dbf)
            if QRegExp('\.gsi$', Qt.CaseInsensitive).indexIn(fname) > -1:
                fb = LeicaGsi(fname)
            elif QRegExp('\.job$', Qt.CaseInsensitive).indexIn(fname) > -1 or \
                QRegExp('\.are$', Qt.CaseInsensitive).indexIn(fname) > -1:
                fb = JobAre(fname)
            elif QRegExp('\.crd$', Qt.CaseInsensitive).indexIn(fname) > -1:
                fb = Sdr(fname)
            elif QRegExp('\.rw5$', Qt.CaseInsensitive).indexIn(fname) > -1:
                fb = SurvCE(fname)
            elif QRegExp('\.dat$', Qt.CaseInsensitive).indexIn(fname) > -1:
                fb = Stonex(fname)
            else:
                QMessageBox.warning(self.iface.mainWindow(),
                                    tr('File warning'),
                                    tr('Unknown fieldbook type'), tr('OK'))
                return
            i = 10  # ordinal number for fieldbook records
            #fb_dbf.startEditing()
            fb.open()
            n_fb = 0  # fieldbook records stored
            n_co = 0  # points stored in coordinate list
            while True:
                # get next observation/station data from fieldbook
                r = fb.parse_next()
                if r is None:
                    break  # end of file
                if 'station' in r:
                    # add row to fieldbook table
                    record = QgsFeature()
                    # add & initialize attributes
                    record.setFields(fb_dbf.pendingFields(), True)
                    j = fb_dbf.dataProvider().fieldNameIndex('id')
                    if j != -1:
                        record.setAttribute(j, i)
                    for key in r:
                        j = fb_dbf.dataProvider().fieldNameIndex(key)
                        if j != -1:
                            record.setAttribute(j, r[key])
                    fb_dbf.dataProvider().addFeatures([record])
                    n_fb += 1
                if 'station_e' in r or 'station_z' in r:
                    # store station coordinates too
                    dimension = 0
                    if 'station_z' in r:
                        dimension += 1
                    else:
                        r['station_z'] = None
                    if 'station_e' in r and 'station_n' in r:
                        dimension += 2
                    else:
                        r['station_e'] = None
                        r['station_n'] = None
                    if not 'pc' in r:
                        r['pc'] = None
                    p = Point(r['point_id'], r['station_e'], r['station_n'],
                              r['station_z'], r['pc'])
                    qp = ScPoint(p)
                    qp.store_coord(dimension)
                    n_co += 1
                if 'e' in r or 'z' in r:
                    # store coordinates too
                    dimension = 0
                    if 'z' in r:
                        dimension += 1
                    else:
                        r['z'] = None
                    if 'e' in r and 'n' in r:
                        dimension += 2
                    else:
                        r['e'] = None
                        r['n'] = None
                    if not 'pc' in r:
                        r['pc'] = None
                    p = Point(r['point_id'], r['e'], r['n'], r['z'], r['pc'])
                    qp = ScPoint(p)
                    qp.store_coord(dimension)
                    n_co += 1
                i += 10
            #fb_dbf.commitChanges()
            if QRegExp('\.are$', Qt.CaseInsensitive).indexIn(fname) == -1:
                if n_fb == 0:  # no observations
                    QgsMapLayerRegistry.instance().removeMapLayer(fb_dbf.id())
                    # remove empty file
                    QFile(ofname).remove()
                    if n_co == 0:  # no coordinates
                        QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),\
                            tr("Neither coordinates nor observations found"))
                    else:
                        QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),\
                            tr("No observations found"))
            self.log.write()
            self.log.write_log(tr("Fieldbook loaded: ") + fname)
            self.log.write("    %d observations, %d coordinates" %
                           (n_fb, n_co))
        return

    def addp(self):
        """ Add point(s) to coordinate list entering coordinates
        """
        if get_coordlist() is None:
            QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),
                                tr("A coordinate list must be opened!"))
            return
        # show the dialog
        self.newp_dlg.show()
        self.newp_dlg.activateWindow()
        # Run the dialog event loop
        result = self.newp_dlg.exec_()

    def calculations(self):
        """ Single point calculations (orientation, intersection,
            resection, freestation)
        """
        # show the dialog
        self.single_dlg.show()
        self.single_dlg.activateWindow()
        # Run the dialog event loop
        result = self.single_dlg.exec_()

    def traverses(self):
        """ Various traverse claculations
        """
        # show the dialog
        self.traverse_dlg.show()
        self.traverse_dlg.activateWindow()
        # Run the dialog event loop
        result = self.traverse_dlg.exec_()

    def networks(self):
        """ Various network adjustments (1D/2D/3D)
        """
        # show the dialog
        self.network_dlg.show()
        self.network_dlg.activateWindow()
        # Run the dialog event loop
        result = self.network_dlg.exec_()

    def transformation(self):
        """ Various coordinate transformations (orthogonal, affine, polynomial)
        """
        # show the dialog
        self.transformation_dlg.show()
        self.transformation_dlg.activateWindow()
        # Run the dialog event loop
        result = self.transformation_dlg.exec_()

    def polygon_division(self):
        """ accept a line from the user to divide the selected polygon on 
            active layer
        """
        al = self.iface.activeLayer()
        if al is None or al.type() != QgsMapLayer.VectorLayer or \
            al.geometryType() != QGis.Polygon:
            QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),
                                tr("Actual layer contains no polygons"))
            return
        if len(al.selectedFeatures()) != 1:
            QMessageBox.warning(
                self.iface.mainWindow(), tr("Warning"),
                tr("Not a single polygon is selected in active layer"))
            return
        self.iface.mapCanvas().setMapTool(self.tool_pdiv)

    def plot_by_temp(self):
        # show the dialog
        self.plotbytemplate_dlg.show()
        self.plotbytemplate_dlg.activateWindow()
        # Run the dialog event loop
        result = self.plotbytemplate_dlg.exec_()

    def batch_plotting(self):
        """ Batch plots selected geometry items using the selected template and scale.
        """
        #check if there are polygon layers in the project
        polygon_layers = get_vector_layers_by_type(QGis.Polygon)
        if polygon_layers is None:
            QMessageBox.warning(
                self.iface.mainWindow(), tr("Warning"),
                tr("This utility needs at least one polygon type layer!"))
            return

        # show the dialog
        self.batchplotting_dlg.show()
        self.batchplotting_dlg.activateWindow()
        # Run the dialog event loop
        result = self.batchplotting_dlg.exec_()

    def settings(self):
        """ Setting of the plugin.
        """
        settings_dlg = PluginSettingsDialog()
        result = settings_dlg.exec_()
        if result == QDialog.Accepted:
            log_path = QSettings().value("SurveyingCalculation/log_path",
                                         config.log_path)
            self.log.set_log_path(log_path)

    def about(self):
        """ About box of the plugin
        """
        QMessageBox.information(
            self.iface.mainWindow(), tr('About'),
            tr('Surveying Calculation Plugin\n\n (c) DigiKom Ltd 2014- http://digikom.hu, mail (at) digikom.hu\nVersion 0.2'
               ))

    def help(self):
        """ Open user's guide of the plugin in the default web browser.
        """
        webbrowser.open(
            "http://www.digikom.hu/SurveyingCalculation/usersguide.html")
Example #52
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)
class Kortforsyningen:
    """QGIS Plugin Implementation."""

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

        self.local_about_file = kf_path + 'about.html'

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

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

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

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

        self.networkManager = QNetworkAccessManager()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            if result:
                webbrowser.open(ABOUT_FILE_URL)

    def unload(self):
        # Remove settings if user not asked to keep them
        if self.settings.value('remember_settings') is False:
            self.settings.setValue('username', '')
            self.settings.setValue('password', '')
        self.clearMenu();
        
    def reloadMenu(self):
        self.clearMenu()
        self.config.load()
        #self.createMenu()
    
    def clearMenu(self):
        # Remove the submenus
        for submenu in self.category_menus:
            if submenu:
                submenu.deleteLater()
        # remove the menu bar item
        if self.menu:
            self.menu.deleteLater()
Example #54
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)
Example #55
0
class RECS:
    """QGIS Plugin Implementation."""

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

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'RECS_HOME_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.initdlg=InitTaskDialog()
        self.selectdlg = SelectTaskDialog()
        self.loginDlg=LogInDialog()
        self.taskMgrDlg=TaskManagerDialog()
        self.taskInfoDlg=taskInfo()
        self.taskFeaturesDlg=taskFeatures()
        #self.loadmapDlg=LoadMapDialog()
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Task')
        self.logIn()
        self.selectTask()
        self.actions = []

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


        # layer.editingStarted.connect(editLayer() )




        # TODO: We are going to let the user set this up in a future iteration
        #self.toolbar = self.iface.addToolBar(u'SelectTask')
        #self.toolbar.setObjectName(u'SelectTask')

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

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Tasks', message)


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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            # self.menu = QMenu( "&Task", self.iface.mainWindow().menuBar() )
            action = self.iface.mainWindow().menuBar().actions()
            lastAction = action[-1]
            self.iface.addPluginToMenu(
                self.menu,
                lastAction)

        self.actions.append(lastAction)

        return action

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

        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        """ Task menu setting """
        self.menu = QMenu(self.iface.mainWindow())
        self.menu.setObjectName("task_menu_object")
        self.menu.setTitle("Task")





        """ Task """
        self.action_tasks = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Tasks", self.iface.mainWindow())
        self.action_tasks.setObjectName("Task_action_object")
        self.action_tasks.setWhatsThis("Task Initialized")
        #QtCore.QObject.connect(self.action_tasks, SIGNAL("triggered()"), self.tasks)

        """ Initializing Task """
        self.action_init_task = QAction(QIcon('::/plugins/RECS/aacadisicon.png'), "Initialize ", self.iface.mainWindow())
        self.action_init_task.setObjectName("Task_action_object")
        self.action_init_task.setWhatsThis("Task Initialize")
        QtCore.QObject.connect(self.action_init_task, SIGNAL("triggered()"), self.initTask)


        """ Select Task """
        self.action_select_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Select Task", self.iface.mainWindow())
        self.action_select_task.setObjectName("Task_Select_object")
        self.action_select_task.setWhatsThis("Select Task")
        QtCore.QObject.connect(self.action_select_task, SIGNAL("triggered()"), self.selectTask)

        """ Reload Task """
        self.action_reload_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Reload Task", self.iface.mainWindow())
        self.action_reload_task.setObjectName("Task_Reload_object")
        self.action_reload_task.setWhatsThis("Reload Task")
        QtCore.QObject.connect(self.action_reload_task, SIGNAL("triggered()"), self.taskManager)

        """ Edit Task """
        self.action_edit_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Edit Task", self.iface.mainWindow())
        self.action_edit_task.setObjectName("Task_Edit_object")
        self.action_edit_task.setWhatsThis("Edit Task")
        QtCore.QObject.connect(self.action_edit_task, SIGNAL("triggered()"), self.editLayer)


        """ Finish Task """
        self.action_finish_task = QAction(QIcon(':/plugins/RECS/aacadisicon.png'), "Finish Task", self.iface.mainWindow())
        self.action_finish_task.setObjectName("Task_Finish_object")
        self.action_finish_task.setWhatsThis("Edit Task")
        QtCore.QObject.connect(self.action_finish_task, SIGNAL("triggered()"), self.finishEditngLayer)


        """ Add action to the menu list """
        #self.menuTask.addAction(self.action_tasks)

        self.menu.addAction(self.action_init_task)
        self.menu.addAction(self.action_select_task)
        self.menu.addAction(self.action_reload_task)
        self.menu.addAction(self.action_edit_task)
        self.menu.addAction(self.action_finish_task)

        """ Add menu to the menubar """
        menubar=self.iface.mainWindow().menuBar()
        menubar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),self.menu)



        """ Add icon to the toolbar """
        #self.iface.addPluginToMenu(u"&load Map", self.action_loadmap)
        #self.iface.addToolBarIcon(self.action_init_task)

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

        layers = self.iface.legendInterface().layers()
        #layer_list = []
        for layer in layers:
           #layer_list.append(layer.name())
           if layer.name() == 'PARCEL':
            self.iface.setActiveLayer(layer)
        self.initdlg.show()
        #layer_list=list(set(layer_list))
        #self.initdlg.comboBox.addItems(layer_list)
        self.initdlg.setFixedSize(self.initdlg.size())
        result = self.initdlg.exec_()
        if result:
            pass
    def selectTask(self):
        self.selectdlg.show()
        self.selectdlg.setFixedSize(self.selectdlg.size())

        self.selectdlg.loadLayer()
        self.selectdlg.populate()
        result = self.selectdlg.exec_()
        if result:
            # self.selectdlg.close()
            pass
    def showTaskInfo(self):
        self.taskInfoDlg.show()
        t_id = self.taskMgrDlg.retTaskID()
        self.taskInfoDlg.getAttribData(t_id)
        #self.taskInfoDlg.populate()
    def taskManager(self):

        if self.taskMgrDlg.isVisible():
            self.taskMgrDlg.loadTaskClicked()
            # self.taskMgrDlg.close()
            # self.apdockwidget.close()
        else:
            self.taskMgrDlg.show()
            self.apdockwidget = QDockWidget("Task Manager", self.iface.mainWindow())
            self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint)
            self.apdockwidget.setWidget(self.taskMgrDlg)
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget)
            self.taskMgrDlg.populate()
            self.taskFeatures()




        # rows = self.taskMgrDlg.taskListTable.rowCount()
        # createdByList=[]
        #
        #
        # for row in range(0,rows):
        #     createdByItems=self.taskMgrDlg.taskListTable.item(row,1)
        #     createdByList.append(createdByItems.text())
        #
        #
        # createdByList=list(set(createdByList))
        # self.taskMgrDlg.createByComboBox.addItems(createdByList)
        # self.taskMgrDlg.createByComboBox.setCurrentIndex(createdByList.index())
        self.menu = QtGui.QMenu()
        #newTask=self.menu.addAction("New Task",self.newTask,"")
        newTask = self.menu.addAction("New Task", self.newTaskEvent)
        loadTask = self.menu.addAction("Load Task", self.loadTaskEvent)
        cancelTask = self.menu.addAction("Cancel Task", self.cancelTaskEvent)
        showTaskArea = self.menu.addAction("Show Task Area", self.showTaskAreaEvent)
        noTask=self.menu.addAction("No Task",self.noTaskEvent)
        showTaskInfo=self.menu.addAction("Show Task Info",self.showTaskInfoEvent)
        updateFeature=self.menu.addAction("Update Features",self.updateFeatureEvent)

        self.taskMgrDlg.taskListTable.addAction(newTask)
        self.taskMgrDlg.taskListTable.addAction(loadTask)
        self.taskMgrDlg.taskListTable.addAction(cancelTask)
        self.taskMgrDlg.taskListTable.addAction(showTaskArea)
        self.taskMgrDlg.taskListTable.addAction(noTask)
        self.taskMgrDlg.taskListTable.addAction(showTaskInfo)
        self.taskMgrDlg.taskListTable.addAction(updateFeature)
        self.taskMgrDlg.taskListTable.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.taskMgrDlg.taskListTable.customContextMenuRequested.connect(self.contextMenuEvent)
        result = self.taskMgrDlg.exec_()
        if result:
            self.taskMgrDlg.populate()
        #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange
    def contextMenuEvent(self, point):
        self.menu.exec_(self.taskMgrDlg.taskListTable.mapToGlobal(point))
    def newTaskEvent(self):
        self.initTask()
    def loadTaskEvent(self):
        self.taskMgrDlg.loadTaskClicked()
        t_id = self.taskMgrDlg.retTaskID()
        self.taskFeaturesDlg.populate(t_id)
    def cancelTaskEvent(self):
        self.taskMgrDlg.cancelTask()
    def showTaskAreaEvent(self):
        self.taskMgrDlg.showTaskAreaClicked()
    def noTaskEvent(self):
        print "noTask Called"
    def showTaskInfoEvent(self):
        self.showTaskInfo()
    def updateFeatureEvent(self):
        print "updateFeature"
    def logIn(self):

        self.loginDlg.show()
        self.loginDlg.setWindowFlags(Qt.FramelessWindowHint)
        result = self.loginDlg.exec_()
        if result:
            pass
    def loadLayer(self):
        self.mlr = None
        # QgsMapLayerRegistry.instance().removeAllMapLayers()
        self.mlr = QgsMapLayerRegistry.instance()
        uri = QgsDataSourceURI()
        uri.setConnection("172.20.0.71", "5432", "ncrprs_db", "postgres", "123456")
        uri.setDataSource("recs", "t_parcel", "parcelgeometry", "")
        vlayer = QgsVectorLayer(uri.uri(), "Parcel", "postgres")
        if vlayer.isValid():
            self.mlr.addMapLayer(vlayer)
        else:
            QMessageBox.information(None, "Unable to Laod Data", "Unable to Load Layers from the Database!")
            return None
    def editLayer(self):
        global taskLayer
        global featCount
        layers = self.iface.legendInterface().layers()
        for layer in layers:
            if layer.name() == 'TaskLayer':
                taskLayer = layer
                taskLayerID=layer.id()
                self.iface.setActiveLayer(taskLayer)
        featCount = taskLayer.featureCount()
        print featCount
        taskLayer.startEditing()
        QgsProject.instance().setSnapSettingsForLayer(taskLayerID,True,2,1,20,True)
    def finishEditngLayer(self):

        """
        change the edits to GML again to detect the changes

        """
        print featCount
        taskLayer_shape = iface.activeLayer()
        QgsVectorFileWriter.writeAsVectorFormat(taskLayer_shape,"Z:\\GMLEdited\\temp.gml","utf-8",None,"GML")

        #QgsMapLayerRegistry.instance().removeAllMapLayers()
        iface.addVectorLayer("Z:\\GMLEdited\\temp.gml","EditedTaskLayer","ogr")
        """
        Compare the two gml geometries
        """

        doc_edited = xml.dom.minidom.parse("Z:\\GMLEdited\\temp.gml")
        doc_origion = xml.dom.minidom.parse("Z:\\GMLFile\\ogrGML.gml")
        editedParcel = doc_edited.getElementsByTagName("gml:featureMember")
        epLength = editedParcel.length
        print epLength
        obj = GeometryEdit()
        if epLength > featCount:
           obj.split(doc_edited,doc_origion)
           print "split"
        elif epLength < featCount:
            obj.merge(doc_edited,doc_origion)
            print "merge"
        else:
            obj.updateGeom()
            print "update"
    def taskFeatures(self):
        self.taskFeaturesDlg.show()
        self.apdockwidget = QDockWidget("Features Of Current Task", self.iface.mainWindow())
        self.apdockwidget.setWindowFlags(Qt.FramelessWindowHint)
        self.apdockwidget.setWidget(self.taskFeaturesDlg)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.apdockwidget)


        self.menu_feature = QtGui.QMenu()
        #newTask=self.menu.addAction("New Task",self.newTask,"")
        editAttr = self.menu_feature.addAction("Edit", self.editEvent)
        self.taskFeaturesDlg.currentTaskTable.addAction(editAttr)
        self.taskFeaturesDlg.currentTaskTable.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.taskFeaturesDlg.currentTaskTable.customContextMenuRequested.connect(self.contextMenuEvent2)

        #self.connect(self.dateTimeEdit,SIGNAL("dateTimeChange
    def contextMenuEvent2(self, point):
        self.menu_feature.exec_(self.taskFeaturesDlg.currentTaskTable.mapToGlobal(point))
    def editEvent(self):
        self.showTaskInfo()
Example #56
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)