Example #1
0
class FilterSetWidget(QWidget, Ui_FilterSetWidget):
    def __init__(self, parent=None):
        super(FilterSetWidget, self).__init__(parent)
        self.setupUi(self)
        self._filterSetActionGroup = QActionGroup(self)
        self._filterSetActionGroup.addAction(self.saveFilterSetAction)
        self._filterSetActionGroup.addAction(self.reloadFilterSetAction)
        self._filterSetActionGroup.addAction(self.deleteFilterSetAction)
        self._filterSetActionGroup.addAction(self.exportFilterSetAction)
        self._filterSetMenu = QMenu(self)
        self._filterSetMenu.addActions(self._filterSetActionGroup.actions())
        self.filterSetTool.setMenu(self._filterSetMenu)
        self.filterSetTool.setDefaultAction(self.saveFilterSetAction)

    def setFilterSet(self, filterSet):
        self.setFilterSetKey(filterSet.key)
        if filterSet.source == 'ark':
            self.saveFilterSetAction.setEnabled(False)
            self.deleteFilterSetAction.setEnabled(False)
            self.filterSetTool.setDefaultAction(self.reloadFilterSetAction)
        else:
            self.saveFilterSetAction.setEnabled(True)
            self.deleteFilterSetAction.setEnabled(True)
            self.filterSetTool.setDefaultAction(self.saveFilterSetAction)

    def setFilterSetKey(self, key):
        self.filterSetCombo.setCurrentIndex(self.filterSetCombo.findData(key))

    def currentFilterSetKey(self):
        return self.filterSetCombo.itemData(self.filterSetCombo.currentIndex())

    def currentFilterSetName(self):
        return self.filterSetCombo.currentText()
Example #2
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 #3
0
    def on_context_menu(self, point):

        item = self.dock.treeWidget.itemAt(point)
        if item is None:
            return
        if item.actiontype is None:
            return
        actionDict = {'application':
                        ('Copy Application', 'Load all layers to QGIS',
                        'Application Settings', 'View Application in web browser',
                         'Delete Application'),
                    'layer':
                        ('Add Layer to QGIS','Layer Settings', 'Delete Layer'),
                    'qgisLayerReference':
                        ('Upload New Style', 'Apply Original Style'),
                    'applicationsItem':
                        ('Create New Application', 'Refresh Applications'),
                    'layersItem':('Upload New Layer from QGIS', 'Refresh Layers'),
                    'connection':('Refresh Connection', 'Remove Connection'),
                    'topitem':['New Connection']}

        actions = actionDict[item.actiontype]
        menu = QMenu()
        acts = []
        for actionName in actions:
            action = QAction(actionName, None)
            self.connectAction(action, actionName, item)
            acts.append(action)
        menu.addActions(acts)
        point = self.dock.treeWidget.mapToGlobal(point)
        menu.exec_(point)
Example #4
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        if linux_distribution():
            self.menu = QMenu('Open with')
            self.menu.aboutToShow.connect(self.build_submenu)
            self.ex_locator = self.locator.get_service('explorer')
            self.ex_locator.add_project_menu(self.menu, lang='all')

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu.clear()
        if self.ex_locator.get_current_project_item().isFolder is not True:
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            entry = xdg_query('default', guess_type(filenam, strict=False)[0])
            if entry:
                app = entry.replace('.desktop', '')
                self.menu.addActions([
                    QAction(QIcon.fromTheme(app), app, self,
                            triggered=lambda: Popen([app, filenam])),
                    QAction(QIcon.fromTheme('folder-open'), 'File Manager',
                            self, triggered=lambda: Popen(['xdg-open',
                                                    path.dirname(filenam)]))])
                self.menu.show()
Example #5
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.menu = QMenu('Convert Image')
        self.menu.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu, lang='all')

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu.clear()
        if self.ex_locator.get_current_project_item().isFolder is not True:
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            # pillow.readthedocs.org/en/latest/handbook/image-file-formats.html
            exten = ('bmp', 'cur', 'gbr', 'gif', 'ico', 'jfif', 'jpeg', 'pbm',
                'pcx', 'pgm', 'png', 'ppm', 'psd', 'tga', 'tiff', 'xbm', 'xpm')
            conditional = path.splitext(filenam)[1][1:].strip().lower() in exten
            if conditional:
                self.menu.addActions([
                    QAction('{} to WEBP'.format(path.basename(filenam)[:50]),
                            self, triggered=lambda: self.convert_img('WEBP')),
                    QAction('{} to JPG'.format(path.basename(filenam)[:50]),
                            self, triggered=lambda: self.convert_img('JPEG')),
                    QAction('{} to PNG'.format(path.basename(filenam)[:50]),
                            self, triggered=lambda: self.convert_img('PNG')), ])
                self.menu.show()

    def convert_img(self, fmt):
        """ convert image to desired format """
        filenam = self.ex_locator.get_current_project_item().get_full_path()
        im = Image.open(filenam).convert("RGB")
        im.save(path.splitext(filenam)[0] + ".{}".format(fmt.lower()), fmt)
Example #6
0
 def contextMenuRequested(point):
     " quick and dirty custom context menu "
     menu = QMenu()
     menu.addActions(
         (
             qaqq,
             qamin,
             qanor,
             qamax,
             qasrc,
             qakb,
             qacol,
             qati,
             qasb,
             qatb,
             qatim,
             qatit,
             qafnt,
             qapic,
             qadoc,
             qali,
             qaslf,
             qaqt,
             qapy,
             qabug,
         )
     )
     menu.exec_(self.mapToGlobal(point))
Example #7
0
    def _onTvFilesCustomContextMenuRequested(self, pos ):
        """Connected automatically by uic
        """
        menu = QMenu()
        
        menu.addAction( core.actionManager().action( "mFile/mClose/aCurrent" ) )
        menu.addAction( core.actionManager().action( "mFile/mSave/aCurrent" ) )
        menu.addAction( core.actionManager().action( "mFile/mReload/aCurrent" ) )
        menu.addSeparator()
        
        # sort menu
        sortMenu = QMenu( self )
        group = QActionGroup( sortMenu )

        group.addAction( self.tr( "Opening order" ) )
        group.addAction( self.tr( "File name" ) )
        group.addAction( self.tr( "URL" ) )
        group.addAction( self.tr( "Suffixes" ) )
        group.triggered.connect(self._onSortTriggered)
        sortMenu.addActions( group.actions() )
        
        for i, sortMode in enumerate(["OpeningOrder", "FileName", "URL", "Suffixes"]):
            action = group.actions()[i]
            action.setData( sortMode )
            action.setCheckable( True )
            if sortMode == self.model.sortMode():
                action.setChecked( True )
        
        aSortMenu = QAction( self.tr( "Sorting" ), self )
        aSortMenu.setMenu( sortMenu )
        aSortMenu.setIcon( QIcon( ":/enkiicons/sort.png" ))
        aSortMenu.setToolTip( aSortMenu.text() )
        
        menu.addAction( sortMenu.menuAction() )
        menu.exec_( self.tvFiles.mapToGlobal( pos ) )
class FilterSetWidget(QWidget, Ui_FilterSetWidget):

    def __init__(self, parent=None):
        super(FilterSetWidget, self).__init__(parent)
        self.setupUi(self)
        self._filterSetActionGroup = QActionGroup(self)
        self._filterSetActionGroup.addAction(self.saveFilterSetAction)
        self._filterSetActionGroup.addAction(self.reloadFilterSetAction)
        self._filterSetActionGroup.addAction(self.deleteFilterSetAction)
        self._filterSetActionGroup.addAction(self.exportFilterSetAction)
        self._filterSetMenu = QMenu(self)
        self._filterSetMenu.addActions(self._filterSetActionGroup.actions())
        self.filterSetTool.setMenu(self._filterSetMenu)
        self.filterSetTool.setDefaultAction(self.saveFilterSetAction)

    def setFilterSet(self, filterSet):
        self.setFilterSetKey(filterSet.key)
        if filterSet.source == 'ark':
            self.saveFilterSetAction.setEnabled(False)
            self.deleteFilterSetAction.setEnabled(False)
            self.filterSetTool.setDefaultAction(self.reloadFilterSetAction)
        else:
            self.saveFilterSetAction.setEnabled(True)
            self.deleteFilterSetAction.setEnabled(True)
            self.filterSetTool.setDefaultAction(self.saveFilterSetAction)

    def setFilterSetKey(self, key):
        self.filterSetCombo.setCurrentIndex(self.filterSetCombo.findData(key))

    def currentFilterSetKey(self):
        return self.filterSetCombo.itemData(self.filterSetCombo.currentIndex())

    def currentFilterSetName(self):
        return self.filterSetCombo.currentText()
Example #9
0
    def contextMenu(self, pos):
        menu = QMenu()
        menu.addActions(self.contextMenuActions)
        difficultyMenu = menu.addMenu("Change difficulty")
        difficultyMenu.addActions(self.difficultyActions)
        # change position a little to have a corner of the menu where the mouse is
	if platform.system() != "Windows":
            menu.exec_(self.wordsTable.mapToGlobal(QPoint(pos.x()+18,pos.y()	+24)))
        else:
            menu.exec_(self.wordsTable.mapToGlobal(QPoint(pos.x()+16,pos.y()	+24)))
Example #10
0
 def initLexerMenu(self):
     self.action_Lexer = QAction(Icons.file_obj, 'Lexer', self)
     men = QMenu()
     self.lexGroup = QActionGroup(self)
     self.lexGroup.setExclusive(True)
     self.lexGroup.selected.connect(self.parent.setLexer)
     #langs = [i for i in dir(Qsci) if i.startswith('QsciLexer')]
     langs = ['Bash', 'Batch', 'CMake', 'CPP', 'CSS', 'C#','HTML','Java', 'JavaScript', 'Lua', 'Makefile','Python', 'SQL', 'XML', 'YAML']
     for l in langs:
         act = self.make_action_lex(l)
         self.lexGroup.addAction(act)
         if(langs.index(l) == 8): #For javascript
             act.setChecked(True)
         #print l[9:] # we don't need to print "QsciLexer" before each name
     men.addActions(self.lexGroup.actions())
     self.action_Lexer.setMenu(men)
     self.addAction(self.action_Lexer)
Example #11
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 #12
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.menu = QMenu('Copy path')
        self.menu.addActions([QAction('Full file path', self, triggered=lambda:
            QApplication.clipboard().setText(self.locator.get_service('explorer'
            ).get_current_project_item().get_full_path())),
            QAction('Filename only', self, triggered=lambda:
            QApplication.clipboard().setText(path.basename(
            self.locator.get_service('explorer').get_current_project_item(
            ).get_full_path()))),
            QAction('Directory path only', self, triggered=lambda:
            QApplication.clipboard().setText(path.dirname(
            self.locator.get_service('explorer').get_current_project_item(
            ).get_full_path())))
        ])
        self.locator.get_service('explorer').add_project_menu(self.menu,
                                                              lang='all')
Example #13
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        if linux_distribution():
            self.menu = QMenu('Open with')
            self.menu.aboutToShow.connect(self.build_submenu)
            self.ex_locator = self.locator.get_service('explorer')
            self.ex_locator.add_project_menu(self.menu, lang='all')

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu.clear()

        if self.ex_locator.get_current_project_item().isFolder is not True:
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            entry = xdg_query('default', guess_type(filenam, strict=False)[0])
            if entry:
                app = entry.replace('.desktop', '')
                actions = [
                QAction(QIcon.fromTheme(app), app, self,
                    triggered=lambda: Popen([app, filenam])),
                QAction(QIcon.fromTheme('folder-open'), 'File Manager',
                    self, triggered=lambda: Popen(['xdg-open', path.dirname(filenam)]))]

                    #QAction(QIcon.fromTheme('Sublime Text 2'), 'Sublime',
                    #    self, triggered=lambda: Popen(['sublime-text', filenam])),
                    #QAction(QIcon.fromTheme('Sqliteman'), 'Sqliteman',
                    #    self, triggered=lambda: Popen(['sqliteman', filenam])),
                    #QAction(QIcon.fromTheme('Google Chrome'), 'Google Chrome',
                    #    self, triggered=lambda: Popen(['google-chrome', filenam]))
                    
                for key in usersettings.commands.keys():
                    action = QAction(QIcon.fromTheme(key), key,
                        self, triggered=lambda: Popen([usersettings.commands[key], filenam]))
                    actions.append(action)
                
                self.menu.addActions(actions)
                    
                self.menu.show()
    def handlePackageContextAction(point):
        window = QApplication.activeWindow()
        package = window.currentPackage()
        menu = QMenu(parent=window)

        install = QAction(QIcon(':/icons/installed.png'), "&Install", window.packages)
        install.connect(install, SIGNAL('triggered()'), lambda: Frontend.default().install(package))
        install.setEnabled(package.get('state', False) & (State.NonInstalled | State.AUR))

        update = QAction(QIcon(':/icons/upgrade.png'), "&Update", window.packages)
        update.connect(update, SIGNAL('triggered()'), lambda: Frontend.default().install(package, update=True))
        update.setEnabled(package.get('state', False) & State.Update)

        remove = QAction(QIcon(':/icons/stop.png'), "&Remove", window.packages)
        remove.connect(remove, SIGNAL('triggered()'), lambda: Frontend.default().remove(package))
        remove.setEnabled(package.get('state', False) & (State.Installed | State.Update))

        remove_forced = QAction(QIcon(':/icons/orphan.png'), "&Remove (force)", window.packages)
        remove_forced.connect(remove_forced, SIGNAL('triggered()'), lambda: Frontend.default().remove(package, force=True))
        remove_forced.setEnabled(package.get('state', False) & (State.Installed | State.Update))

        menu.addActions((install, update, remove, remove_forced))
        menu.exec_(window.packages.mapToGlobal(point))
Example #15
0
 def initApiMenu(self):
     self.action_Api = QAction(Icons.lib, 'Api', self)
     men = QMenu()
     self.apiGroup = QActionGroup(self)
     self.apiGroup.setExclusive(True)
     self.apiGroup.selected.connect(self.parent.setApi)
     list = oslistdir(apiDir)
     apis = []
     if(list != None):
         for i in list:
             if i.endswith("api"):
                 apis.append(i.replace(".api", ""))
     if(apis != None):
         for i in apis:
             act = self.make_action_api(i)
             self.apiGroup.addAction(act)
             if(i == "emo"): #For emo
                 act.setChecked(True)
     men.addActions(self.apiGroup.actions())
     self.action_Api.setMenu(men)
     self.addAction(self.action_Api)
     
     
Example #16
0
File: main.py Project: PyAr/wefree
    def build_menu(self, signals):
        """Build the menu."""
        def action_cmp(a,b):
            aText = a.text().upper()
            bText = b.text().upper()
            if aText == bText: return 0
            if aText < bText: return -1
            return 1

        menu = QMenu(self)

        connected = False
        # the signals
        signal_actions = []
        for signal in signals:
            icon = self.icon_for_signal(signal)

            if signal.is_connected():
                connected = True

            when_triggered = (lambda sign: lambda:self.please_connect(sign))(signal)
            action = QAction(icon, signal.ssid, self, triggered = when_triggered)
            signal_actions.append(action)

        signal_actions.sort(cmp = action_cmp)
        menu.addActions(signal_actions)

        self.update_connected_state(connected)

        # the bottom part
        menu.addSeparator()
        menu.addAction(QAction("Share...",        self, triggered=self.share_keys))
        menu.addAction(QAction("Update Database", self, triggered=self.update_database))
        menu.addAction(QAction("Rescan",          self, triggered=self.rescan_networks))
        menu.addAction(QAction("Quit",            self, triggered=self.app_quit))
        menu.addAction(QAction("WTF?",            self, triggered=self.open_about_dialog))
        return menu
Example #17
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.menu1 = QMenu('Compress')
        self.menu1.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu1, lang='all')
        if not version_info[0] < 3:
            self.menu2 = QMenu('Extract')
            self.menu2.aboutToShow.connect(self.build_submenu)
            self.ex_locator.add_project_menu(self.menu2, lang='all')

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu1.clear()
        if self.ex_locator.get_current_project_item().isFolder is True:
            folder = self.ex_locator.get_current_project_item().get_full_path()
            self.menu1.addActions([
                QAction('To ZIP', self, triggered=lambda:
                                        make_archive(folder, 'zip', folder)),
                QAction('To TAR', self, triggered=lambda:
                                        make_archive(folder, 'tar', folder)),
                QAction('To BZ2', self, triggered=lambda:
                                        make_archive(folder, 'bztar', folder))])
            self.menu1.show()
        elif not version_info[0] < 3:
            self.menu2.clear()
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            exten = ('zip', 'tar', 'bz2', 'bztar', 'gztar')
            conditional = path.splitext(filenam)[1][1:].strip().lower() in exten
            if conditional:
                self.menu2.addAction(QAction('From {}'.format(
                    path.splitext(filenam)[1].upper()), self, triggered=lambda:
                    unpack_archive(filenam, path.dirname(filenam))))
                self.menu2.show()
Example #18
0
    def _onTvFilesCustomContextMenuRequested(self, pos):
        """Connected automatically by uic
        """
        menu = QMenu()

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

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

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

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

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

        menu.addAction(sortMenu.menuAction())
        menu.exec_(self.tvFiles.mapToGlobal(pos))
Example #19
0
class ActionSettingsTool(QToolButton):

    settingsChanged = pyqtSignal()
    mapActionChanged = pyqtSignal(int)
    filterActionChanged = pyqtSignal(int)
    drawingActionChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super(ActionSettingsTool, self).__init__(parent)

        self._mapActionGroup = QActionGroup(self)
        self._noMapAction = self._addMapAction(MapAction.NoMapAction, 'No map action')
        self._zoomMapAction = self._addMapAction(MapAction.ZoomMap, 'Zoom map view')
        self._panMapAction = self._addMapAction(MapAction.PanMap, 'Pan map view')
        self._moveMapAction = self._addMapAction(MapAction.MoveMap, 'Move map view')
        self._moveMapAction.setChecked(True)

        self._filterActionGroup = QActionGroup(self)
        self._noFilterAction = self._addFilterAction(FilterAction.NoFilterAction, 'No filter action')
        self._includeFilterAction = self._addFilterAction(FilterAction.IncludeFilter, 'Add to filter')
        self._exclusiveFilterAction = self._addFilterAction(FilterAction.ExclusiveFilter, 'Exclusive filter')
        self._selectFilterAction = self._addFilterAction(FilterAction.SelectFilter, 'Add to selection')
        self._exclusiveSelectFilterAction = self._addFilterAction(
            FilterAction.ExclusiveSelectFilter, 'Exclusive selection')
        self._highlightFilterAction = self._addFilterAction(FilterAction.HighlightFilter, 'Add to highlight')
        self._exclusiveHighlightFilterAction = self._addFilterAction(
            FilterAction.ExclusiveHighlightFilter, 'Exclusive highlight')
        self._exclusiveHighlightFilterAction.setChecked(True)

        self._drawingActionGroup = QActionGroup(self)
        self._noDrawingAction = self._addDrawingAction(DrawingAction.NoDrawingAction, 'No drawing action')
        self._noDrawingAction.setChecked(True)
        self._loadDrawingsAction = self._addDrawingAction(DrawingAction.LoadDrawings, 'Load drawings')
        self._addDrawingsAction = self._addDrawingAction(DrawingAction.AddDrawings, 'Add drawings')

        self._settingsMenu = QMenu(self)
        self._settingsMenu.addActions(self._mapActionGroup.actions())
        self._settingsMenu.addSeparator()
        self._settingsMenu.addActions(self._filterActionGroup.actions())
        self._settingsMenu.addSeparator()
        self._settingsMenu.addActions(self._drawingActionGroup.actions())

        self._settingsAction = QAction(QIcon(':/plugins/ark/settings.svg'), "Action Settings", self)
        self._settingsAction.setMenu(self._settingsMenu)
        self.setDefaultAction(self._settingsAction)
        self.setPopupMode(QToolButton.InstantPopup)

    def setMapAction(self, mapAction):
        if mapAction == MapAction.NoMapAction:
            self._noMapAction.setChecked(True)
        elif mapAction == MapAction.ZoomMap:
            self._zoomMapAction.setChecked(True)
        elif mapAction == MapAction.PanMap:
            self._panMapAction.setChecked(True)
        elif mapAction == MapAction.MoveMap:
            self._moveMapAction.setChecked(True)

    def setFilterAction(self, filterAction):
        if filterAction == FilterAction.NoFilterAction:
            self._noFilterAction.setChecked(True)
        elif filterAction == FilterAction.IncludeFilter:
            self._includeFilterAction.setChecked(True)
        elif filterAction == FilterAction.ExclusiveFilter:
            self._exclusiveFilterAction.setChecked(True)
        elif filterAction == FilterAction.SelectFilter:
            self._selectFilterAction.setChecked(True)
        elif filterAction == FilterAction.ExclusiveSelectFilter:
            self._exclusiveSelectFilterAction.setChecked(True)
        elif filterAction == FilterAction.HighlightFilter:
            self._highlightFilterAction.setChecked(True)
        elif filterAction == FilterAction.ExclusiveHighlightFilter:
            self._exclusiveHighlightFilterAction.setChecked(True)

    def setDrawingAction(self, drawingAction):
        if drawingAction == DrawingAction.NoDrawingAction:
            self._noDrawingAction.setChecked(True)
        elif drawingAction == DrawingAction.LoadDrawings:
            self._loadDrawingsAction.setChecked(True)
        elif drawingAction == DrawingAction.AddDrawings:
            self._addDrawingsAction.setChecked(True)

    def _addMapAction(self, mapAction, text):
        action = QAction(text, self)
        action.setCheckable(True)
        action.setData(mapAction)
        action.triggered.connect(self._mapActionSelected)
        self._mapActionGroup.addAction(action)
        return action

    def _mapActionSelected(self):
        self.mapActionChanged.emit(self._mapActionGroup.checkedAction().data())
        self.settingsChanged.emit()

    def _addFilterAction(self, filterAction, text):
        action = QAction(text, self)
        action.setCheckable(True)
        action.setData(filterAction)
        action.triggered.connect(self._filterActionSelected)
        self._filterActionGroup.addAction(action)
        return action

    def _filterActionSelected(self):
        self.filterActionChanged.emit(self._filterActionGroup.checkedAction().data())
        self.settingsChanged.emit()

    def _addDrawingAction(self, drawingAction, text):
        action = QAction(text, self)
        action.setCheckable(True)
        action.setData(drawingAction)
        action.triggered.connect(self._drawingActionSelected)
        self._drawingActionGroup.addAction(action)
        return action

    def _drawingActionSelected(self):
        self.drawingActionChanged.emit(self._drawingActionGroup.checkedAction().data())
        self.settingsChanged.emit()
Example #20
0
 def on_neoUnitList_customContextMenuRequested(self, pos):
     if not self.neoUnitList.selectedIndexes():
         return
     context_menu = QMenu(self)
     context_menu.addActions(self._context_actions(self.neoUnitList))
     context_menu.popup(self.neoUnitList.mapToGlobal(pos))
Example #21
0
class PgVersion(QObject):
    def __init__(self, iface):
        QObject.__init__(self)
        # Save reference to the QGIS interface
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.w = None
        self.vsCheck = None
        self.layer_list = []

        #Initialise thetranslation environment
        self.plugin_path = QDir.cleanPath(
            os.path.abspath(os.path.dirname(__file__)))
        myLocaleName = QLocale.system().name()
        myLocale = myLocaleName[0:2]
        if QFileInfo(self.plugin_path).exists():
            localePath = self.plugin_path + "/i18n/pgVersion_" + myLocale + ".qm"

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

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

#    QgsMapLayerRegistry.instance().layerWasAdded.connect(self.add_layer)
#    QgsMapLayerRegistry.instance().layerWillBeRemoved.connect(self.remove_layer)

    def initGui(self):

        self.helpDialog = HelpDialog()
        self.logview_dialog = LogView(self)
        self.feature_history = FeatureHistory(self.iface)
        self.tools = PgVersionTools(self)

        self.toolBar = self.iface.addToolBar("PG Version")
        self.toolBar.setObjectName("PG Version")

        self.actionInit = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-init.png"),
            self.tr("Prepare Layer for Versioning"), self.iface.mainWindow())
        self.actionLoad = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-commit.png"),
            self.tr("Load Versioned Layer"), self.iface.mainWindow())
        self.actionCommit = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-load.png"),
            self.tr("Commit Changes"), self.iface.mainWindow())
        self.actionRevert = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-revert.png"),
            self.tr("Revert to HEAD Revision"), self.iface.mainWindow())
        self.actionLogView = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-logview.png"),
            self.tr("Show Logs"), self.iface.mainWindow())
        self.actionDiff = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-diff.png"),
            self.tr("Show Diffs"), self.iface.mainWindow())
        self.actionFeatureInfo = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-feature-info.png"),
            self.tr("Feature History"), self.iface.mainWindow())
        self.actionFeatureInfo.setCheckable(True)

        self.actionDrop = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-drop.png"),
            self.tr("Drop Versioning from Layer"), self.iface.mainWindow())
        self.actionHelp = QAction(QIcon(""), self.tr("Help"),
                                  self.iface.mainWindow())
        self.actionAbout = QAction(QIcon(""), self.tr("About"),
                                   self.iface.mainWindow())
        self.actionDelete = QAction(
            QIcon(":/plugins/pgversion/icons/pgversion-drop.png"),
            self.tr("Bulk delete directly in the database"),
            self.iface.mainWindow())
        self.actionDelete.setEnabled(False)

        self.actionList = [
            self.actionInit, self.actionLoad, self.actionCommit,
            self.actionDiff, self.actionRevert, self.actionFeatureInfo,
            self.actionLogView, self.actionDrop, self.actionDelete,
            self.actionHelp, self.actionAbout
        ]

        self.toolBar.addAction(self.actionInit)
        self.toolBar.addAction(self.actionLoad)
        self.toolBar.addAction(self.actionCommit)
        self.toolBar.addAction(self.actionRevert)
        self.toolBar.addAction(self.actionFeatureInfo)
        self.toolBar.addAction(self.actionLogView)
        self.toolBar.addAction(self.actionDiff)
        self.toolBar.addAction(self.actionDelete)

        # Add the Menubar into the new Database Main Menue starting with QGIS1.7
        try:
            for a in self.actionList:
                self.iface.addPluginToDatabaseMenu("PG Version", a)
        except AttributeError:
            # For former QGIS Versions use the old Main Menue
            self.menu = QMenu()
            self.menu.setTitle("PG Version")
            self.menu.addActions(self.actionList)
            self.menuBar = self.iface.mainWindow().menuBar()
            self.menuBar.addMenu(self.menu)

        self.actionInit.triggered.connect(self.doInit)
        self.actionLoad.triggered.connect(self.doLoad)
        self.actionDiff.triggered.connect(self.doDiff)
        self.actionCommit.triggered.connect(self.doCommit)
        self.actionRevert.triggered.connect(self.doRevert)
        self.actionLogView.triggered.connect(self.doLogView)
        self.actionDrop.triggered.connect(self.doDrop)
        self.actionHelp.triggered.connect(self.doHelp)
        self.actionAbout.triggered.connect(self.doAbout)
        self.actionDelete.triggered.connect(self.doDelete)
        self.actionFeatureInfo.triggered.connect(self.doFeatureInfo)

        self.logview_dialog.diffLayer.connect(self.doDiff)
        self.logview_dialog.rollbackLayer.connect(self.doRollback)
        self.logview_dialog.checkoutLayer.connect(self.doCheckout)
        self.logview_dialog.checkoutTag.connect(self.doCheckout)
        self.logview_dialog.createBranch.connect(self.doMakeBranch)

        QgsMapLayerRegistry.instance().layerWasAdded.connect(self.add_layer)
        QgsMapLayerRegistry.instance().layerWillBeRemoved.connect(
            self.remove_layer)

        self.handler = None
        self.selected_layer = None
        self.iface.currentLayerChanged.connect(self.onLayerChanged)

    def onLayerChanged(self, layer):
        if layer != None:
            self.selected_layer = layer

            if self.selected_layer.type(
            ) == 0 and self.selected_layer.selectedFeatureCount() == 0:
                self.actionDelete.setEnabled(False)
            else:
                if self.tools.hasVersion(self.selected_layer):
                    if self.selected_layer.isEditable():
                        self.actionDelete.setEnabled(True)  # true
                    else:
                        self.actionDelete.setEnabled(False)
                else:
                    self.actionDelete.setEnabled(False)  # true

    def add_layer(self, l):
        if self.tools.hasVersion(l):
            if l.id not in self.layer_list:

                l.editingStopped.connect(lambda my_list=self.layer_list: self.
                                         tools.setModified(my_list))
                l.editingStopped.connect(
                    lambda my_layer=l: self.tools.editingStopped(my_layer))
                l.saveLayerToProject.connect(
                    lambda my_layer=l: self.tools.editingStopped(my_layer))
                l.selectionChanged.connect(self.onLayerChanged)
                self.layer_list.append(l.id())
                self.tools.setModified(self.layer_list)

    def remove_layer(self, id):
        self.layer_list = list(set(self.layer_list))
        if id in set(self.layer_list):
            self.layer_list.remove(id)

    def unload(self):
        # remove menubar
        try:
            for a in self.actionList:
                self.iface.removePluginDatabaseMenu("PG Version", a)
        except:
            del self.menuBar
        del self.toolBar

    def toggle_feature_info_cursor(self):
        pass

    def doFeatureInfo(self):
        self.iface.mapCanvas().setMapTool(self.feature_history)

    def doDelete(self):
        res = QMessageBox.question(
            None, self.tr("Question"),
            self.
            tr("Are you sure to delete all selected features. You cannot undo this action!"
               ),
            QMessageBox.StandardButtons(QMessageBox.No | QMessageBox.Yes))

        if res == QMessageBox.Yes:
            QApplication.restoreOverrideCursor()
            canvas = self.iface.mapCanvas()
            currentLayer = canvas.currentLayer()
            mySchema = self.tools.layerSchema(currentLayer)
            myTable = self.tools.layerTable(currentLayer)
            myPkey = QgsDataSourceURI(
                currentLayer.dataProvider().dataSourceUri()).keyColumn()
            myDb = self.tools.layerDB('doInit', currentLayer)
            selectedFeatures = currentLayer.selectedFeatures()
            delete_list = "("

            if currentLayer.selectedFeatureCount() > 0:
                for feature in selectedFeatures:
                    delete_list += str(feature.attributes()[0]) + ", "

                delete_list = delete_list[:-2]
                delete_list += ")"
                sql = "delete from \"%s\".\"%s\" where \"%s\" in %s" % (
                    mySchema, myTable, myPkey, delete_list)
                QApplication.setOverrideCursor(Qt.WaitCursor)
                myDb.run(sql)
                QApplication.restoreOverrideCursor()
                currentLayer.removeSelection()
                currentLayer.triggerRepaint()
                self.tools.setModified(self.layer_list)


#                self.actionDelete.setEnabled(false)

    def doInit(self):
        canvas = self.iface.mapCanvas()
        currentLayer = canvas.currentLayer()

        if currentLayer == None:
            QMessageBox.information(
                None, '', self.tr('Please select a layer for versioning'))
            return
        elif self.tools.hasVersion(currentLayer):
            QMessageBox.warning(
                None, self.tr('Warning'),
                self.tr('The selected layer is already under versioning!'))
            return
        else:
            mySchema = self.tools.layerSchema(currentLayer)
            myTable = self.tools.layerTable(currentLayer)
            myDb = self.tools.layerDB('doInit', currentLayer)
            if not self.tools.check_PGVS_revision(myDb):
                return

            if not self.tools.versionExists(currentLayer):
                answer = QMessageBox.question(
                    None, '',
                    self.
                    tr('Do you want to create the version environment for the table {0}'
                       ).format(mySchema + '.' + myTable), self.tr('Yes'),
                    self.tr('No'))
                QApplication.setOverrideCursor(Qt.WaitCursor)
                sql = "select * from versions.pgvsinit('%s.%s')" % (mySchema,
                                                                    myTable)
                result = myDb.runError(sql)

                if result == ' ':
                    sql = "GRANT ALL ON TABLE %s.%s TO versions" % (mySchema,
                                                                    myTable)
                    grant_result = myDb.runError(sql)
                    QMessageBox.information(
                        None, 'Init',
                        self.tr('Init was successful!\n\n\
Please set the user permissions for table {0} and reload it via Database -> PG Version!'
                                ).format(myTable))

                    QgsMapLayerRegistry.instance().removeMapLayer(
                        currentLayer.id())

                    QApplication.restoreOverrideCursor()
            else:
                self.iface.messageBar().pushMessage(
                    self.tr('Init Error'),
                    self.tr(
                        'Versioning envoronment for table {0} already exsists!'
                    ).format(mySchema + "." + myTable),
                    level=QgsMessageBar.CRITICAL,
                    duration=3)

    def doLoad(self):
        self.dlg = PgVersionLoadDialog(self)
        self.dlg.show()

    def doRollback(self, item):
        if item == None:
            QMessageBox.information(None, self.tr('Error'),
                                    self.tr('Please select a valid revision'))
            return

        revision = item.text(0)
        canvas = self.iface.mapCanvas()
        currentLayer = canvas.currentLayer()

        if currentLayer == None:
            QMessageBox.information(None, '',
                                    self.tr('Please select a versioned layer'))
            return
        else:
            answer = QMessageBox.question(
                None, '',
                self.tr('Are you sure to rollback to revision {0}?').format(
                    revision), self.tr('Yes'), self.tr('No'))
            if answer == 0:
                if self.tools.isModified(currentLayer):
                    answer = QMessageBox.question(None, '', \
                    self.tr('Layer {0} has modifications which will be lost after rollback! \
If you want to keep this modifications please commit them. \
Are you sure to rollback to revision {1}?'                                              ).format(currentLayer.name(),  revision), self.tr('Yes'),  self.tr('No'))
                    if answer == 1:
                        return

                QApplication.setOverrideCursor(Qt.WaitCursor)
                provider = currentLayer.dataProvider()
                uri = provider.dataSourceUri()
                myDb = self.tools.layerDB('doRollback', currentLayer)
                if not self.tools.check_PGVS_revision(myDb):
                    return
                mySchema = QgsDataSourceURI(uri).schema()

                if len(mySchema) == 0:
                    mySchema = 'public'
                myTable = QgsDataSourceURI(uri).table()

                sql = "select * from versions.pgvsrollback('" + mySchema + "." + myTable.replace(
                    '_version', '') + "'," + revision + ")"

                myDb.run(sql)
                myDb.close()
                self.logview_dialog.close()
                currentLayer.triggerRepaint()
                QApplication.restoreOverrideCursor()
                self.tools.setModified(self.layer_list)
                self.iface.messageBar().pushMessage(
                    'INFO',
                    self.tr('Rollback to revision {0} was successful!').format(
                        revision),
                    level=QgsMessageBar.INFO,
                    duration=3)
                return

    def doCommit(self):
        canvas = self.iface.mapCanvas()

        if canvas.currentLayer() == None:
            self.iface.messageBar().pushMessage(
                'Error',
                self.tr('Please select a versioned layer for committing'),
                level=QgsMessageBar.CRITICAL,
                duration=3)
            return

        canvas = self.iface.mapCanvas()
        theLayer = canvas.currentLayer()
        mySchema = self.tools.layerSchema(theLayer)
        myTable = self.tools.layerTable(theLayer).replace('_version', '')

        if not self.tools.hasVersion(theLayer):
            QMessageBox.warning(None, self.tr('Warning'),
                                self.tr('Please select a versioned layer!'))
        else:
            if self.tools.isModified(theLayer):
                confRecords = self.tools.confRecords(theLayer)
                if confRecords == None:
                    # show the dialog
                    self.dlgCommitMessage = CommitMessageDialog()
                    self.dlgCommitMessage.show()
                    result = self.dlgCommitMessage.exec_()

                    if result == QDialog.Accepted:
                        QApplication.setOverrideCursor(Qt.WaitCursor)
                        sql = "select * from versions.pgvscommit('%s.%s','%s')" % (
                            mySchema, myTable,
                            self.dlgCommitMessage.textEdit.toPlainText())
                        myDB = self.tools.layerDB('commit', theLayer)
                        myDB.run(sql)
                        myDB.close()
                        self.tools.layerRepaint()
                        self.iface.messageBar().pushMessage(
                            "Info",
                            self.tr('Commit of your changes was successful'),
                            level=QgsMessageBar.INFO,
                            duration=3)
                        self.tools.setModified(self.layer_list)
                        QApplication.restoreOverrideCursor()
                else:
                    if self.w != None:
                        self.w = None
                    self.w = ConflictWindow(theLayer, 'conflict', self)
                    self.w.mergeCompleted.connect(self.doCommit)
                    self.w.show()

                self.tools.setModified(self.layer_list)
            else:
                self.iface.messageBar().pushMessage(
                    'INFO',
                    self.tr(
                        'No layer changes for committing, everything is OK'),
                    level=QgsMessageBar.INFO,
                    duration=3)

        self.tools.setModified(self.layer_list)

    def doCheckout(self, revision, tag=None):
        if revision == None:
            QMessageBox.information(None, self.tr('Error'),
                                    self.tr('Please select a valid revision'))
            return

        canvas = self.iface.mapCanvas()
        currentLayer = canvas.currentLayer()

        if currentLayer == None:
            QMessageBox.information(None, '',
                                    self.tr('Please select a versioned layer'))
            return
        else:
            answer = QMessageBox.question(
                None, '',
                self.tr('Are you sure to checkout the layer to revision {0}?').
                format(revision), self.tr('Yes'), self.tr('No'))
            if answer == 0:
                QApplication.setOverrideCursor(Qt.WaitCursor)
                provider = currentLayer.dataProvider()
                uri = provider.dataSourceUri()
                uniqueCol = QgsDataSourceURI(uri).keyColumn()
                geomCol = QgsDataSourceURI(uri).geometryColumn()
                mySchema = QgsDataSourceURI(uri).schema()
                myTable = QgsDataSourceURI(uri).table()

                if len(mySchema) == 0:
                    mySchema = 'public'

                sql = 'select * from versions.pgvscheckout(NULL::"%s"."%s", %s)' % (
                    mySchema, myTable.replace('_version', ''), revision)

                myUri = QgsDataSourceURI(uri)
                myUri.setDataSource("", u"(%s\n)" % (sql), geomCol, "",
                                    uniqueCol)

                layer = None

                if tag:
                    table_ext = " (Tag: %s)" % tag
                else:
                    table_ext = " (Revision: %s)" % revision

                layer = QgsVectorLayer(myUri.uri(), myTable + table_ext,
                                       "postgres")

                QgsMapLayerRegistry.instance().addMapLayer(layer)
                QApplication.restoreOverrideCursor()
                if layer.isValid():
                    self.iface.messageBar().pushMessage(
                        'INFO',
                        self.tr('Checkout to revision {0} was successful!'
                                ).format(revision),
                        level=QgsMessageBar.INFO,
                        duration=3)
                    layer.triggerRepaint()
                else:
                    self.iface.messageBar().pushMessage(
                        'CRITICAL',
                        self.
                        tr('Something went wrong during checkout to revision {0}!'
                           ).format(revision),
                        level=QgsMessageBar.CRITICAL,
                        duration=3)
                self.logview_dialog.close()
                return

    def doRevert(self):
        canvas = self.iface.mapCanvas()
        theLayer = self.iface.activeLayer()
        provider = theLayer.dataProvider()
        uri = provider.dataSourceUri()
        myDb = self.tools.layerDB('revert', theLayer)
        mySchema = QgsDataSourceURI(uri).schema()
        myTable = QgsDataSourceURI(uri).table()

        if not self.tools.hasVersion(theLayer):
            QMessageBox.warning(None, self.tr('Warning'),
                                self.tr('Please select a versioned layer!'))
        else:
            if len(mySchema) == 1:
                mySchema = 'public'

            answer = QMessageBox.question(
                None, '',
                self.tr('are you sure to revert to the HEAD revision?'),
                self.tr('Yes'), self.tr('No'))

            if answer == 0:
                sql = "select * from versions.pgvsrevert('" + mySchema + "." + myTable.replace(
                    '_version', '') + "')"
                result = myDb.read(sql)

                if len(result) > 1:
                    QMessageBox.information(None, '', result)
                else:
                    self.iface.messageBar().pushMessage(
                        "Info",
                        self.
                        tr('All changes are set back to the HEAD revision: {0}'
                           ).format(str(result["PGVSREVERT"][0])),
                        level=QgsMessageBar.INFO,
                        duration=3)

            self.tools.setModified(self.layer_list)
            theLayer.triggerRepaint()
            myDb.close()

    def doLogView(self):
        canvas = self.iface.mapCanvas()
        theLayer = self.iface.activeLayer()

        if theLayer <> None:
            if not self.tools.hasVersion(theLayer):
                QMessageBox.warning(
                    None, self.tr('Warning'),
                    self.tr('Please select a versioned layer!'))
            else:
                provider = theLayer.dataProvider()
                uri = provider.dataSourceUri()
                myDb = self.tools.layerDB('logview', theLayer)
                mySchema = QgsDataSourceURI(uri).schema()
                myTable = QgsDataSourceURI(uri).table()

                if len(mySchema) == 0:
                    mySchema = 'public'

                sql = "select * from versions.pgvslogview('%s.%s') order by revision desc" % (
                    mySchema, myTable.replace('_version', '').split('#')[0])
                result = myDb.read(sql)

                self.logview_dialog.setLayer(theLayer)
                self.logview_dialog.createTagList()
                self.logview_dialog.treeWidget.clear()

                itemList = []

                for i in range(len(result["PROJECT"])):
                    myItem = QTreeWidgetItem()
                    myItem.setText(0, result["REVISION"][i])
                    myItem.setText(1, result["DATUM"][i])
                    myItem.setText(2, result["PROJECT"][i])
                    myItem.setText(3, result["LOGMSG"][i])
                    itemList.append(myItem)

                sql = "select version_table_id \
              from versions.version_tables \
              where version_table_schema = '%s' \
                and version_table_name = '%s'" % (
                    mySchema, myTable.replace('_version', '').split('#')[0])

                result = myDb.read(sql)
                self.logview_dialog.treeWidget.addTopLevelItems(itemList)
                self.logview_dialog.set_version_table_id(
                    result['VERSION_TABLE_ID'][0])
                self.logview_dialog.show()
                myDb.close()
                canvas.refresh()

    def doDiff(self):
        canvas = self.iface.mapCanvas()
        currentLayer = canvas.currentLayer()

        if self.tools.isModified(currentLayer):
            myDb = self.tools.layerDB('logview', currentLayer)

            if currentLayer == None:
                QMessageBox.information(
                    None, '', self.tr('Please select a versioned layer'))
                return
            else:
                answer = 0
                if answer == 0:
                    QApplication.setOverrideCursor(Qt.WaitCursor)
                    geomCol = self.tools.layerGeomCol(currentLayer)
                    geometryType = self.tools.layerGeometryType(currentLayer)
                    mySchema = self.tools.layerSchema(currentLayer)
                    myTable = self.tools.layerTable(currentLayer)
                    id = self.tools.layerBranchId(currentLayer)

                    if len(mySchema) == 0:
                        mySchema = 'public'

                    sql = u"select * from \"%s\".\"%s\" limit 0" % (mySchema,
                                                                    myTable)
                    cols = myDb.cols(sql)
                    extent = self.iface.mapCanvas().extent().toString(
                    ).replace(':', ',')
                    authority, crs = currentLayer.crs().authid().split(':')
                    geo_idx = '%s && ST_MakeEnvelope(%s,%s)' % (geomCol,
                                                                extent, crs)

                    sql = ("with \
    head as (select max(revision) as head from versions.\"{schema}_{origin}_version_log\"), \
    delete as (\
    select 'delete'::varchar as action, * \
      from (\
      select * from versions.pgvscheckout(NULL::\"{schema}\".\"{origin}\",(select * from head), \'{geo_idx}\') \
      except \
      select * from \"{schema}\".\"{origin}_version#{id}\" where {geo_idx}\
      ) as foo \
    ), \
    insert as (\
    select 'insert'::varchar as action, * \
      from ( \
        select * from \"{schema}\".\"{origin}_version#{id}\" where {geo_idx} \
    except \
        select * from versions.pgvscheckout(NULL::\"{schema}\".\"{origin}\",(select * from head), \'{geo_idx}\') \
       ) as foo) \
    \
    select row_number() OVER () AS rownum, * \
    from \
    (\
    select * from delete \
    union  \
    select * from insert) as foo").format(id=id,
                                          schema=mySchema,
                                          table=myTable,
                                          origin=myTable.replace(
                                              '_version', '').split('#')[0],
                                          geo_idx=geo_idx)

                    branch_name_sql = "select branch_text \
                           from versions.version_branch \
                           where branch_id = %s" % (myTable.split('#')[1])

                    branch_name = myDb.read(branch_name_sql)

                    myUri = QgsDataSourceURI(self.tools.layerUri(currentLayer))
                    myUri.setDataSource("", u"(%s\n)" % sql, geomCol, "",
                                        "rownum")
                    layer_name = "%s - %s (Diff to HEAD Revision)" % (
                        myTable.split('#')[0], branch_name['BRANCH_TEXT'][0])
                    layer = QgsVectorLayer(myUri.uri(), layer_name, "postgres")

                    mem_layer = self.tools.create_memory_layer(
                        layer, layer_name)

                    if mem_layer == None:
                        self.iface.messageBar().pushMessage(
                            'WARNING',
                            self.tr('Layer could not be loaded.'),
                            level=QgsMessageBar.INFO,
                            duration=3)

                    else:
                        userPluginPath = QFileInfo(
                            QgsApplication.qgisUserDbFilePath()).path(
                            ) + "/python/plugins/pgversion"
                        mem_layer.setRendererV2(None)

                        if geometryType == 0:
                            mem_layer.loadNamedStyle(userPluginPath +
                                                     "/legends/diff_point.qml")
                        elif geometryType == 1:
                            mem_layer.loadNamedStyle(
                                userPluginPath +
                                "/legends/diff_linestring.qml")
                        elif geometryType == 2:
                            mem_layer.loadNamedStyle(
                                userPluginPath + "/legends/diff_polygon.qml")

                        QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
                        self.iface.messageBar().pushMessage(
                            'INFO',
                            self.tr('Diff to HEAD revision was successful!'),
                            level=QgsMessageBar.INFO,
                            duration=3)

                    QApplication.restoreOverrideCursor()
                    self.logview_dialog.close()
                    return
        else:
            self.iface.messageBar().pushMessage(
                'INFO',
                self.tr('No differences to HEAD revision detected!'),
                level=QgsMessageBar.INFO,
                duration=3)
            return

    def doDrop(self):

        #      try:
        theLayer = self.iface.activeLayer()
        provider = theLayer.dataProvider()
        uri = provider.dataSourceUri()
        mySchema = QgsDataSourceURI(uri).schema()
        if len(mySchema) == 0:
            mySchema = 'public'
        myTable = QgsDataSourceURI(uri).table()

        if theLayer == None:
            QMessageBox.information(
                None, '', self.tr('Please select a layer for versioning'))
            return
        else:
            answer = QMessageBox.question(
                None, '',
                self.tr('are you sure to to drop pgvs from the table {0}?').
                format(mySchema + "." + myTable.replace('_version', '')),
                self.tr('Yes'), self.tr('No'))

            if answer == 0:
                if self.tools.isModified(theLayer):
                    QMessageBox.warning(None, self.tr('Warning'), \
                        self.tr('Layer %s has uncommited changes, please commit them or revert to HEAD revision' % (theLayer.name())))
                else:
                    myDb = self.tools.layerDB('doDrop', theLayer)
                    sql = "select versions.pgvsdrop('%s.%s') " % (
                        mySchema, myTable.replace('_version', ''))
                    result = myDb.read(sql)
                    myDb.close()

                    layer_name = theLayer.name()
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        theLayer.id())
                    self.iface.messageBar().pushMessage(
                        'INFO',
                        self.tr('Versioning for layer {0} dropped!').format(
                            layer_name),
                        level=QgsMessageBar.INFO,
                        duration=3)

    def doMakeBranch(self, name):
        sql = "select versions.pgvsmakebranch('%s', '%s') " % (
            mySchema, myTable.replace('_version', '').split('#')[0], name)
        QMessageBox.information(None, '', sql)

    def doHelp(self):
        helpUrl = QUrl()
        helpUrl.setUrl('file://%s/docs/help.html' % self.plugin_path)
        self.helpDialog.webView.load(helpUrl)
        self.helpDialog.show()

    def doAbout(self):
        self.about = About()
        self.about.show()
class CFSceneContextMenuMixin:
    " Encapsulates the context menu handling "

    def __init__(self):
        self.menu = None
        self.individualMenus = {}

        # Scene menu preparation
        self.sceneMenu = QMenu()
        self.sceneMenu.addAction(getIcon("filesvg.png"), "Save as SVG...", self.parent().onSaveAsSVG)
        self.sceneMenu.addAction(getIcon("filepdf.png"), "Save as PDF...", self.parent().onSaveAsPDF)
        self.sceneMenu.addAction(getIcon("filepixmap.png"), "Save as PNG...", self.parent().onSaveAsPNG)
        self.sceneMenu.addSeparator()
        self.sceneMenu.addAction(getIcon("copymenu.png"), "Copy to clipboard", self.parent().copyToClipboard)

        # Common menu for all the individually selected items
        self.commonMenu = QMenu()
        # self.commonMenu.addAction(
        #    getIcon( "cutmenu.png" ), "Cut (Ctrl+X)", self.onCut )
        # self.commonMenu.addAction(
        #    getIcon( "copymenu.png" ), "Copy (Ctrl+C)", self.onCopy )
        # self.commonMenu.addSeparator()
        # self.commonMenu.addAction(
        #    getIcon( "trash.png" ), "Delete (Del)", self.onDelete )

        # Non-comment common menu for the individually selected items
        self.nonCommentCommonMenu = QMenu()
        # self.nonCommentCommonMenu.addAction(
        #    getIcon( "customcolors.png" ), "Custom colors...",
        #    self.onCustomColors )
        # self.nonCommentCommonMenu.addAction(
        #    getIcon( "replacetitle.png" ), "Replace text...",
        #    self.onReplaceText )

        # Individual items specific menu: begin
        ifContextMenu = QMenu()
        ifContextMenu.addAction(getIcon("switchbranches.png"), "Switch branch layout", self.onSwitchIfBranch)

        self.individualMenus[IfCell] = ifContextMenu
        # Individual items specific menu: end

        # Menu for a group of selected items
        self.groupMenu = QMenu()
        # self.groupMenu.addAction(
        #    getIcon( "cfgroup.png" ), "Group...",
        #    self.onGroup )
        # self.groupMenu.addAction(
        #    getIcon( "customcolors.png" ), "Custom colors...",
        #    self.onCustomColors )
        # self.groupMenu.addSeparator()
        # self.groupMenu.addAction(
        #    getIcon( "trash.png" ), "Delete (Del)", self.onDelete )

        return

    def onContextMenu(self, event):
        " Triggered when a context menu should be shown "
        selectedItems = self.selectedItems()
        selectionCount = len(selectedItems)
        if selectionCount == 0:
            self.sceneMenu.popup(event.screenPos())
            return

        if selectionCount == 1:
            self.__buildIndividualMenu(selectedItems[0])
        else:
            self.__buildGroupMenu(selectedItems)
        self.menu.popup(event.screenPos())
        return

    def __buildIndividualMenu(self, item):
        " Builds a context menu for the given item "
        self.menu = QMenu()
        if type(item) in self.individualMenus:
            individualPart = self.individualMenus[type(item)]
            self.menu.addActions(individualPart.actions())
            self.menu.addSeparator()
        if not item.isComment():
            self.menu.addActions(self.nonCommentCommonMenu.actions())
            self.menu.addSeparator()
        self.menu.addActions(self.commonMenu.actions())

        # Note: if certain items need to be disabled then it should be done
        #       here

        return

    def __buildGroupMenu(self, items):
        " Builds a context menu for the group of items "
        self.menu = QMenu()
        self.menu.addActions(self.groupMenu.actions())

        # Note: if certain items need to be disabled then it should be done
        #       here

        return

    def onSwitchIfBranch(self):
        " If primitive should switch the branches "
        selectedItems = self.selectedItems()
        for item in selectedItems:
            if item.kind == CellElement.IF:
                item.switchBranches()
        return

    def onCustomColors(self):
        " Custom background and foreground colors "
        print "Custom colors"

    def onReplaceText(self):
        " Replace the code with a title "
        print "Replace title"

    def onDelete(self):
        " Delete the item "
        print "Delete"

    def onGroup(self):
        " Groups items into a single one "
        print "Group"

    def onCopy(self):
        print "Copy"

    def onCut(self):
        print "Cut"
Example #23
0
class QVertex:
    """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',
            'QVertex_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.dlg = QVertexDialog()
        self.dlg_coordcatalog = None
        self.dlg_geodata = None
        # Declare instance attributes
        self.actions = []
        #self.menu = self.tr(u'&qVertex')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QVertex')
        self.toolbar.setObjectName(u'QVertex')

    # 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('QVertex', 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 initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.menu = QMenu()
        self.menu.setTitle(u"Землеустройство")

        self.qvertex_createPoint = QAction(u"Создать точки", self.iface.mainWindow())
        self.qvertex_createPoint.setEnabled(True)
        #self.qvertex_createPoint.setIcon(QIcon(":/plugins/openland/icons/importkk.png"))

        self.qvertex_createCtalog = QAction(u"Создать ведомость координат", self.iface.mainWindow())
        self.qvertex_createCtalog.setEnabled(True)
        # self.qvertex_createCtalog.setIcon(QIcon(":/plugins/openland/icons/importkk.png"))

        self.qvertex_createGeodata = QAction(u"Создать выноску геоданных", self.iface.mainWindow())
        self.qvertex_createGeodata.setEnabled(True)
        # self.qvertex_createGeodata.setIcon(QIcon(":/plugins/openland/icons/importkk.png"))

        self.menu.addActions([self.qvertex_createPoint, self.qvertex_createCtalog, self.qvertex_createGeodata])
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()
        lastAction = actions[len(actions) - 1]
        menu_bar.insertMenu(lastAction, self.menu)
        #icon_path = ':/plugins/QVertex/icon.png'
        # self.add_action(
        #     icon_path,
        #     text=self.tr(u'Землеустройство'),
        #     callback=self.run,
        #     parent=self.iface.mainWindow())


        QObject.connect(self.qvertex_createPoint, SIGNAL("triggered()"), self.doCreatepoint)
        QObject.connect(self.qvertex_createCtalog, SIGNAL("triggered()"), self.doCreateCoordcatalog)
        QObject.connect(self.qvertex_createGeodata, SIGNAL("triggered()"), self.doCreateGeodata)


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


    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 doCreatepoint(self):
        f = CreatePoints(self.iface)
        f.Create()

    def doCreateCoordcatalog(self):
        if self.dlg_coordcatalog is None:
            self.dlg_coordcatalog = CreateCoordCatalog(self.iface)
            self.dlg_coordcatalog.setWindowModality(Qt.NonModal)
        self.dlg_coordcatalog.show()

    def doCreateGeodata(self):
        if self.dlg_geodata is None:
            self.dlg_geodata = CreateGeodata(self.iface)
            self.dlg_geodata.setWindowModality(Qt.NonModal)
        self.dlg_geodata.show()
Example #24
0
class Dummy:
    instance = None

    def __init__(self, iface):
        from createunbeffl import application as createunbeffl
        from importdyna import application as importdyna
        from exportdyna import application as exportdyna
        from linkflaechen import application as linkflaechen
        from tools import application as tools
        self.plugins = [
            createunbeffl.CreateUnbefFl(iface),
            importdyna.ImportFromDyna(iface),
            exportdyna.ExportToKP(iface),
            linkflaechen.LinkFl(iface),
            tools.QKanTools(iface)
        ]
        Dummy.instance = self

        # Plugins
        self.instances = []

        # QGIS
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.actions = []

        actions = self.iface.mainWindow().menuBar().actions()
        self.menu = None
        for menu in actions:
            if menu.text() == 'QKan':
                self.menu = menu.menu()
                self.menu_action = menu
                break

        self.toolbar = self.iface.addToolBar('QKan')
        self.toolbar.setObjectName('QKan')

    def initGui(self):
        # Create and insert QKan menu after the 3rd menu
        if self.menu is None:
            self.menu = QMenu('QKan', self.iface.mainWindow().menuBar())

            actions = self.iface.mainWindow().menuBar().actions()
            prepend = actions[3]
            self.menu_action = self.iface.mainWindow().menuBar().insertMenu(prepend, self.menu)

        # Calls initGui on all known QKan plugins
        for plugin in self.plugins:
            plugin.initGui()

        self.sort_actions()

    def sort_actions(self):
        # Finally sort all actions
        self.actions.sort(key=lambda x: x.text().lower())
        self.menu.clear()
        self.menu.addActions(self.actions)

    def unload(self):
        from qgis.utils import unloadPlugin
        # Unload all other instances
        for instance in self.instances:
            print('Unloading ', instance.name)
            if not unloadPlugin(instance.name):
                print('Failed to unload plugin!')

        # Remove entries from own menu
        for action in self.menu.actions():
            self.menu.removeAction(action)

        # Remove entries from Plugin menu and toolbar
        for action in self.actions:
            self.iface.removeToolBarIcon(action)

        # Remove the toolbar
        del self.toolbar

        # Remove menu
        self.iface.mainWindow().menuBar().removeAction(self.menu_action)

        # Call unload on all loaded plugins
        for plugin in self.plugins:
            plugin.unload()

    def register(self, instance):
        self.instances.append(instance)

        self.plugins += instance.plugins

    def unregister(self, instance):
        self.instances.remove(instance)

        for plugin in instance.plugins:
            self.plugins.remove(plugin)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.menu.addAction(action)

        self.actions.append(action)

        return action
Example #25
0
class Historize(QObject):
    """This class handles the initialization and calls of the menus"""
    def __init__(self, iface):
        QObject.__init__(self)

        self.iface = iface
        self.dbconn = DBConn(iface)
        plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(plugin_dir, 'i18n',
                                   'Historize_{}.qm'.format(locale))

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

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

    def initGui(self):
        self.menu = QMenu()
        self.menu.setTitle("Historize")

        self.layerMenu = QMenu()
        self.layerMenu.setTitle("Layer")

        # Create menu actions
        self.actionInitDB = QAction(self.tr(u"Initialize Database"),
                                    self.iface.mainWindow())
        self.actionInitLayer = QAction(self.tr(u"Initialize Layer"),
                                       self.iface.mainWindow())
        self.actionLayerUpdate = QAction(self.tr(u"Update Layer"),
                                         self.iface.mainWindow())
        self.actionLayerLoad = QAction(self.tr(u"Load Layer"),
                                       self.iface.mainWindow())
        self.actionAbout = QAction(self.tr(u"About"), self.iface.mainWindow())

        # Connect menu actions
        self.actionInitDB.triggered.connect(self.initialize_database)
        self.actionInitLayer.triggered.connect(self.initialize_layer)
        self.actionLayerLoad.triggered.connect(self.show_load_layer_dialog)
        self.actionLayerUpdate.triggered.connect(self.show_update_layer_dialog)
        self.actionAbout.triggered.connect(self.show_about_dialog)

        self.iface.legendInterface().currentLayerChanged.connect(
            self.enable_disable_gui)

        # Add actions to menu
        self.layerMenu.addActions([
            self.actionInitLayer, self.actionLayerLoad, self.actionLayerUpdate
        ])
        self.menu.addAction(self.actionInitDB)
        self.menu.addMenu(self.layerMenu)
        self.menu.addAction(self.actionAbout)
        self.menu.insertSeparator(self.actionAbout)
        menuBar = self.iface.mainWindow().menuBar()
        menuBar.addMenu(self.menu)

        # Disable unusable actions
        self.actionInitDB.setEnabled(False)
        self.actionInitLayer.setEnabled(False)
        self.actionLayerUpdate.setEnabled(False)
        self.actionLayerLoad.setEnabled(False)

    def unload(self):
        self.menu.deleteLater()

    def initialize_database(self):
        """Use Database info from layer and run historisation.sql on it."""

        selectedLayer = self.iface.activeLayer()
        provider = selectedLayer.dataProvider()

        if provider.name() != 'postgres':
            QMessageBox.warning(
                self.iface.mainWindow(), self.tr(u"Invalid Layer"),
                self.tr(u"Layer must be provided by postgres!"))
            return
        uri = QgsDataSourceURI(provider.dataSourceUri())
        conn = self.dbconn.connect_to_DB(uri)
        cur = conn.cursor()
        if conn is False:
            return

        result = QMessageBox.warning(
            self.iface.mainWindow(), self.tr(u"Initialize Historisation"),
            self.tr(u"Initialize historisation on this layers database?"),
            QMessageBox.No | QMessageBox.Yes)
        if result == QMessageBox.Yes:
            sqlPath = os.path.dirname(
                os.path.realpath(__file__)) + '/sql/historisierung.sql'
            try:
                # Ignore first three characters
                # which invalidate the SQL command
                cur.execute(open(sqlPath, "r").read())
                conn.commit()
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Success"),
                    self.tr(u"Database initialized successfully!"))
            except psycopg2.Error as e:
                conn.rollback()
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Error"),
                    self.tr(u"Couldn't initialize Database.\n" + e.message))
            conn.close()
            self.enable_disable_gui(selectedLayer)
        else:
            return

    def initialize_layer(self):
        """Use Layer info and run init() .sql query"""
        selectedLayer = self.iface.activeLayer()
        provider = selectedLayer.dataProvider()
        uri = QgsDataSourceURI(provider.dataSourceUri())
        conn = self.dbconn.connect_to_DB(uri)

        if conn is False:
            return

        result = QMessageBox.warning(
            self.iface.mainWindow(), self.tr(u"Initialize Layer"),
            self.tr(u"Are you sure you wish to proceed?"),
            QMessageBox.No | QMessageBox.Yes)
        if result == QMessageBox.Yes:
            # Get SQL vars
            hasGeometry = selectedLayer.hasGeometryType()
            schema = uri.schema()
            table = uri.table()

            execute = SQLExecute(self.iface, self.iface.mainWindow(), uri)
            success, msg = execute.Init_hist_tabs(hasGeometry, schema, table)
            if success:
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Success"),
                    self.tr(u"Layer successfully initialized!"))
            else:
                QMessageBox.warning(self.iface.mainWindow(), self.tr(u"Error"),
                                    self.tr(u"Initialization failed!\n" + msg))
            self.enable_disable_gui(selectedLayer)
        else:
            return

    def show_update_layer_dialog(self):
        """Open ImportUpdate dialog"""
        self.updateDialog = ImportUpdateDialog(self.iface)
        self.updateDialog.show()

    def show_load_layer_dialog(self):
        """Open selectDate dialog"""
        self.dateDialog = SelectDateDialog(self.iface)
        self.dateDialog.show()

    def show_about_dialog(self):
        """Show About dialog"""
        self.aboutDialog = AboutDialog()
        self.aboutDialog.show()

    def enable_disable_gui(self, layer):
        """Enable/Disable menu options based on selected layer"""
        self.actionInitDB.setEnabled(False)
        self.layerMenu.setEnabled(False)
        self.actionInitLayer.setEnabled(False)
        self.actionLayerUpdate.setEnabled(False)
        self.actionLayerLoad.setEnabled(False)

        selectedLayer = self.iface.activeLayer()
        if selectedLayer:
            provider = layer.dataProvider()

            if provider.name() == "postgres":
                self.actionInitDB.setEnabled(True)
                uri = QgsDataSourceURI(provider.dataSourceUri())
                execute = SQLExecute(self.iface, self.iface.mainWindow(), uri)
                historised = execute.check_if_historised(
                    uri.schema(),
                    self.iface.activeLayer().name())
                db_initialized = execute.db_initialize_check(uri.schema())

                if db_initialized:
                    self.actionInitDB.setEnabled(False)
                    self.layerMenu.setEnabled(True)
                else:
                    self.layerMenu.setEnabled(False)

                if historised:
                    self.actionLayerUpdate.setEnabled(True)
                    self.actionLayerLoad.setEnabled(True)
                else:
                    self.actionInitLayer.setEnabled(True)
Example #26
0
class fToolsPlugin:

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.updateThemeIcons("theme")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def doEliminate(self):
        d = doEliminate.Dialog(self.iface)
        d.exec_()
    def __init__(self, AUTO):
        ' Initialize QWidget inside MyMainWindow '
        super(MyMainWindow, self).__init__()
        QWidget.__init__(self)
        self.auto = AUTO
        self.statusBar().showMessage('               {}'.format(__doc__))
        self.setStyleSheet('QStatusBar{color:grey;}')
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont('Ubuntu Light', 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(),
                            QDesktopWidget().screenGeometry().height())

        self.base = path.abspath(path.join(getcwd(), str(datetime.now().year)))

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # process
        self.process1 = None
        self.process2 = None
        self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw'
        self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}'
        self.process3 = QProcess(self)
        #self.process3.finished.connect(self.on_process3_finished)
        #self.process3.error.connect(self.on_process3_error)

        self.cmd3 = ('nice -n 20 ' +
          'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"')
        self.actual_file = ''

        # re starting timers, one stops, one starts
        self.timerFirst = QTimer(self)
        self.timerFirst.timeout.connect(self.end)
        self.timerSecond = QTimer(self)
        self.timerSecond.timeout.connect(self.run)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None
        print((' INFO: Proxy Auto-Config as ' + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}')
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setTabsClosable(False)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        self.dock4 = QDockWidget()
        self.dock5 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5):
            a.setWindowModality(Qt.NonModal)
            # a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__
                             if a.windowTitle() == '' else a.windowTitle())
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"),
                                   'Double Click Me')

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
        qaqq.setShortcut('Ctrl+Q')
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"),
                        'AutoCenter AutoResize', self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"),
                        'View Date and Time', self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self)
        qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call(
            'xdg-open mailto:' + '*****@*****.**'.decode('rot13'),
            shell=True) else ' ERROR ')
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self)
        if KDE:
            qaslf.triggered.connect(
                                KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget,
            __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (',
            __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep
            ))))
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"),
                        'Set GUI Font', self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(lambda:
            self.setStyleSheet(''.join((
                '*{font-family:', str(font.toString()), '}'))
                if KFontDialog.getFont(font)[0] == QDialog.Accepted else ''))
        else:
            qafnt.triggered.connect(lambda:
                self.setStyleSheet(''.join(('*{font-family:',
                            str(QFontDialog.getFont()[0].toString()), '}'))))
        qasrc = QAction(QIcon.fromTheme("applications-development"),
                        'View Source Code', self)
        qasrc.triggered.connect(lambda:
                            call('xdg-open {}'.format(__file__), shell=True))
        qakb = QAction(QIcon.fromTheme("input-keyboard"),
                       'Keyboard Shortcuts', self)
        qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget,
                               'Keyboard Shortcuts', ' Ctrl+Q = Quit '))
        qapic = QAction(QIcon.fromTheme("camera-photo"),
                        'Take a Screenshot', self)
        qapic.triggered.connect(lambda: QPixmap.grabWindow(
            QApplication.desktop().winId()).save(QFileDialog.getSaveFileName(
            self.mainwidget, " Save Screenshot As ...", path.expanduser("~"),
            ';;(*.png) PNG', 'png')))
        qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self)
        qatb.triggered.connect(lambda: self.toolbar.hide()
                if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("zoom-in"),
                       'Switch ToolBar Icon Size', self)
        qati.triggered.connect(lambda:
            self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4))
        qasb = QAction(QIcon.fromTheme("preferences-other"),
                       'Toggle Tabs Bar', self)
        qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide()
                               if self.mainwidget.tabBar().isVisible() is True
                               else self.mainwidget.tabBar().show())
        qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self)
        qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip()))
        qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self)
        qapy.triggered.connect(lambda: open_new_tab('http://python.org/about'))
        qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors',
                        self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(lambda:
                self.setStyleSheet(''.join(('* { background-color: ',
                                            str(color.name()), '}')))
                if KColorDialog.getColor(color, self) else '')
        else:
            qacol.triggered.connect(lambda: self.setStyleSheet(''.join((
                ' * { background-color: ', str(QColorDialog.getColor().name()),
                ' } '))))
        qatit = QAction(QIcon.fromTheme("preferences-system"),
                        'Set the App Window Title', self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
            qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf,
            qaqt, qakde, qapy, qabug))
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu('&File').addActions((qaqq, ))
        menu.addMenu('&Window').addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim,
                                              qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali,
                                          qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            ' quick and dirty custom context menu '
            menu = QMenu()
            menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
                qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali,
                qaslf, qaqt, qakde, qapy, qabug))
            menu.exec_(self.mapToGlobal(point))
        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            ' widget tuple passed as argument should be checked as ON '
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            ' widget tuple passed as argument should have filled background '
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

        #######################################################################

        # dock 1
        QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize(
               self.dock3.size().width() / 4, 25)
        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)

        self.spec = QPushButton(self)
        self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.spec.setMinimumSize(self.spec.size().width(), 250)
        self.spec.setFlat(True)
        self.spec.clicked.connect(self.spectro)

        self.clock = QLCDNumber()
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.setMinimumSize(self.clock.size().width(), 50)
        self.clock.setNumDigits(25)
        self.timer1 = QTimer(self)
        self.timer1.timeout.connect(lambda: self.clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        self.timer1.start(1000)
        self.clock.setToolTip(datetime.now().strftime("%c %x"))
        self.clock.setCursor(QCursor(Qt.CrossCursor))

        self.diskBar = QProgressBar()
        self.diskBar.setMinimum(0)
        self.diskBar.setMaximum(statvfs(HOME).f_blocks *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setValue(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setToolTip(str(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free')

        self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__,
            ', version', __version__, __license__, ' <br> by ', __author__,
            ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>',
            'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo')))

        self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record')
        self.rec.setMinimumSize(self.rec.size().width(), 50)
        self.rec.clicked.connect(self.go)  # self.run

        self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.stop.clicked.connect(self.end)

        self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.kill.clicked.connect(self.killer)

        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;"> Spectro'), self.spec,
            QLabel('<b style="color:white;"> Time '), self.clock,
            QLabel('<b style="color:white;"> Disk '), self.diskBar,
            QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback,
            QLabel('<b style="color:white;"> Record '), self.rec, self.stop,
            self.kill):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)

        self.slider = QSlider(self)
        self.slid_l = QLabel(self.slider)
        self.slider.setCursor(QCursor(Qt.OpenHandCursor))
        self.slider.sliderPressed.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.slider.sliderReleased.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.OpenHandCursor)))
        self.slider.valueChanged.connect(lambda:
                            self.slider.setToolTip(str(self.slider.value())))
        self.slider.valueChanged.connect(lambda: self.slid_l.setText(
                    '<h2 style="color:white;">{}'.format(self.slider.value())))
        self.slider.setMinimum(10)
        self.slider.setMaximum(99)
        self.slider.setValue(30)
        self.slider.setOrientation(Qt.Vertical)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setTickInterval(2)
        self.slider.setSingleStep(10)
        self.slider.setPageStep(10)

        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b style="color:white;">MINUTES of recording'), self.slider,
            QLabel('<b style="color:white;"> Default: 30 Min')):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        try:
            self.label2 = QLabel(getoutput('sox --version', shell=True))
            self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25])
            self.label6 = QLabel(str(getoutput('oggenc --version', shell=True)))
        except:
            print(''' ERROR: No SOX, OGGenc avaliable !
                  ( sudo apt-get install vorbis-tools sox alsa-utils ) ''')
            exit()

        self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"),
                                   'OGG --> ZIP')
        self.button5.clicked.connect(lambda: make_archive(
            str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...",
            getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip",
            path.abspath(path.join(getcwd(), str(datetime.now().year)))))

        self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files')
        self.button1.clicked.connect(lambda:
                                     call('xdg-open ' + getcwd(), shell=True))

        self.button0 = QPushButton(
            QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF')
        self.button0.clicked.connect(lambda:
            call('sleep 3 ; xset dpms force off', shell=True))

        vboxg3 = QVBoxLayout(group3)
        for each_widget in (
            QLabel('<b style="color:white;"> OGG Output Codec '), self.label6,
            QLabel('<b style="color:white;"> Raw Record Backend '), self.label4,
            QLabel('<b style="color:white;"> Helper Libs '), self.label2,
            QLabel('<b style="color:white;"> OGG ZIP '), self.button5,
            QLabel('<b style="color:white;"> Files '), self.button1,
            QLabel('<b style="color:white;"> LCD '), self.button0):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize(
               self.dock2.size().width() / 4, 25)
        try:
            audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA",
                Solid.AudioInterface.OpenSoundSystem: "Open Sound",
                Solid.AudioInterface.UnknownAudioDriver: "Unknown?"}
            audioInterfaceTypeStr = {
                Solid.AudioInterface.AudioControl: "Control",
                Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?",
                Solid.AudioInterface.AudioInput: "In",
                Solid.AudioInterface.AudioOutput: "Out"}
            soundcardTypeStr = {
                Solid.AudioInterface.InternalSoundcard: "Internal",
                Solid.AudioInterface.UsbSoundcard: "USB3",
                Solid.AudioInterface.FirewireSoundcard: "FireWire",
                Solid.AudioInterface.Headset: "Headsets",
                Solid.AudioInterface.Modem: "Modem"}
            display = QTreeWidget()
            display.setAlternatingRowColors(True)
            display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"])
            display.setColumnWidth(0, 350)
            display.setColumnWidth(1, 350)
            display.setColumnWidth(3, 75)
            # retrieve a list of Solid.Device for this machine
            deviceList = Solid.Device.allDevices()
            # filter the list of all devices and display matching results
            # note that we never create a Solid.AudioInterface object, but
            # receive one from the 'asDeviceInterface' call
            for device in deviceList:
                if device.isDeviceInterface(
                                         Solid.DeviceInterface.AudioInterface):
                    audio = device.asDeviceInterface(
                            Solid.DeviceInterface.AudioInterface)
                    devtype = audio.deviceType()
                    devstr = []
                    for key in audioInterfaceTypeStr:
                        flag = key & devtype
                        if flag:
                            devstr.append(audioInterfaceTypeStr[key])
                    QTreeWidgetItem(display, [device.product(), audio.name(),
                        audioDriverStr[audio.driver()], "/".join(devstr),
                        soundcardTypeStr[audio.soundcardType()]])
            self.dock2.setWidget(display)
        except:
            self.dock2.setWidget(QLabel(""" <center style='color:white;'>
            <h1>:(<br>ERROR: Please, install PyKDE !</h1><br>
            <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>"""))

        ## dock 3
        QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize(
               self.dock3.size().width() / 4, 25)
        self.fileView = QColumnView()
        self.fileView.updatePreviewWidget.connect(self.play)
        self.fileView.setToolTip(' Browse and Preview Files ')
        self.media = None
        self.model = QDirModel()
        self.fileView.setModel(self.model)
        self.dock3.setWidget(self.fileView)

        # dock4
        QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize(
               self.dock4.size().width() / 4, 25)
        self.group4 = QGroupBox()
        self.group4.setTitle(__doc__)

        self.combo0 = QComboBox()
        self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE',
          'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE'])

        self.combo1 = QComboBox()
        self.combo1.addItems(['1', '-1', '0', '2', '3', '4',
                              '5', '6', '7', '8', '9', '10'])

        self.combo2 = QComboBox()
        self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16'])

        self.combo3 = QComboBox(self)
        self.combo3.addItems(['MONO', 'STEREO', 'Surround'])

        self.combo4 = QComboBox()
        self.combo4.addItems(['44100', '96000', '48000', '32000',
                              '22050', '16000', '11025', '8000'])

        self.combo5 = QComboBox(self)
        self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13',
            '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0'])

        self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic')

        self.chckbx0 = QCheckBox('Disable Software based Volume Control')

        self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix')

        self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files')

        self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound')

        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (
            QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1,
            QLabel('<b style="color:white;"> Sound Record Format'), self.combo0,
            QLabel('<b style="color:white;"> Sound KBps '), self.combo2,
            QLabel('<b style="color:white;"> Sound Channels '), self.combo3,
            QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4,
            QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0,
            QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1,
            QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2,
            QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3,
            QLabel('<b style="color:white;"> CPUs Priority'), self.combo5,
            QLabel('<b style="color:white;">Nepomuk Semantic User Experience'),
            self.nepochoose):
            vboxg4.addWidget(each_widget)
        self.dock4.setWidget(self.group4)

        # dock 5
        QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5
               ).resize(self.dock5.size().width() / 3, 25)
        self.group5 = QGroupBox()
        self.group5.setTitle(__doc__)

        self.dial = QDial()
        self.dial.setCursor(QCursor(Qt.OpenHandCursor))
        self.di_l = QLabel(self.dial)
        self.di_l.resize(self.dial.size() / 8)
        self.dial.sliderPressed.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.dial.sliderReleased.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.OpenHandCursor)))
        self.dial.valueChanged.connect(lambda:
                            self.dial.setToolTip(str(self.dial.value())))
        self.dial.valueChanged.connect(lambda: self.di_l.setText(
                    '<h1 style="color:white;">{}'.format(self.dial.value())))
        self.dial.setValue(0)
        self.dial.setMinimum(-999)
        self.dial.setMaximum(999)
        self.dial.setSingleStep(100)
        self.dial.setPageStep(100)
        self.dial.setWrapping(False)
        self.dial.setNotchesVisible(True)

        self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run')
        self.defo.setMinimumSize(self.defo.size().width(), 50)
        self.defo.clicked.connect(lambda: self.process3.start(
            'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "'
            .format(self.dial.value()) if int(self.dial.value()) != 0 else
            'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "'
            .format(' 3,2500,3 3,-2500,3 ' * 999)))

        self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.qq.clicked.connect(self.process3.kill)

        self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.die.clicked.connect(lambda: call('killall rec', shell=True))

        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.dial, self.defo, self.qq, self.die):
            vboxg5.addWidget(each_widget)
        self.dock5.setWidget(self.group5)

        # configure some widget settings
        must_be_checked((self.nepochoose, self.chckbx1,
                         self.chckbx2, self.chckbx3))
        must_have_tooltip((self.label2, self.label4, self.label6, self.combo0,
            self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4,
            self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3,
            self.rec, self.stop, self.defo, self.qq, self.die, self.kill,
            self.button0, self.button1, self.button5))
        must_autofillbackground((self.clock, self.label2, self.label4,
            self.label6, self.nepochoose, self.chckbx0, self.chckbx1,
            self.chckbx2, self.chckbx3))
        must_glow((self.rec, self.dial, self.combo1))
        self.nepomuk_get('testigo')
        if self.auto is True:
            self.go()
Example #28
0
class CFSceneContextMenuMixin:
    " Encapsulates the context menu handling "

    def __init__(self):
        self.menu = None
        self.individualMenus = {}

        # Scene menu preparation
        self.sceneMenu = QMenu()
        self.sceneMenu.addAction(getIcon('filesvg.png'), 'Save as SVG...',
                                 self.parent().onSaveAsSVG)
        self.sceneMenu.addAction(getIcon('filepdf.png'), 'Save as PDF...',
                                 self.parent().onSaveAsPDF)
        self.sceneMenu.addAction(getIcon('filepixmap.png'), 'Save as PNG...',
                                 self.parent().onSaveAsPNG)
        self.sceneMenu.addSeparator()
        self.sceneMenu.addAction(getIcon('copymenu.png'), 'Copy to clipboard',
                                 self.parent().copyToClipboard)

        # Common menu for all the individually selected items
        self.commonMenu = QMenu()
        #self.commonMenu.addAction(
        #    getIcon( "cutmenu.png" ), "Cut (Ctrl+X)", self.onCut )
        #self.commonMenu.addAction(
        #    getIcon( "copymenu.png" ), "Copy (Ctrl+C)", self.onCopy )
        #self.commonMenu.addSeparator()
        #self.commonMenu.addAction(
        #    getIcon( "trash.png" ), "Delete (Del)", self.onDelete )

        # Non-comment common menu for the individually selected items
        self.nonCommentCommonMenu = QMenu()
        #self.nonCommentCommonMenu.addAction(
        #    getIcon( "customcolors.png" ), "Custom colors...",
        #    self.onCustomColors )
        #self.nonCommentCommonMenu.addAction(
        #    getIcon( "replacetitle.png" ), "Replace text...",
        #    self.onReplaceText )

        # Individual items specific menu: begin
        ifContextMenu = QMenu()
        ifContextMenu.addAction(getIcon("switchbranches.png"),
                                "Switch branch layout", self.onSwitchIfBranch)

        self.individualMenus[IfCell] = ifContextMenu
        # Individual items specific menu: end

        # Menu for a group of selected items
        self.groupMenu = QMenu()
        #self.groupMenu.addAction(
        #    getIcon( "cfgroup.png" ), "Group...",
        #    self.onGroup )
        #self.groupMenu.addAction(
        #    getIcon( "customcolors.png" ), "Custom colors...",
        #    self.onCustomColors )
        #self.groupMenu.addSeparator()
        #self.groupMenu.addAction(
        #    getIcon( "trash.png" ), "Delete (Del)", self.onDelete )

        return

    def onContextMenu(self, event):
        " Triggered when a context menu should be shown "
        selectedItems = self.selectedItems()
        selectionCount = len(selectedItems)
        if selectionCount == 0:
            self.sceneMenu.popup(event.screenPos())
            return

        if selectionCount == 1:
            self.__buildIndividualMenu(selectedItems[0])
        else:
            self.__buildGroupMenu(selectedItems)
        self.menu.popup(event.screenPos())
        return

    def __buildIndividualMenu(self, item):
        " Builds a context menu for the given item "
        self.menu = QMenu()
        if type(item) in self.individualMenus:
            individualPart = self.individualMenus[type(item)]
            self.menu.addActions(individualPart.actions())
            self.menu.addSeparator()
        if not item.isComment():
            self.menu.addActions(self.nonCommentCommonMenu.actions())
            self.menu.addSeparator()
        self.menu.addActions(self.commonMenu.actions())

        # Note: if certain items need to be disabled then it should be done
        #       here

        return

    def __buildGroupMenu(self, items):
        " Builds a context menu for the group of items "
        self.menu = QMenu()
        self.menu.addActions(self.groupMenu.actions())

        # Note: if certain items need to be disabled then it should be done
        #       here

        return

    def onSwitchIfBranch(self):
        " If primitive should switch the branches "
        selectedItems = self.selectedItems()
        for item in selectedItems:
            if item.kind == CellElement.IF:
                item.switchBranches()
        return

    def onCustomColors(self):
        " Custom background and foreground colors "
        print "Custom colors"

    def onReplaceText(self):
        " Replace the code with a title "
        print "Replace title"

    def onDelete(self):
        " Delete the item "
        print "Delete"

    def onGroup(self):
        " Groups items into a single one "
        print "Group"

    def onCopy(self):
        print "Copy"

    def onCut(self):
        print "Cut"
Example #29
0
    def __init__(self,parent):
        QToolBar.__init__(self,parent)
        self.parent = parent
        self.action_NewProject = QAction(Icons.newprj, 'Project', self)
        self.action_NewProject.triggered.connect(self.parent.treeWidget.newProject)
        self.action_NewProject.setToolTip("Create a New Project")

        self.action_Open = QAction(Icons.open, 'Open', self)
        self.action_Open.triggered.connect(self.parent.fileOpen)
        self.action_Open.setToolTip("Open File")

        self.action_Save = QAction(Icons.save, 'Save', self)
        self.action_Save.setShortcut('Ctrl+S')
        self.action_Save.triggered.connect(self.parent.fileSave)
        self.action_Save.setToolTip("Save Current File")

        self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self)
        self.action_SaveAll.setShortcut('Ctrl+A')
        self.action_SaveAll.triggered.connect(self.parent.fileSaveAll)
        self.action_SaveAll.setToolTip("Save All Files")
        
        
        
        self.action_Build = QAction(Icons.thread_view, 'Build', self)
        self.action_Build.setShortcut('Ctrl+B')
        self.action_Build.triggered.connect(self.parent.build_project)
        self.action_Debug = QAction(Icons.debug_exec, 'Debug', self)
        self.action_Refresh = QAction(Icons.refresh_tab, 'Refresh', self)
        self.action_Refresh.triggered.connect(self.parent.treeWidget.refreshCurrentProject)
        
        self.action_Run = QAction(Icons.run, 'Run', self)
        self.action_Run.setShortcut('Ctrl+R')
        self.action_Run.triggered.connect(self.parent.adb.run)
        self.action_RunFile = QAction(Icons.go, 'Cmd', self)
        self.action_RunFile.triggered.connect(self.parent.openCommand)
        self.parent.runButton.clicked.connect(self.parent.command.setCmdLine)
        self.action_Stop = QAction(Icons.stop, 'Stop', self)
        self.action_Stop.setShortcut('Ctrl+Q')
        self.action_Stop.triggered.connect(self.parent.adb.stop)
        self.action_Design = QAction(Icons.color_palette, 'Design', self)
        self.action_Design.triggered.connect(self.parent.design)
        self.action_Level = QAction(Icons.cmpC_pal, 'Level', self)
        self.action_Level.triggered.connect(self.parent.level)
        self.action_Todo = QAction(Icons.task_set, 'Todo', self)
        self.action_Todo.triggered.connect(self.parent.todo)
        self.action_Help = QAction(Icons.toc_open, 'Help', self)
        self.action_Help.triggered.connect(self.parent.help)
        
        men = QMenu()
        
        #Threshold Slider
        self.threshSlider = QSlider()
        self.threshSlider.setTickPosition(QSlider.TicksLeft)
        self.threshSlider.setOrientation(Qt.Horizontal)
        self.threshSlider.setValue(config.thresh())
        self.threshSlider.setMinimum(0)
        self.threshSlider.setMaximum(5)
        self.threshSlider.valueChanged.connect(self.parent.setThreshold)
        self.threshSliderAction = QWidgetAction(men)
        self.threshSliderAction.setDefaultWidget(self.threshSlider)
        
        #TabsWidth Slider
        self.tabsSlider = QSlider()
        self.tabsSlider.setTickPosition(QSlider.TicksLeft)
        self.tabsSlider.setOrientation(Qt.Horizontal)
        self.tabsSlider.setValue(config.tabwidth())
        self.tabsSlider.setMinimum(0)
        self.tabsSlider.setMaximum(8)
        self.tabsSlider.valueChanged.connect(self.parent.setTabWidth)
        self.tabsSliderAction = QWidgetAction(men)
        self.tabsSliderAction.setDefaultWidget(self.tabsSlider)
        
        #iconSize Slider
        self.iconSlider = QSlider()
        self.iconSlider.setTickPosition(QSlider.TicksLeft)
        self.iconSlider.setOrientation(Qt.Horizontal)
        self.iconSlider.setValue(config.iconSize())
        self.iconSlider.setMinimum(16)
        self.iconSlider.setMaximum(32)
        self.iconSlider.setSingleStep(2)
        self.iconSlider.valueChanged.connect(self.setIcon)
        self.iconSliderAction = QWidgetAction(men)
        self.iconSliderAction.setDefaultWidget(self.iconSlider)
        
        '''Font Button'''
        self.fontCombo = QFontComboBox()
        self.fontCombo.currentFontChanged.connect(self.parent.setFont)
        self.fontCombo.setCurrentFont(QFont(config.fontName()))
        self.fontComboMenu = QWidgetAction(men)
        self.fontComboMenu.setDefaultWidget(self.fontCombo)
        
        '''Font Size'''
        self.fontSizeCombo = QComboBox()
        for size in range(1,40):
            self.fontSizeCombo.addItem(str(size))
        self.fontSizeCombo.setCurrentIndex(config.fontSize())
        self.fontSizeCombo.currentIndexChanged.connect(self.parent.setFontSize)
        self.fontSizeComboMenu = QWidgetAction(men)
        self.fontSizeComboMenu.setDefaultWidget(self.fontSizeCombo)
        
        
        action_explorer = QAction("Show Explorer",self)
        action_explorer.triggered.connect(self.parent.exp)
        action_console = QAction("Show Console",self)
        action_console.triggered.connect(self.parent.cmd)
        action_designer = QAction("Show Designer",self)
        action_designer.triggered.connect(self.parent.design)
        action_Indentation = QAction("Indentation Guides",self)
        action_Indentation.triggered.connect(self.parent.setIndent)
        action_WhiteSpace = QAction("Show WhiteSpace",self)
        action_WhiteSpace.triggered.connect(self.parent.setWhiteSpace)
        action_EndLine = QAction("Show End of Lines",self)
        action_EndLine.triggered.connect(self.parent.setEndLine)
        action_Margin = QAction("Line Numbers",self)
        action_Margin.triggered.connect(self.parent.setMargin)
        action_ToolLabel = QAction("Tool Labels",self)
        action_ToolLabel.triggered.connect(self.setToolLabel)
        action_Android = QAction(Icons.android,'Android', self)
        action_Android.triggered.connect(self.parent.android)
        action_Ant = QAction(Icons.ant_view,'Ant', self)
        action_Ant.triggered.connect(self.parent.antt)
        action_Squirrel = QAction(Icons.nut,'Squirrel', self)
        action_Squirrel.triggered.connect(self.parent.squirrel)
        action_Ios1 = QAction(Icons.ios,'iOS', self)
        action_Update = QAction("Update",self)
        action_Update.triggered.connect(self.parent.update)
        
        
        '''Encoding'''
        encodingGroup = QActionGroup(self)
        encodingGroup.setExclusive(True)
        action_Ascii = QAction("Ascii",encodingGroup)
        action_Ascii.setCheckable(True)
        action_Unicode = QAction("Unicode",encodingGroup)
        action_Unicode.setCheckable(True)
        encodingGroup.addAction(action_Ascii)
        encodingGroup.addAction(action_Unicode)
        encodingGroup.selected.connect(self.parent.setEncoding)
        if(config.encoding() == Encoding.ASCII):
            action_Ascii.setChecked(True)
        else:
            action_Unicode.setChecked(True)
        men.addAction(action_Android)
        men.addAction(action_Ant)
        men.addAction(action_Squirrel)
        men.addAction(action_Ios1)
        men.addAction(action_Update)
        men.addSeparator()
        men.addAction(action_explorer)
        men.addAction(action_console)
        men.addAction(action_designer)
        men.addAction(action_Indentation)
        men.addAction(action_WhiteSpace)
        men.addAction(action_EndLine)
        men.addAction(action_Margin)
        men.addAction(action_ToolLabel)
        men.addSeparator()
        men.addActions(encodingGroup.actions())
        men.addSeparator()
        head_font = QLabel("Font---------------------")
        fnt = head_font.font()
        fnt.setBold(True)
        head_font.setFont(fnt)
        head_fontWidgetAction = QWidgetAction(men)
        head_fontWidgetAction.setDefaultWidget(head_font)
        men.addAction(head_fontWidgetAction)
        men.addAction(self.fontComboMenu)
        men.addAction(self.fontSizeComboMenu)
        men.addSeparator()
        men.addAction(QAction("TabWidth",self))
        men.addAction(self.tabsSliderAction)
        men.addSeparator()
        men.addAction(QAction("Threshold",self))
        men.addAction(self.threshSliderAction)
        #men.addAction(QAction("Icon Size",self))
        #men.addAction(self.iconSliderAction)
        
        self.action_Options = QAction(Icons.emblem_system, 'Options', self)
        self.action_Options.setMenu(men)
        
        
        self.action_Full = QAction(Icons.fullscreen, 'Full', self)
        self.action_Full.setShortcut('Shift+Enter')
        self.action_Full.triggered.connect(self.parent.full)
        
        self.modeGroup = QActionGroup(self)
        self.modeGroup.setExclusive(True)
        self.modeGroup.selected.connect(self.parent.setMode)
        self.action_Squirrel = QAction(Icons.nut, 'Squ', self.modeGroup)
        self.action_Squirrel.setCheckable(True)
        self.action_Emo = QAction(Icons.emo, 'Emo', self.modeGroup)
        self.action_Emo.setCheckable(True)
        self.action_And = QAction(Icons.android, 'Android', self.modeGroup)
        self.action_And.setCheckable(True)
        self.action_Ios = QAction(Icons.ios, 'ios', self.modeGroup)
        self.action_Ios.setCheckable(True)
        self.modeGroup.addAction(self.action_Squirrel)
        self.modeGroup.addAction(self.action_Emo)
        self.modeGroup.addAction(self.action_And)
        self.modeGroup.addAction(self.action_Ios)

        
        self.action_Style = QAction(Icons.style, 'Style', self)
        men1 = QMenu()
        self.styleslist = []
        self.style1 = QAction("All Hallow's Eve",self)
        self.style1.triggered.connect(lambda:self.parent.style_clicked(1))
        self.style1.setCheckable(True)
        self.style2 = QAction("Amy",self)
        self.style2.triggered.connect(lambda:self.parent.style_clicked(2))
        self.style2.setCheckable(True)
        self.style3 = QAction("Aptana Studio",self)
        self.style3.triggered.connect(lambda:self.parent.style_clicked(3))
        self.style3.setCheckable(True)
        self.style4 = QAction("Bespin",self)
        self.style4.triggered.connect(lambda:self.parent.style_clicked(4))
        self.style4.setCheckable(True)
        self.style5 = QAction("Blackboard",self)
        self.style5.triggered.connect(lambda:self.parent.style_clicked(5))
        self.style5.setCheckable(True)
        self.style6 = QAction("Choco",self)
        self.style6.triggered.connect(lambda:self.parent.style_clicked(6))
        self.style6.setCheckable(True)
        self.style7 = QAction("Cobalt",self)
        self.style7.triggered.connect(lambda:self.parent.style_clicked(7))
        self.style7.setCheckable(True)
        self.style8 = QAction("Dawn",self)
        self.style8.triggered.connect(lambda:self.parent.style_clicked(8))
        self.style8.setCheckable(True)
        self.style9 = QAction("Eclipse",self)
        self.style9.triggered.connect(lambda:self.parent.style_clicked(9))
        self.style9.setCheckable(True)
        self.styleslist.append(self.style1)
        self.styleslist.append(self.style2)
        self.styleslist.append(self.style3)
        self.styleslist.append(self.style4)
        self.styleslist.append(self.style5)
        self.styleslist.append(self.style6)
        self.styleslist.append(self.style7)
        self.styleslist.append(self.style8)
        self.styleslist.append(self.style9)
        men1.addActions(self.styleslist)
        self.action_Style.setMenu(men1)
        self.styleslist[self.parent.styleIndex].setChecked(True)

        self.action_Stop.setDisabled(True)
        self.setToolLabel()
        self.setAllowedAreas(Qt.AllToolBarAreas)
        #self.setFixedHeight(40)
        #self.setIconSize(QSize(config.iconSize(),config.iconSize()))

        self.addAction(self.action_NewProject)
        self.addAction(self.action_Open)
        self.addAction(self.action_Save)
        self.addAction(self.action_SaveAll)
        #self.addAction(self.action_Refresh)
        self.addSeparator()
        self.addAction(self.action_Build)
        self.addAction(self.action_Run)
        self.addAction(self.action_RunFile)
        self.addAction(self.action_Stop)
        self.addAction(self.action_Debug)
        self.addSeparator()
        self.addAction(self.action_Design)
        self.addAction(self.action_Level)
        self.addAction(self.action_Todo)
        self.addAction(self.action_Options)
        self.addAction(self.action_Style)
        self.addSeparator()
        self.addAction(self.action_Help)
        self.addAction(self.action_Full)
        self.addSeparator()
        self.addActions(self.modeGroup.actions())
        if(config.mode() == 0):
            self.action_Squirrel.setChecked(True)
        elif(config.mode() == 1):
            self.action_Emo.setChecked(True)
        elif(config.mode() == 2):
            self.action_And.setChecked(True)
        elif(config.mode() == 3):
            self.action_Ios.setChecked(True)
Example #30
0
 def initOptionsMenu(self):
     men = QMenu()
     
     #Threshold Slider
     self.threshSlider = QSlider()
     self.threshSlider.setTickPosition(QSlider.TicksLeft)
     self.threshSlider.setOrientation(Qt.Horizontal)
     self.threshSlider.setValue(config.thresh())
     self.threshSlider.setMinimum(0)
     self.threshSlider.setMaximum(5)
     self.threshSlider.valueChanged.connect(self.parent.setThreshold)
     self.threshSliderAction = QWidgetAction(men)
     self.threshSliderAction.setDefaultWidget(self.threshSlider)
     
     #TabsWidth Slider
     self.tabsSlider = QSlider()
     self.tabsSlider.setTickPosition(QSlider.TicksLeft)
     self.tabsSlider.setOrientation(Qt.Horizontal)
     self.tabsSlider.setValue(config.tabwidth())
     self.tabsSlider.setMinimum(0)
     self.tabsSlider.setMaximum(8)
     self.tabsSlider.valueChanged.connect(self.parent.setTabWidth)
     self.tabsSliderAction = QWidgetAction(men)
     self.tabsSliderAction.setDefaultWidget(self.tabsSlider)
     
     #iconSize Slider
     self.iconSlider = QSlider()
     self.iconSlider.setTickPosition(QSlider.TicksLeft)
     self.iconSlider.setOrientation(Qt.Horizontal)
     self.iconSlider.setValue(config.iconSize())
     self.iconSlider.setMinimum(16)
     self.iconSlider.setMaximum(32)
     self.iconSlider.setSingleStep(2)
     self.iconSlider.valueChanged.connect(self.setIcon)
     self.iconSliderAction = QWidgetAction(men)
     self.iconSliderAction.setDefaultWidget(self.iconSlider)
     
     '''Font Button'''
     self.fontCombo = QFontComboBox()
     self.fontCombo.currentFontChanged.connect(self.parent.setFont)
     self.fontCombo.setCurrentFont(QFont(config.fontName()))
     self.fontComboMenu = QWidgetAction(men)
     self.fontComboMenu.setDefaultWidget(self.fontCombo)
     
     '''Font Size'''
     self.fontSizeCombo = QComboBox()
     for size in range(1,40):
         self.fontSizeCombo.addItem(str(size))
     self.fontSizeCombo.setCurrentIndex(config.fontSize())
     self.fontSizeCombo.currentIndexChanged.connect(self.parent.setFontSize)
     self.fontSizeComboMenu = QWidgetAction(men)
     self.fontSizeComboMenu.setDefaultWidget(self.fontSizeCombo)
     
     
     action_Android = QAction(Icons.android,'Android', self)
     action_Android.triggered.connect(self.parent.android)
     action_Ant = QAction(Icons.ant_view,'Ant', self)
     action_Ant.triggered.connect(self.parent.antt)
     action_Squirrel = QAction(Icons.nut,'Squirrel', self)
     action_Squirrel.triggered.connect(self.parent.squirrel)
     action_Ios1 = QAction(Icons.ios,'iOS', self)
     action_Update = QAction(Icons.update,"Update",self)
     action_Update.triggered.connect(self.parent.update)
     
     action_explorer = QAction("Explorer",self)
     action_explorer.triggered.connect(self.parent.exp)
     action_explorer.setCheckable(True)
     action_explorer.setChecked(True)
     action_console = QAction("Console",self)
     action_console.triggered.connect(self.parent.cmd)
     action_console.setCheckable(True)
     action_console.setChecked(False)
     #action_designer = QAction("Designer",self)
     #action_designer.triggered.connect(self.parent.design)
     action_Indentation = QAction("Indentation Guides",self)
     action_Indentation.triggered.connect(self.parent.setIndent)
     action_Indentation.setCheckable(True)
     action_Indentation.setChecked(config.indent())
     action_WhiteSpace = QAction("WhiteSpace",self)
     action_WhiteSpace.triggered.connect(self.parent.setWhiteSpace)
     action_WhiteSpace.setCheckable(True)
     action_WhiteSpace.setChecked(config.whiteSpace())
     action_EndLine = QAction("End of Lines",self)
     action_EndLine.triggered.connect(self.parent.setEndLine)
     action_EndLine.setCheckable(True)
     action_Margin = QAction("Line Numbers",self)
     action_Margin.triggered.connect(self.parent.setMargin)
     action_Margin.setCheckable(True)
     action_Margin.setChecked(config.margin())
     action_ToolLabel = QAction("Tool Labels",self)
     action_ToolLabel.triggered.connect(self.setToolLabel)
     action_ToolLabel.setCheckable(True)
     #action_ToolLabel.setChecked(config.toolLabel())
     
     '''Encoding'''
     encodingGroup = QActionGroup(self)
     encodingGroup.setExclusive(True)
     action_Ascii = QAction("Ascii",encodingGroup)
     action_Ascii.setCheckable(True)
     action_Unicode = QAction("Unicode",encodingGroup)
     action_Unicode.setCheckable(False)
     encodingGroup.addAction(action_Ascii)
     encodingGroup.addAction(action_Unicode)
     encodingGroup.selected.connect(self.parent.setEncoding)
     if(config.encoding() == Encoding.ASCII):
         action_Ascii.setChecked(True)
     else:
         action_Unicode.setChecked(True)
     men.addAction(action_Update)
     men.addAction(self.action_Help)
     men.addAction(self.action_Full)
     men.addSeparator()
     men.addAction(action_Android)
     men.addAction(action_Ant)
     men.addAction(action_Squirrel)
     men.addAction(action_Ios1)
     
     men.addSeparator()
     men.addAction(action_explorer)
     men.addAction(action_console)
     #men.addAction(action_designer)
     men.addSeparator()
     men.addAction(action_Indentation)
     men.addAction(action_WhiteSpace)
     men.addAction(action_EndLine)
     men.addAction(action_Margin)
     men.addAction(action_ToolLabel)
     men.addSeparator()
     men.addActions(encodingGroup.actions())
     men.addSeparator()
     head_font = QLabel("Font---------------------")
     fnt = head_font.font()
     fnt.setBold(True)
     head_font.setFont(fnt)
     head_fontWidgetAction = QWidgetAction(men)
     head_fontWidgetAction.setDefaultWidget(head_font)
     men.addAction(head_fontWidgetAction)
     men.addAction(self.fontComboMenu)
     men.addAction(self.fontSizeComboMenu)
     men.addSeparator()
     men.addAction(QAction("TabWidth",self))
     men.addAction(self.tabsSliderAction)
     men.addSeparator()
     men.addAction(QAction("Threshold",self))
     men.addAction(self.threshSliderAction)
     #men.addAction(QAction("Icon Size",self))
     #men.addAction(self.iconSliderAction)
     
     self.action_Options = QAction(Icons.emblem_system, 'Options', self)
     self.action_Options.setMenu(men)
     self.addAction(self.action_Options)
    def __init__(self, parent=None):
        " Initialize QWidget inside MyMainWindow "
        super(MyMainWindow, self).__init__(parent)
        QWidget.__init__(self)
        self.statusBar().showMessage("               {}".format(__doc__))
        self.setStyleSheet("QStatusBar{color:grey;}")
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont("Ubuntu Light", 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height())

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get("http_proxy", ""))
        QNetworkProxy.setApplicationProxy(
            QNetworkProxy(
                QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy,
                proxy_url.host(),
                proxy_url.port(),
                proxy_url.userName(),
                proxy_url.password(),
            )
        ) if "http_proxy" in environ else None
        print((" INFO: Proxy Auto-Config as " + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.tabCloseRequested.connect(lambda: self.mainwidget.setTabPosition(randint(0, 3)))
        # if self.mainwidget.tabPosition() == 0
        # else self.mainwidget.setTabPosition(0))
        self.mainwidget.setStyleSheet("QTabBar{color:white;font-weight:bold;}")
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3):
            a.setWindowModality(Qt.NonModal)
            a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle())
            a.setStyleSheet(" QDockWidget::title{text-align:center;}")
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), "Double Click Me")

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self)
        qaqq.setShortcut("Ctrl+Q")
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"), "AutoCenter AutoResize", self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"), "View Date and Time", self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self)
        qabug.triggered.connect(
            lambda: qabug.setDisabled(True)
            if not call("xdg-open mailto:" + "*****@*****.**".decode("rot13"), shell=True)
            else " ERROR "
        )
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), "About KDE", self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self)
        if KDE:
            qaslf.triggered.connect(KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(
                lambda: QMessageBox.about(
                    self.mainwidget,
                    __doc__,
                    "".join(
                        (
                            __doc__,
                            linesep,
                            "version ",
                            __version__,
                            ", (",
                            __license__,
                            "), by ",
                            __author__,
                            ", ( ",
                            __email__,
                            " )",
                            linesep,
                        )
                    ),
                )
            )
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), "Set GUI Font", self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(
                lambda: self.setStyleSheet(
                    "".join(("*{font-family:", str(font.toString()), "}"))
                    if KFontDialog.getFont(font)[0] == QDialog.Accepted
                    else ""
                )
            )
        else:
            qafnt.triggered.connect(
                lambda: self.setStyleSheet("".join(("*{font-family:", str(QFontDialog.getFont()[0].toString()), "}")))
            )
        qasrc = QAction(QIcon.fromTheme("applications-development"), "View Source Code", self)
        qasrc.triggered.connect(lambda: call("xdg-open {}".format(__file__), 1))
        qakb = QAction(QIcon.fromTheme("input-keyboard"), "Keyboard Shortcuts", self)
        qakb.triggered.connect(
            lambda: QMessageBox.information(self.mainwidget, "Keyboard Shortcuts", " Ctrl+Q = Quit ")
        )
        qapic = QAction(QIcon.fromTheme("camera-photo"), "Take a Screenshot", self)
        qapic.triggered.connect(
            lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save(
                QFileDialog.getSaveFileName(
                    self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ";;(*.png) PNG", "png"
                )
            )
        )
        qatb = QAction(QIcon.fromTheme("go-top"), "Toggle ToolBar", self)
        qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("help-browser"), "Switch ToolBar Icon Size", self)
        qati.triggered.connect(
            lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4)
        )
        qasb = QAction(QIcon.fromTheme("zoom-in"), "Toggle Tabs Bar", self)
        qasb.triggered.connect(
            lambda: self.mainwidget.tabBar().hide()
            if self.mainwidget.tabBar().isVisible() is True
            else self.mainwidget.tabBar().show()
        )
        qadoc = QAction(QIcon.fromTheme("help-browser"), "On-line Docs", self)
        qadoc.triggered.connect(lambda: open_new_tab(__url__))
        qapy = QAction(QIcon.fromTheme("help-about"), "About Python", self)
        qapy.triggered.connect(lambda: open_new_tab("http://python.org/about"))
        qali = QAction(QIcon.fromTheme("help-browser"), "Read Licence", self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), "Set GUI Colors", self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(
                lambda: self.setStyleSheet("".join(("* { background-color: ", str(color.name()), "}")))
                if KColorDialog.getColor(color, self)
                else ""
            )
        else:
            qacol.triggered.connect(
                lambda: self.setStyleSheet(
                    "".join((" * { background-color: ", str(QColorDialog.getColor().name()), " } "))
                )
            )
        qatit = QAction(QIcon.fromTheme("preferences-system"), "Set the App Window Title", self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        for b in (
            qaqq,
            qamin,
            qanor,
            qamax,
            qasrc,
            qakb,
            qacol,
            qatim,
            qatb,
            qafnt,
            qati,
            qasb,
            qatit,
            qapic,
            qadoc,
            qali,
            qaslf,
            qaqt,
            qakde,
            qapy,
            qabug,
        ):
            self.toolbar.addAction(b)
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu("&File").addActions((qaqq,))
        menu.addMenu("&Window").addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu("&Settings").addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu("&Help").addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            " quick and dirty custom context menu "
            menu = QMenu()
            menu.addActions(
                (
                    qaqq,
                    qamin,
                    qanor,
                    qamax,
                    qasrc,
                    qakb,
                    qacol,
                    qafnt,
                    qati,
                    qasb,
                    qatb,
                    qatim,
                    qatit,
                    qapic,
                    qadoc,
                    qali,
                    qaslf,
                    qaqt,
                    qakde,
                    qapy,
                    qabug,
                )
            )
            menu.exec_(self.mapToGlobal(point))

        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            " widget tuple passed as argument should be checked as ON "
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            " widget tuple passed as argument should have tooltips "
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            " widget tuple passed as argument should have filled background "
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            " apply an glow effect to the widget "
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(
                                lambda: each_widget.graphicsEffect().setEnabled(True)
                                if each_widget.graphicsEffect().isEnabled() is False
                                else each_widget.graphicsEffect().setEnabled(False)
                            )
                        except:
                            each_widget.sliderPressed.connect(
                                lambda: each_widget.graphicsEffect().setEnabled(True)
                                if each_widget.graphicsEffect().isEnabled() is False
                                else each_widget.graphicsEffect().setEnabled(False)
                            )
                except:
                    pass

        #######################################################################

        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)
        self.frmt = QComboBox(self.group1)
        self.frmt.addItems(["blah ", "blah blah", "blah blah blah"])
        self.file1 = QLineEdit()
        self.file1.setPlaceholderText("/full/path/to/one_file.py")
        self.file1.setCompleter(self.completer)
        self.borig = QPushButton(QIcon.fromTheme("folder-open"), "Open")
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;">some comment'),
            self.file1,
            self.borig,
            QLabel('<b style="color:white;">Lorem Impsum'),
            self.frmt,
        ):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)
        self.nwfl = QCheckBox("Be Awesome")
        self.smll = QCheckBox("Solve the Squaring of the Circle")
        self.lrgf = QCheckBox("Im just a QCheckBox")
        self.case = QCheckBox("Use Quantum Processing")
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.nwfl, self.smll, self.lrgf, self.case):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        self.plai = QCheckBox("May the Force be with You")
        self.nocr = QCheckBox("Im just a Place Holder")
        self.ridt = QCheckBox("Lorem Impsum")
        self.nocm = QCheckBox("Divide by Zero")
        vboxg3 = QVBoxLayout(group3)
        for each_widget in (self.plai, self.nocr, self.ridt, self.nocm):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        self.dock2.setWidget(QPlainTextEdit())

        # dock 3
        self.dock3.setWidget(QCalendarWidget())

        # configure some widget settings
        must_be_checked((self.nwfl, self.smll, self.lrgf, self.plai))
        must_have_tooltip((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case))
        must_autofillbackground(
            (self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case)
        )
        must_glow((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl))
Example #32
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file ')
        self.infile.returnPressed.connect(self.run)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.infile.setCompleter(self.completer)

        self.menu = QMenu('Base64')
        self.menu.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu, lang='all')

        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to Encode...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['*', 'jpg', 'png', 'webp', 'svg', 'gif', 'webm']])))))
        self.chckbx1 = QCheckBox('Use basic Caesar Cipher (ROT13)')
        self.chckbx1.setToolTip('Use "string".decode("rot13") to Decipher ! ')
        self.chckbx2 = QCheckBox('Use "data:type/subtype;base64,..."')
        self.chckbx2.setChecked(True)
        self.chckbx3 = QCheckBox('Copy encoded output to Clipboard')
        self.chckbx4 = QCheckBox('Use URL-Safe Base64 Encoder')
        self.combo1 = QComboBox()
        self.combo1.addItems(['Do Not Generate Code', 'Generate CSS embed Code',
            'Generate Python Embed Code', 'Generate HTML embed Code',
            'Generate JS embed Code', 'Generate QML embed Code'])
        self.combo1.currentIndexChanged.connect(self.combo_changed)

        self.output = QTextEdit('''
        We can only see a short distance ahead,
        but we can see plenty there that needs to be done.
        - Alan Turing ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton(QIcon.fromTheme("face-cool"), 'Encode BASE64')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>Encode file as plain text string</i>'),
            QLabel('<b>File to Encode:'), self.infile, self.open, self.chckbx2,
            self.chckbx3, self.chckbx1, self.chckbx4,
            QLabel('<b>Embedding Template Code:'), self.combo1,
            QLabel(' <b>Base64 String Output: '), self.output,
            QLabel('<center><small><i>' + ''.join((__doc__, __version__,
                   __license__, 'by', __author__))), self.button
        ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Base64")
        self.guimode = QComboBox(self.dock)
        self.guimode.addItems(['Full Mode', 'Simple Mode'])
        self.guimode.currentIndexChanged.connect(self.guimode_change)

    def guimode_change(self):
        """ Change from Simple Mode to Full Mode by Hide or Show Widgets """
        if self.guimode.currentIndex() is 0:
            self.chckbx1.show()
            self.chckbx2.show()
            self.chckbx3.show()
            self.chckbx4.show()
        else:
            self.chckbx1.hide()
            self.chckbx2.hide()
            self.chckbx3.hide()
            self.chckbx4.hide()
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(True)
            self.chckbx3.setChecked(False)
            self.chckbx4.setChecked(False)

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu.clear()
        if self.ex_locator.get_current_project_item().isFolder is not True:
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            self.menu.addActions([
                QAction('Copy {} as Base64'.format(path.basename(filenam)[:50]),
                        self, triggered=lambda:
                        QApplication.clipboard().setText(
                        '"data:{};charset=utf-8;base64,{}"'.format(
                            guess_type(filenam, strict=False)[0],
                            b64encode(open(filenam, "rb").read())))),
                QAction('Copy {} as Base64 URL-Safe'.format(
                        path.basename(filenam)[:50]),
                        self, triggered=lambda:
                        QApplication.clipboard().setText(
                        '"data:{};charset=utf-8;base64,{}"'.format(
                            guess_type(filenam, strict=False)[0],
                            urlsafe_b64encode(open(filenam, "rb").read()))))])
            self.menu.show()

    def run(self):
        ' run the encoding '
        mimetype = guess_type(str(self.infile.text()).strip(), strict=False)[0]
        _mime = mimetype if mimetype is not None else self.ask_mime()
        fle = str(self.infile.text()).strip().replace('file:///', '/')
        encoder = urlsafe_b64encode if self.chckbx4.isChecked() else b64encode
        if int(path.getsize(fle)) / 1024 / 1024 >= 1:
            QMessageBox.information(self.dock, __doc__,
            '''<b style="color:red"> WARNING!: File size is > 1 Megabyte!,<br>
            this will take some time, depending your CPU Processing power!.''')
        output = '"{}{}{}{}"'.format(
            'data:' if self.chckbx2.isChecked() is True else '',
            _mime if self.chckbx2.isChecked() is True else '',
           ';charset=utf-8;base64,' if self.chckbx2.isChecked() is True else '',
            encoder(open(fle, "rb").read()))
        if self.combo1.currentIndex() is 1:
            output = ('html, body { margin:0; padding:0; background: url(' +
            output + ') no-repeat center center fixed; background-size:cover }')
        elif self.combo1.currentIndex() is 2:
            output = PY_EMBED.format(getuser(),
                     datetime.now().isoformat().split('.')[0], output)
        elif self.combo1.currentIndex() is 3:
            output = '<img src={} alt="{}" title="{}"/>'.format(output,
                     fle.split(sep)[-1], fle.split(sep)[-1])
        elif self.combo1.currentIndex() is 4:
            output = 'var embedded_file = window.atob({}); '.format(output)
        elif self.combo1.currentIndex() is 5:
            output = 'Image { source: ' + output + ' } '
        if self.chckbx1.isChecked() is True:
            output = str(output).encode('rot13')
        if self.chckbx3.isChecked() is True:
            QApplication.clipboard().setText(output)
        self.output.setPlainText(output)
        self.output.setFocus()
        self.output.selectAll()

    def ask_mime(self):
        ' ask user for mime type '
        return str(QInputDialog.getText(self.dock, __doc__, 'Write a MIME-Type',
               QLineEdit.Normal, 'application/octet-stream')[0]).strip().lower()

    def combo_changed(self):
        ' on combo changed '
        if self.combo1.currentIndex() is 1 or self.combo1.currentIndex() is 3:
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(True)
        elif self.combo1.currentIndex() is 2 or self.combo1.currentIndex() is 4:
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(False)
Example #33
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 #34
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.menu, self.qactions = QMenu(__doc__), []
        self.menu.aboutToShow.connect(self.build_submenu)
        self.new_snipe = QAction('New Snippet', self, triggered=lambda:
            self.locator.get_service("editor").add_editor(content=TEMPLATE, ))
        self.locator.get_service("menuApp").add_menu(self.menu)

    def build_submenu(self):
        '''Build sub menu on the fly based on the available qactions'''
        self.menu.clear()
        if len(self.qactions):
            self.menu.addAction(self.new_snipe)
            self.menu.addSeparator()
            self.menu.addActions(sorted(list(set(self.qactions))))
        else:
            self.menu.addActions([self.new_snipe, QAction('Load Snippets', self,
            triggered=lambda: self.menu.addActions(sorted(self.run())))])

    def run(self):
        """Get directory,walk it,make list of snippets,convet them to Qaction"""
        dir_walk = QFileDialog.getExistingDirectory(None, __doc__, DEFAULT_PATH)
        list_of_files = self.walkdir_to_filelist(dir_walk)
        return self.snippets_to_qactions(list_of_files)

    def walkdir_to_filelist(self, where):
        """Perform full walk of where, gather full path of all files"""
        return [path.join(root, f) for root, d, files in walk(str(where))
                for f in files if f.lower().endswith('.sublime-snippet')]

    def snippets_to_qactions(self, list_of_files):
        """ takes a list of full paths and adds them as qactions on the menu """
        for snippet_file in list_of_files:
            with open(snippet_file, 'r') as snippet:
                sni = parse(str(snippet.read()).strip())
                try:
                    self.qactions.append(QAction(str(
                    '[{}] '.format(sni['snippet']['scope'].split('.')[1][:9]) +
                    sni['snippet']['description'][:99]), self, triggered=lambda:
                    self.locator.get_service("editor").insert_text(
                    self.snippet_replacer(str(sni['snippet']['content'])))))
                except:
                    pass
                snippet.flush()
        return self.qactions

    def snippet_replacer(self, snippetext):
        """ replaces the env vars by user input values or guessed values """
        # sublimetext.info/docs/en/extensibility/snippets.html#environment-variables
        #OPTIMIZE: how can we do this better?
        return snippetext.replace(
                '$SELECTION',
                self.locator.get_service("editor").get_actual_tab().textCursor().selectedText(),
            ).replace(
                '$TM_SELECTED_TEXT',
                self.locator.get_service("editor").get_actual_tab().textCursor().selectedText(),
            ).replace(
                '$TM_CURRENT_LINE',
                self.locator.get_service("editor").get_actual_tab().textCursor().block().text()
            ).replace(
                '$TM_FILENAME',
                path.basename(self.locator.get_service("editor").get_opened_documents()[self.locator.get_service("editor").get_tab_manager().currentIndex()])
            ).replace(
                '$TM_FILEPATH',
                path.dirname(self.locator.get_service("editor").get_opened_documents()[self.locator.get_service("editor").get_tab_manager().currentIndex()])
            ).replace(
                '$TM_LINE_INDEX',
                str(len(self.locator.get_service("editor").get_actual_tab().textCursor().block().text()))
            ).replace('$TM_SOFT_TABS', 'YES').replace('$TM_FULLNAME', getuser()
            ).replace('$TM_TAB_SIZE', '4')
Example #35
0
class GdalTools:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        #self.analysisMenu.addActions( [  ] )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def doSettings(self):
        from tools.doSettings import GdalToolsSettingsDialog as Settings
        d = Settings(self.iface)
        d.exec_()
Example #36
0
class EjdexplInt:

    def __init__(self, iface):

        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.searchobj = None
        self.readconfig()
        self.updateconfig()
        self.srsitem = CanvasItems(self.iface.mapCanvas(),self.config['search_color'],self.config['search_style'],self.config['search_width'],self.config['search_icon'],self.config['search_size'])
        self.db = QSqlDatabase.addDatabase('QODBC')
        self.db.setDatabaseName(self.config['connection'])
        
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir,'i18n','EjdexplInt_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

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

    def tr(self, message):

        return QCoreApplication.translate('EjdexplInt', message)

    def initGui(self):
    
        self.action = QAction(QIcon(":/plugins/EjdexplInt/icons/icon.png"),self.tr(u'Activate EjdExplorer tool'),self.iface.mainWindow())
        self.action.setWhatsThis(u"Activate EjdExplorer tool")
        self.action.triggered.connect(self.run)
    
        self.tbmenu = QMenu()

        self.ag1 = QActionGroup(self.tbmenu,exclusive=True)
        self.acPol  = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Polygon.ico'),self.tr(u'Draw polygon'),self.tbmenu,checkable=True))
        self.acLin  = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Polyline.ico'),self.tr(u'Draw line'),self.tbmenu,checkable=True))
        self.acPnt  = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Geo-Fence.ico'),self.tr(u'Draw point'),self.tbmenu,checkable=True))
        self.acAlay = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Layers.ico'),self.tr(u'Active selection'),self.tbmenu,checkable=True))
        self.acPobj = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Quest.ico'),self.tr(u'Previous object'),self.tbmenu,checkable=True))
        self.tbmenu.addActions(self.ag1.actions());
        self.acPol.setChecked(self.config['searchtool']==u'polygon')
        self.acLin.setChecked(self.config['searchtool']==u'line')
        self.acPnt.setChecked(self.config['searchtool']==u'point')
        self.acAlay.setChecked(self.config['searchtool']==u'selection')
        self.acPobj.setChecked(self.config['searchtool']==u'search')

        self.tbmenu.addSeparator()

        self.ag2 = QActionGroup(self.tbmenu,exclusive=True)
        self.acSingle = self.ag2.addAction(QAction(self.tr(u'Use single mode'),self.tbmenu,checkable=True))
        self.acBulk = self.ag2.addAction(QAction(self.tr(u'Use bulk mode'),self.tbmenu,checkable=True))
        self.acMerge = self.ag2.addAction(QAction(self.tr(u'Use merge mode'),self.tbmenu,checkable=True))
        self.tbmenu.addActions(self.ag2.actions());
        self.acSingle.setChecked(self.config['tabchoice']==u'single')
        self.acBulk.setChecked(self.config['tabchoice']==u'bulk')
        self.acMerge.setChecked(self.config['tabchoice']==u'merge')

        if self.config['old_behavior'] == 0:
            self.tbmenu.addSeparator()
            self.acClear = QAction(self.tr(u'Clear'),self.tbmenu,checkable=False)
            self.acClear.triggered.connect(self.clearSearch)    
            self.tbmenu.addAction(self.acClear)

        self.toolButton = QToolButton()
        self.toolButton.addAction(self.action)
        self.toolButton.setDefaultAction(self.action)
        self.toolButton.setMenu(self.tbmenu)
        self.toolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.iface.addToolBarWidget(self.toolButton)
        self.iface.addPluginToMenu(self.tr(u'Activate EjdExplorer tool'), self.action)

        self.ag1.triggered.connect(self.drawChanged)    

    def drawChanged(self, action):
        if action.isChecked():
            self.run()


    def clearSearch(self):
        if self.config['old_behavior'] == 0:
            self.srsitem.clearMarkerGeom()
        
    def unload(self):

        self.iface.removePluginMenu(self.tr(u'Activate EjdExplorer tool'), self.action)
        self.iface.removeToolBarIcon(self.action)
        del self.tbmenu     # No parent
        del self.toolButton # No parent


    def run(self):

        geoms =  None
        canvas = self.iface.mapCanvas()
        if self.config['old_behavior'] == 0:
            self.srsitem.clearMarkerGeom()

        if self.acPol.isChecked():   # polygon
            tool = CaptureTool(canvas, self.geometryAdded, CaptureTool.CAPTURE_POLYGON)
            canvas.setMapTool(tool)        
        elif self.acLin.isChecked(): # line
            tool = CaptureTool(canvas, self.geometryAdded, CaptureTool.CAPTURE_LINE)
            canvas.setMapTool(tool)        
        elif self.acPnt.isChecked(): # point
            tool = AddPointTool(canvas, self.geometryAdded)
            canvas.setMapTool(tool)        
        elif self.acAlay.isChecked(): # active layer selection
            layer = self.iface.activeLayer()
            if (layer) and (layer.type() == QgsMapLayer.VectorLayer):
                selection = layer.selectedFeatures()
                if (selection):
                    for f in selection:
                        if geoms == None:
                            geoms = f.geometry()
                        else:
                            geoms = geoms.combine( f.geometry() )
            if (geoms != None):
                self.geometryAdded(geoms)            
            else:
                self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'No object found'), QgsMessageBar.CRITICAL, 6)
        elif self.acPobj.isChecked(): # existing object
            geoms = self.searchobj
            if (geoms != None):
                self.geometryAdded(geoms)            
            else:
                self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'No existing object found'), QgsMessageBar.CRITICAL, 6)
                self.acPol.setChecked(True)
        else:
            self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'Uknown search tool'), QgsMessageBar.CRITICAL, 6)

    def cnvobj2wkt (self,gobj,epsg_in,epsg_out, buffer_pol, buffer_lin):
        
        # Buffer around search object; negative for polygon or positive for points and lines
        if gobj.type() == 2: # Polygon
            gobj = gobj.buffer(buffer_pol,8)       
        else:                # Line or Point
            gobj = gobj.buffer(buffer_lin,8)       

        crsSrc = QgsCoordinateReferenceSystem(int(epsg_in))
        crsDest = QgsCoordinateReferenceSystem(int(epsg_out))
        xform = QgsCoordinateTransform(crsSrc, crsDest)
        i = gobj.transform(xform)

        return gobj.exportToWkt()

    def geometryAdded(self, geom):

        self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Start EjdExplorer'), self.tr(u'Starting EjdExplorer program, takes a few seconds..'), QgsMessageBar.INFO, 6)

        self.searchobj = geom
        if self.config['old_behavior'] == 0:
            self.srsitem.setMarkerGeom(geom)
        epsg_in = self.iface.mapCanvas().mapRenderer().destinationCrs().authid().replace('EPSG:','')
        geom_txt = self.cnvobj2wkt (geom,epsg_in,self.config['epsg'],self.config['buffer_pol'],self.config['buffer_lin'])
        txt1, txt2 = self.getlists (geom_txt)
        
        mode = u'single'
        if self.acBulk.isChecked():
            mode = u'bulk'
        if self.acMerge.isChecked():
            mode = u'merge'

        # NB! parameters dosn't work as expected, LIFA contacted (and admit to an error in their program)
        txt = u'start ' + self.config['command'] + u' "' + self.config['parameter'].format(mode, txt1,txt2) + u'"'
        txt = txt.encode('latin-1')
        if len(txt) <= 8190: # max length of command-line parameter 
            os.system ( txt)
        else:
            self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Start EjdExplorer'), self.tr(u'To many entities selected; try with a smaller search object'), QgsMessageBar.CRITICAL, 6)       

        self.iface.actionPan().trigger()


    def msgbox (self,txt1):

        cb = QApplication.clipboard()
        cb.setText(txt1)
        msgBox = QMessageBox()
        msgBox.setText(txt1)
        msgBox.exec_()

    def getlists(self, wkt):

        ejrlrv = []
        matrnr = []

        if (self.db.open()==True):     
 			    
            query = QSqlQuery (self.config['sqlquery'].format(wkt,self.config['epsg'])) 
            while (query.next()):
                ejrlrv.append(query.value(0))
                matrnr.append(query.value(1))
        else:
            self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Database Error'), db.lastError().text(), QgsMessageBar.INFO, 6)

        return u','.join(ejrlrv), u','.join(matrnr) 

        
    def readconfig(self):

        s = QSettings()
        k = __package__
        self.config = {
            'epsg':       unicode(s.value(k + "/epsg"       , "25832", type=str)),
            'buffer_pol': s.value(k + "/buffer_pol" , -0.1, type=float),
            'buffer_lin': s.value(k + "/buffer_lin" , 0.1, type=float),
            'searchtool': unicode(s.value(k + "/searchtool" , "point", type=str)).lower(),
            'tabchoice':  unicode(s.value(k + "/tabchoice"  , "single", type=str)).lower(),
            'sqlquery':   unicode(s.value(k + "/sqlquery"   , "select  LTRIM(RTRIM(CONVERT(varchar(10), [landsejerlavskode]))) as ejrlvnr, LTRIM(RTRIM([matrikelnummer])) as matrnr from [dbo].[Jordstykke] where geometry::STGeomFromText('{0}',{1}).STIntersects([geometri])=1", type=str)),
            'connection': unicode(s.value(k + "/connection" , "Driver={SQL Server};Server=f-sql12;Database=LOIS;Trusted_Connection=Yes;", type=str)),
            'command':    unicode(s.value(k + "/command"    , 'C:/"Program Files (x86)"/LIFA/EjdExplorer/LIFA.EjdExplorer.GUI.exe', type=str)),
            'parameter':  unicode(s.value(k + "/parameter"  , 'ejdexpl://?mode={0}&CadastralDistrictIdentifier={1}&RealPropertyKey={2}', type=str)),
            'search_color':  str(s.value(k + "/search_color", "#FF0000", type=str)),
            'search_width':  s.value(k + "/search_width", 4, type=int),
            'search_style':  s.value(k + "/search_style", 1, type=int),
            'search_icon':   s.value(k + "/search_icon", QgsVertexMarker.ICON_CROSS, type=int),
            'search_size':   s.value(k + "/search_size", 30, type=int),
            'old_behavior':   s.value(k + "/old_behavior", 0, type=int)
        }
        self.srsitem = CanvasItems(self.iface.mapCanvas(),self.config['search_color'],self.config['search_style'],self.config['search_width'],self.config['search_icon'],self.config['search_size'])

    def updateconfig(self):

        s = QSettings()
        k = __package__
        s.setValue(k + "/epsg",          self.config['epsg'])
        s.setValue(k + "/buffer_pol",    self.config['buffer_pol'])
        s.setValue(k + "/buffer_lin",    self.config['buffer_lin'])
        s.setValue(k + "/searchtool",    self.config['searchtool'])
        s.setValue(k + "/tabchoice",     self.config['tabchoice'])
        s.setValue(k + "/sqlquery",      self.config['sqlquery'])
        s.setValue(k + "/connection",    self.config['connection'])
        s.setValue(k + "/command",       self.config['command'])
        s.setValue(k + "/parameter",     self.config['parameter'])
        s.setValue(k + "/search_color",  self.config['search_color'])
        s.setValue(k + "/search_style",  self.config['search_style'])
        s.setValue(k + "/search_width",  self.config['search_width'])
        s.setValue(k + "/search_icon",  self.config['search_icon'])
        s.setValue(k + "/search_size",  self.config['search_size'])
        s.setValue(k + "/old_behavior", self.config['old_behavior'])
        s.sync
Example #37
0
class fToolsPlugin:
    def __init__(self, iface):
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

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

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

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

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

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

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

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

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

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

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

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

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

        self.updateThemeIcons("theme")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def doEliminate(self):
        d = doEliminate.Dialog(self.iface)
        d.exec_()
Example #38
0
class QVertex:
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        """Constructor.
		print os.path.abspath(os.path.dirname(__file__) + '/svgwrite'
        :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__)
        # /home/filippov/work/test.qgs -> /home/filippov/work/test

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

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

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

        # Create the dialog (after translation) and keep reference

        self.dlg_coordcatalog = None
        self.dlg_geodata = None

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

        # Настройки http://gis-lab.info/docs/qgis/cookbook/settings.html
        #print self.plugin_dir
        self.settings = QSettings(self.plugin_dir + os.sep + 'config.ini', QSettings.IniFormat)

        if sys.platform.startswith('win'):
            self.lastDir = self.settings.value('last_dir', self.plugin_dir)
        else:
            self.lastDir = self.settings.value('last_dir', self.plugin_dir)

        # msk = self.settings.value('current_crs')
        # self.current_crs = self.settings.value(msk, '+proj=longlat +datum=WGS84 +no_defs')
        # self.iface.messageBar().pushMessage(u'Используется '+msk, QgsMessageBar.INFO, 15)

        #msk_names = self.settings.value('msk_names')
        self.dlg = None#QVertexDialogBase(self.iface, msk_names)
        #self.showSettings()

    # 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('QVertex', 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 initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.menu = QMenu()
        self.menu.setTitle(u"QVertex")

        self.qvertex_createProject = QAction(u"Создать проект", self.iface.mainWindow())
        self.qvertex_createProject.setEnabled(True)
        # self.qvertex_createProject.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))
        self.menu.addAction(self.qvertex_createProject)

        # self.qvertex_showSettings = QAction(u"Настройка МСК", self.iface.mainWindow())
        # self.qvertex_showSettings.setEnabled(True)
        # # self.qvertex_showSettings.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))
        # self.menu.addAction(self.qvertex_showSettings)


        self.pointMenu = QMenu()
        self.pointMenu.setTitle(u"Точки")

        self.qvertex_createVertex = QAction(u"Создать примыкающие вершины", self.iface.mainWindow())
        self.qvertex_createVertex.setEnabled(True)
        # self.qvertex_createVertex.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))

        self.qvertex_createPoint = QAction(u"Создать характерные точки", self.iface.mainWindow())
        self.qvertex_createPoint.setEnabled(True)
        #self.qvertex_createPoint.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))

        #self.qvertex_createNewPoint.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))
        self.pointMenu.addActions([self.qvertex_createVertex, self.qvertex_createPoint])
        self.menu.addMenu(self.pointMenu)

        self.qvertex_createBoundPart = QAction(u"Создать части границ", self.iface.mainWindow())
        self.qvertex_createBoundPart.setEnabled(True)
        # self.qvertex_createProject.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))
        self.menu.addAction(self.qvertex_createBoundPart)


        self.reportMenu = QMenu()
        self.reportMenu.setTitle(u"Отчёты")

        self.qvertex_createCtalog = QAction(u"HTML-ведомость координат", self.iface.mainWindow())
        self.qvertex_createCtalog.setEnabled(True)

        self.qvertex_createMapPlan = QAction(u"HTML-ведомость карта(план)", self.iface.mainWindow())
        self.qvertex_createMapPlan.setEnabled(True)

        self.qvertex_createGeodata = QAction(u"SVG-ведомость и описание границ", self.iface.mainWindow())
        self.qvertex_createGeodata.setEnabled(True)
        # self.qvertex_createGeodata.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))
        self.reportMenu.addActions([self.qvertex_createCtalog, self.qvertex_createMapPlan, self.qvertex_createGeodata])
        self.menu.addMenu(self.reportMenu)

        self.qvertex_exportTechno = QAction(u"Экспорт в Технокад", self.iface.mainWindow())
        self.qvertex_exportTechno.setEnabled(True)
        # self.qvertex_exportTechno.setIcon(QIcon(":/plugins/QVertex/icons/importkk.png"))
        self.menu.addAction(self.qvertex_exportTechno)

        #self.menu.addActions([self.qvertex_createCtalog, self.qvertex_createGeodata])


        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()
        lastAction = actions[len(actions) - 1]
        menu_bar.insertMenu(lastAction, self.menu)
        #icon_path = ':/plugins/QVertex/icon.png'
        # self.add_action(
        #     icon_path,
        #     text=self.tr(u'Землеустройство'),
        #     callback=self.run,
        #     parent=self.iface.mainWindow())

        QObject.connect(self.qvertex_createProject, SIGNAL("triggered()"), self.doCreateProject)
        QObject.connect(self.qvertex_createVertex, SIGNAL("triggered()"), self.doCreatePublicVertexes)
        QObject.connect(self.qvertex_createPoint, SIGNAL("triggered()"), self.doCreatepoint)
        QObject.connect(self.qvertex_createCtalog, SIGNAL("triggered()"), self.doCreateCoordcatalog)
        QObject.connect(self.qvertex_createMapPlan, SIGNAL("triggered()"), self.doCatalogMapPlan)
        QObject.connect(self.qvertex_createGeodata, SIGNAL("triggered()"), self.doCreateGeodata)
        QObject.connect(self.qvertex_createBoundPart, SIGNAL("triggered()"), self.createBoundPart)
        QObject.connect(self.qvertex_exportTechno, SIGNAL("triggered()"), self.exportTechno)

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

    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 isObjectsSelected(self):
        if self.iface.mapCanvas().layers() > 0 and self.iface.mapCanvas().currentLayer() is not None:
            if self.iface.mapCanvas().currentLayer().selectedFeatures() is not None:
                return True
            else:
                return False
        else:
            return False

    def getLayerByName(self, layerName):
        for layer in self.iface.mapCanvas().layers():
            if layer.name() == layerName:
                return layer

    def isMultiPart(self, feature):
        if feature.attribute(u'order') != NULL:
            return True

    def doCreatePublicVertexes(self):
        for clayer in self.iface.mapCanvas().layers():
            if clayer.name() == u'ЗУ':
                pointLayer = clayer
                break
            else:
                pointLayer = None
        if self.isObjectsSelected() and pointLayer is not None:
            pointLayer.startEditing()
            try:
                for feat in self.iface.mapCanvas().currentLayer().selectedFeatures():
                    geom = feat.geometry()
                    if geom.isMultipart():
                        polygons = geom.asMultiPolygon()
                        for polygone in polygons:
                            print 'parse multipolygon part'
                            for ring in polygone:
                                print 'parse multipolygon part ring'
                                for point in ring:
                                    succ = pointLayer.addTopologicalPoints(point)
                                    self.iface.messageBar().pushMessage(u'Добавлены ' + str(succ).encode('UTF-8') + u' примыкающие вершины',
                                                                   QgsMessageBar.INFO, 5)
                                    #print 'inserted result ', str(succ)
                    else:
                        for ring in geom.asPolygon():
                            for point in ring:
                                succ = pointLayer.addTopologicalPoints(point)
                                self.iface.messageBar().pushMessage(u'Добавлены ' + str(succ).encode('UTF-8') + u' примыкающие вершины',
                                                                   QgsMessageBar.INFO, 5)
            except Exception as err:
                self.iface.messageBar().pushMessage(u'Ошибка при добавлении примыкающих вершин! ' + err.encode('UTF-8'),
                                                                   QgsMessageBar.ERROR, 5)
                print 'error in doCreatePublicVertexes!', err
            finally:
                print 'commit'
                pointLayer.commitChanges()

    # копирование шаблонных шейпов и прочего составляющего проект
    def doCreateProject(self):
        curr_path = self.lastDir
        if curr_path == u'':
            curr_path = os.getcwd()
        work_dir_name = QFileDialog.getExistingDirectory(None, u'Выберите папку для нового проекта', curr_path)
        #print type(work_dir_name)
        if work_dir_name != u'':
            if sys.platform.startswith('win'):
                current_path = work_dir_name.encode('cp1251')
            else:
                current_path = work_dir_name
            try:
                shutil.copytree(self.plugin_dir+ os.sep + 'start', current_path + os.sep + 'qvertex')
                #print 'shutil.copytree'

                proj = QgsProject.instance()
                print current_path + os.sep + 'qvertex'+ os.sep + 'landplan.qgs'
                proj.read(QFileInfo(current_path + os.sep + 'qvertex'+ os.sep + 'landplan.qgs'))
                self.settings.setValue('last_dir', current_path + os.sep + 'qvertex')
                #self.showSettings()
            except shutil.Error as ex:
                self.iface.messageBar().pushMessage(ex.message, QgsMessageBar.ERROR, 1)
            finally:
                pass
        else:
            print 'cancelled'

    def showSettings(self):
        msk_names = self.settings.value('msk_names')
        if self.dlg is None:
            self.dlg = QVertexDialogBase(self.iface, msk_names)
            self.dlg.setWindowModality(Qt.WindowModal)
        if self.dlg.exec_() == 1:
            msk = self.dlg.listCrs.currentItem().text()
            #print msk
            self.settings.setValue('current_crs', msk)
            self.current_crs = self.settings.value(msk, '+proj=longlat +datum=WGS84 +no_defs')
            self.iface.messageBar().pushMessage(u'Используется '+msk, QgsMessageBar.INFO, 1)

    def doCreatepoint(self):
        if self.isObjectsSelected():
            CreatePoints(self.iface)

    def doCreateCoordcatalog(self):
        if self.dlg_coordcatalog is None:
            self.dlg_coordcatalog = CreateCoordCatalog(self.iface, self.current_crs)
            self.dlg_coordcatalog.setWindowModality(Qt.NonModal)
        self.dlg_coordcatalog.show()

    def doCreateGeodata(self):
        if self.dlg_geodata is None:
            self.dlg_geodata = CreateGeodata(self.iface, self.current_crs)
            self.dlg_geodata.setWindowModality(Qt.NonModal)
        self.dlg_geodata.show()

    def createPart(self, layer, ring):
        c = len(ring)
        curr = 1
        pointLayer = self.getLayerByName(u'Точки')
        if pointLayer is None:
            idx = -1
        else:
            idx = pointLayer.fieldNameIndex('name')
        cadastreLayer = self.getLayerByName(u'Кадастр')
        for point in ring:
            if curr < c:
                point1 = point
                point2 = ring[curr]
                isEqual = False
                pt1stst = False
                pt2stst = False
                curr += 1
                #print point1, point2
                line_geometry=QgsGeometry.fromPolyline([QgsPoint(point1.x(), point1.y()),
                                                       QgsPoint(point2.x(), point2.y())])
                # find point
                for pointfeature in pointLayer.getFeatures():
                    if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(point1.x(), point1.y()))):
                        name = unicode(pointfeature.attribute(u'name'))
                        if name[0] == u'н':
                            pt1stst = True
                    if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(point2.x(), point2.y()))):
                        name = unicode(pointfeature.attribute(u'name'))
                        if name[0] == u'н':
                            pt2stst = True
                # check for identity
                features = layer.getFeatures()
                for f in features:
                    if line_geometry.equals(f.geometry()):
                        self.iface.messageBar().pushMessage(u'Найдена дублирующая часть границы, пропущена', level=QgsMessageBar.INFO)
                        isEqual = True
                        break
                #check for cadastre
                if not pt1stst and not pt2stst:
                    findInCadastre = False
                    print 'cadastre check'
                    if cadastreLayer is not None and not findInCadastre:
                        cadObjs = cadastreLayer.getFeatures()
                        for cadObj in cadObjs:
                            #print 'cadastre check iteration'
                            if cadObj.geometry().isMultipart():
                                for cpoly in cadObj.geometry().asMultiPolygon():
                                    if not findInCadastre:
                                        for cring in cpoly:
                                            cadCurr = 1
                                            if not findInCadastre:
                                                cc = len(cring)
                                                for cpoint in cring:
                                                    if cadCurr < cc:
                                                        cpoint1 = cpoint
                                                        cpoint2 = cring[cadCurr]
                                                        cadCurr += 1
                                                    cadLine=QgsGeometry.fromPolyline([QgsPoint(cpoint1.x(), cpoint1.y()), QgsPoint(cpoint2.x(), cpoint2.y())])
                                                    #print 'checking line'
                                                    if line_geometry.within(cadLine.buffer(0.000001, 16)):
                                                        print 'find in cadastre'
                                                        findInCadastre = True
                                                        break
                                                    else:
                                                        findInCadastre = False
                            else:
                                if not findInCadastre:
                                    for cring in cadObj.geometry().asPolygon():
                                        cadCurr = 1
                                        if not findInCadastre:
                                            cc = len(cring)
                                            for cpoint in cring:
                                                if cadCurr < cc:
                                                    cpoint1 = cpoint
                                                    cpoint2 = cring[cadCurr]
                                                    cadCurr += 1
                                                cadLine=QgsGeometry.fromPolyline([QgsPoint(cpoint1.x(), cpoint1.y()), QgsPoint(cpoint2.x(), cpoint2.y())])
                                                #print 'checking line'
                                                if  line_geometry.within(cadLine.buffer(0.000001, 16)):
                                                    print 'finded in cadastre'
                                                    findInCadastre = True
                                                    break
                                                else:
                                                    findInCadastre = False
                    if not findInCadastre:
                        pt2stst = True
                if not isEqual:
                    feat = QgsFeature()
                    feat.setGeometry(line_geometry)
                    typeidx = layer.fieldNameIndex('type')
                    feat.initAttributes(2)
                    if pt1stst or pt2stst:
                        feat.setAttribute(typeidx, 2)
                    else:
                        feat.setAttribute(typeidx, 0)
                    layer.dataProvider().addFeatures([feat])

    def createBoundPart(self):
        partLayer = self.getLayerByName(u'Части границ')
        if partLayer is not None:
            partLayer.startEditing()
            try:
                for feat in self.iface.mapCanvas().currentLayer().selectedFeatures():
                    geom = feat.geometry()
                    polygone = geom.asMultiPolygon()[0]
                    for ring in polygone:
                        self.createPart(partLayer, ring)
            except Exception as err:
                #self.iface.messageBar().pushMessage(err, QgsMessageBar.ERROR, 5)
                print 'error in createBoundPart!', err
            finally:
                partLayer.commitChanges()
                self.iface.messageBar().pushMessage(u'Создание частей границ завершено',
                                                    level=QgsMessageBar.INFO)

    def doCatalogMapPlan(self):
        pointLayer = self.getLayerByName(u'Точки')
        file_name = QFileDialog.getSaveFileName(None, u'Сохраните ведомость координат для карта(план)', self.lastDir, u'HTML файлы(*.html *.HTML)')
        if not file_name == u'':
            htmldata_start = u'<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=windows-1251"><meta name=ProgId content=Word.Document><meta name=Generator content="Microsoft Word 15"><meta name=Originator content="Microsoft Word 15"></head><body lang=RU link=blue vlink=purple style=\'tab-interval:35.4pt\'><table class=MsoNormalTable border=1 cellspacing=0 cellpadding=0 width=718 style=\'width:19.0cm;margin-left:-1.7pt;border-collapse:collapse;border:none; mso-border-alt:solid windowtext .5pt;mso-yfti-tbllook:1184;mso-padding-alt: 0cm 5.4pt 0cm 5.4pt\'>'
            htmldata_row = u'<tr style=\'mso-yfti-irow:0;mso-yfti-firstrow:yes;mso-yfti-lastrow:yes\'>  <td width=85 style=\'width:63.8pt;border:solid windowtext 1.0pt;mso-border-alt:  solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'>  <p class=MsoNormal style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt:auto\'><span  style=\'font-size:10.0pt;color:black\'>{0}<o:p></o:p></span></p>  </td> <td width=113 valign=top style=\'width:3.0cm;border:solid windowtext 1.0pt;  border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:  solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'>  <p class=MsoNormal align=center style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><span style=\'font-size:10.0pt\'>{1}<o:p></o:p></span></p> </td> <td width=113 valign=top style=\'width:3.0cm;border:solid windowtext 1.0pt;  border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:  solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'>  <p class=MsoNormal align=center style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><span style=\'font-size:10.0pt\'>{2}<o:p></o:p></span></p></td>  <td width=227 valign=top style=\'width:6.0cm;border:solid windowtext 1.0pt;  border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:  solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'>  <p class=MsoNormal align=center style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><span style=\'font-size:10.0pt;color:black\'>{4}<o:p></o:p></span></p></td>  <td width=180 valign=top style=\'width:134.65pt;border:solid windowtext 1.0pt;  border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:  solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'> <p class=MsoNormal align=centerstyle=\'mso-margin-top-alt:auto;mso-margin-bottom-alt:  auto;text-align:center\'><b style=\'mso-bidi-font-weight:normal\'><sub><span style=\'font-size:10.0pt\'>{3}</span></sub></b><spanstyle=\'font-size:10.0pt\'><o:p></o:p></span></p> </td> </tr>'
            htmldata_end = u'</table></body></html>'

            exportData = htmldata_start
            for feat in self.iface.mapCanvas().currentLayer().selectedFeatures():
                polygone = feat.geometry().asPolygon()
                ringq = 0
                for ring in polygone:
                    for pt in ring:
                        for pointfeature in pointLayer.getFeatures():
                            if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(pt.x(), pt.y()))):
                                fullname = unicode(pointfeature.attribute(u'name'))
                                # if fullname[0] == u'н':
                                #     name = fullname[1:]+u';'
                                #     prefix = u'н;'
                                # else:
                                #     name = fullname + u';'
                                #     prefix = u';'

                                x = round(QgsGeometry.fromPoint(pt).asPoint().y(), 2)
                                sx = unicode('{:.2f}'.format(x))
                                y = round(QgsGeometry.fromPoint(pt).asPoint().x(), 2)
                                sy = unicode('{:.2f}'.format(y))
                                exportData += htmldata_row.format(fullname, sx, sy, u'–––––––', u'картометрический')
                                # pref = unicode(pointfeature.attribute(u'prec'))+u';'
                                # hold = unicode(pointfeature.attribute(u'hold'))

                    if len(polygone) >= ringq+2:
                        exportData += htmldata_row.format(u'', u'', u'', u'', u'')
                    ringq += 1
            exportData += htmldata_end
            try:
                ccf = open(file_name, 'w') # + u'.csv'
                ccf.write(exportData.encode('cp1251'))
            except Exception as err:
                print err
            finally:
                ccf.close()

    def exportTechno(self):
        pointLayer = None
        for clayer in self.iface.mapCanvas().layers():
            if clayer.name() == u'Точки': # TODO
                pointLayer = clayer
                break
            else:
                return

        file_name = QFileDialog.getSaveFileName(None, u'Сохраните данные для Технокада', self.lastDir, u'CSV файлы(*.csv *.CSV)')
        #print file_name
        if not file_name == u'':
            csvdata = u'Контур;Префикс номера;Номер;Старый X;Старый Y;Новый X;Новый Y;Метод определения;Формула;Радиус;Погрешность;Описание закрепления\n;;;;;;;;;;;\n'
            #delimLine = u';;;;;;;;;;;\n'

            # crsSrc = QgsCoordinateReferenceSystem(4326)
            # crsDest = QgsCoordinateReferenceSystem()
            # crsDest.createFromProj4(self.current_crs)
            # transform = QgsCoordinateTransform(crsSrc, crsDest)

            contour = 1
            for feat in self.iface.mapCanvas().currentLayer().selectedFeatures():
                geom = feat.geometry()
                if self.isMultiPart(feat):
                    # gt = QgsGeometry(geom)
                    # gt.transform(transform)
                    csvdata += self.prepareExportPoint(pointLayer, geom.asMultiPolygon()[0], 1)
                    if len(self.iface.mapCanvas().currentLayer().selectedFeatures()) > contour:
                        csvdata += u';;;;;;;;;;;\n'
                    contour += 1
                else:
                    # gt = QgsGeometry(geom)
                    # gt.transform(transform)
                    csvdata += self.prepareExportPoint(pointLayer, geom.asMultiPolygon()[0], 1)
            try:
                ccf = open(file_name, 'w') # + u'.csv'
                ccf.write(csvdata.encode('cp1251'))
            except Exception as err:
                print err
                #self.iface.messageBar().pushMessage(u'Ошибка при экспорте в Технокад! ' + err.encode('UTF-8'),
                                                                  # QgsMessageBar.ERROR, 5)
            finally:
                ccf.close()

    def prepareExportPoint(self, pointLayer, polygon, contour):
        ringq = 0
        csvdata = u''
        for ring in polygon:
            for pt in ring:
                for pointfeature in pointLayer.getFeatures():
                    if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(pt.x(), pt.y()))):
                        fullname = unicode(pointfeature.attribute(u'name'))
                        if fullname[0] == u'н':
                            name = fullname[1:]+u';'
                            prefix = u'Н;'
                        else:
                            name = fullname + u';'
                            prefix = u';'

                        x = round(QgsGeometry.fromPoint(pt).asPoint().y(), 2)
                        sx = unicode('{:.2f}'.format(x))+u';'
                        y = round(QgsGeometry.fromPoint(pt).asPoint().x(), 2)
                        sy = unicode('{:.2f}'.format(y))+u';'
                        pref = unicode(pointfeature.attribute(u'prec'))+u';'
                        hold = unicode(pointfeature.attribute(u'hold'))
                        if ringq > 0:
                            cnt = u'['+unicode(str(contour))+u'.'+unicode(str(ringq))+u'];'
                        else:
                            cnt = u'['+unicode(str(contour))+u'];'
                        csvdata += cnt+prefix+name+u';;'+sx+sy+u';;;'+pref+hold+u'\n'

            if len(polygon) >= ringq+2:
                csvdata +=u';;;;;;;;;;;\n'
            ringq += 1

        return csvdata

    # Упорядочить точки (первая на северо-западе)
    def doChangePointPos(self):
        try:
            for feat in self.iface.mapCanvas().currentLayer().selectedFeatures():
                findPointIdx = 0
                #newgeomarr = []
                #newgeom = null
                geom = feat.geometry()
                if self.isMultiPart(feat):
                    polygons = geom.asMultiPolygon()[0]
                    for polygone in polygons:
                        print 'parse multipolygon part'
                        for ring in polygone:
                            findPointIdx = findNorthWestPoint(ring)
                            changeGeometryPointOrder(ring, findPointIdx)
                else:
                    for ring in geom.asMultiPolygon()[0]:
                        findPointIdx = findNorthWestPoint(ring)
                        changeGeometryPointOrder(ring, findPointIdx)
        except:
            print 'error in doChangePointPos'
        finally:
            feat.setGeometry(newgeom)
            print 'change geometry'
        pass

    def findNorthWestPoint(self, ring):
        maxYX = 10000000
        iter = 0
        idx = 0
        for point in ring:
            if iter < len(ring)-1:
                x = point.x()
                y = point.y()
                if (x - y) < maxYX:
                    maxYX = (x - y)
                    idx = iter
                iter += 1
        return iter

    def changeGeometryPointOrder(self, ring, newPointIdx):
        if newPointIdx == 0:
            return ring

        after = ring[newPointIdx:]
        del after[-1]
        firstPoint = after[0]
        before = ring[:newPointIdx]
        after.extend(before)
        after.append(firstPoint)
        ring = after
Example #39
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 #40
0
class FilterClauseWidget(QWidget, Ui_FilterClauseWidget):

    clauseAdded = pyqtSignal()
    clauseRemoved = pyqtSignal(int)
    clauseChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super(FilterClauseWidget, self).__init__(parent)
        self.setupUi(self)

        self._filterIndex = -1
        self._filterType = FilterType.Include
        self._filterActionStatus = -1
        self._siteCode = ''

        self._addIcon = QIcon(':/plugins/ark/filter/addFilter.svg')
        self._addAction = QAction(self._addIcon, 'Add filter', self)
        self._addAction.setStatusTip('Add filter')
        self._addAction.triggered.connect(self._addFilterClicked)

        self._removeIcon = QIcon(':/plugins/ark/filter/removeFilter.svg')
        self._removeAction = QAction(self._removeIcon, 'Remove filter', self)
        self._removeAction.setStatusTip('Remove filter')
        self._removeAction.triggered.connect(self._removeFilterClicked)

        self.setFilterAction(FilterWidgetAction.AddFilter)

        self._includeIcon = QIcon(':/plugins/ark/filter/includeFilter.png')
        self._includeAction = QAction(self._includeIcon, 'Include', self)
        self._includeAction.setStatusTip('Include items in selection')
        self._includeAction.setCheckable(True)
        self._includeAction.triggered.connect(self._includeFilterChecked)

        self._excludeIcon = QIcon(':/plugins/ark/filter/excludeFilter.png')
        self._excludeAction = QAction(self._excludeIcon, 'Exclude', self)
        self._excludeAction.setStatusTip('Exclude items from selection')
        self._excludeAction.setCheckable(True)
        self._excludeAction.triggered.connect(self._excludeFilterChecked)

        self._selectIcon = QIcon(':/plugins/ark/filter/selectFilter.svg')
        self._selectAction = QAction(self._selectIcon, 'Select', self)
        self._selectAction.setStatusTip('Select items')
        self._selectAction.setCheckable(True)
        self._selectAction.triggered.connect(self._selectFilterChecked)

        self._highlightIcon = QIcon(':/plugins/ark/filter/highlightFilter.svg')
        self._highlightAction = QAction(self._highlightIcon, 'Highlight', self)
        self._highlightAction.setStatusTip('Highlight items')
        self._highlightAction.setCheckable(True)
        self._highlightAction.triggered.connect(self._highlightFilterChecked)

        self._typeActionGroup = QActionGroup(self)
        self._typeActionGroup.addAction(self._includeAction)
        self._typeActionGroup.addAction(self._excludeAction)
        self._typeActionGroup.addAction(self._selectAction)
        self._typeActionGroup.addAction(self._highlightAction)

        self._colorTool = QgsColorButtonV2(self)
        self._colorTool.setAllowAlpha(True)
        self._colorTool.setColorDialogTitle('Choose Highlight Color')
        self._colorTool.setContext('Choose Highlight Color')
        self._colorTool.setDefaultColor(Application.highlightFillColor())
        self._colorTool.setToDefaultColor()
        self._colorTool.colorChanged.connect(self._colorChanged)
        self._colorAction = QWidgetAction(self)
        self._colorAction.setDefaultWidget(self._colorTool)

        self._typeMenu = QMenu(self)
        self._typeMenu.addActions(self._typeActionGroup.actions())
        self._typeMenu.addSeparator()
        self._typeMenu.addAction(self._colorAction)
        self.filterTypeTool.setMenu(self._typeMenu)

        self._setFilterType(FilterType.Include)

    def index(self):
        return self._filterIndex

    def setIndex(self, index):
        self._filterIndex = index

    def clause(self):
        cl = FilterClause()
        cl.item = Item(self.siteCode(), self.classCode(), self.filterRange())
        cl.action = self.filterType()
        cl.color = self.color()
        return cl

    def setClause(self, clause):
        self.blockSignals(True)
        self._colorTool.blockSignals(True)
        self._siteCode = clause.item.siteCode()
        self.filterClassCombo.setCurrentIndex(self.filterClassCombo.findData(clause.item.classCode()))
        self.filterRangeCombo.setEditText(clause.item.itemId())
        self._setFilterType(clause.action)
        # self._colorTool.setColor(clause.color)
        self._colorTool.blockSignals(False)
        self.blockSignals(False)

    def _setFilterType(self, filterType):
        self._filterType = filterType
        if filterType == FilterType.Exclude:
            self._excludeAction.setChecked(True)
            self.filterTypeTool.setDefaultAction(self._excludeAction)
        elif filterType == FilterType.Select:
            self._selectAction.setChecked(True)
            self.filterTypeTool.setDefaultAction(self._selectAction)
        elif filterType == FilterType.Highlight:
            self._highlightAction.setChecked(True)
            self.filterTypeTool.setDefaultAction(self._highlightAction)
        else:
            self._includeAction.setChecked(True)
            self.filterTypeTool.setDefaultAction(self._includeAction)

    def filterType(self):
        return self._filterType

    def siteCode(self):
        return self._siteCode

    def setSiteCode(self, siteCode):
        self._siteCode = siteCode

    def classCode(self):
        return self.filterClassCombo.itemData(self.filterClassCombo.currentIndex())

    def filterRange(self):
        return self._normaliseRange(self.filterRangeCombo.currentText())

    def color(self):
        return self._colorTool.color()

    def setClassCodes(self, codes):
        self.filterClassCombo.clear()
        keys = codes.keys()
        keys.sort()
        for key in keys:
            self.filterClassCombo.addItem(codes[key], key)

    def setHistory(self, history):
        self.filterRangeCombo.addItems(history)
        self.filterRangeCombo.clearEditText()

    def history(self):
        history = []
        for idx in range(0, self.filterRangeCombo.count()):
            history.append(self.filterRangeCombo.itemText(idx))
        return history

    def clearFilterRange(self):
        self.filterRangeCombo.clearEditText()

    def setFilterAction(self, action):
        if self._filterActionStatus == FilterWidgetAction.AddFilter:
            self.filterRangeCombo.lineEdit().returnPressed.disconnect(self._addFilterClicked)
        elif self._filterActionStatus == FilterWidgetAction.RemoveFilter:
            self.filterRangeCombo.lineEdit().editingFinished.disconnect(self._filterRangeChanged)
        self._filterActionStatus = action
        if action == FilterWidgetAction.LockFilter:
            self.filterActionTool.removeAction(self._addAction)
            self.filterActionTool.setDefaultAction(self._removeAction)
            self.setEnabled(False)
        elif action == FilterWidgetAction.RemoveFilter:
            self.filterActionTool.removeAction(self._addAction)
            self.filterActionTool.setDefaultAction(self._removeAction)
            self.filterRangeCombo.lineEdit().editingFinished.connect(self._filterRangeChanged)
            self.setEnabled(True)
        else:
            self.filterActionTool.removeAction(self._removeAction)
            self.filterActionTool.setDefaultAction(self._addAction)
            self.filterRangeCombo.lineEdit().returnPressed.connect(self._addFilterClicked)
            self.setEnabled(True)

    def _normaliseRange(self, text):
        return text.replace(' - ', '-').replace(',', ' ').strip()

    def _addFilterClicked(self):
        self.setFilterAction(FilterWidgetAction.RemoveFilter)
        self.clauseAdded.emit()

    def _removeFilterClicked(self):
        self.clauseRemoved.emit(self._filterIndex)

    def _includeFilterChecked(self):
        self._setFilterType(FilterType.Include)
        self.clauseChanged.emit(self._filterIndex)

    def _excludeFilterChecked(self):
        self._setFilterType(FilterType.Exclude)
        self.clauseChanged.emit(self._filterIndex)

    def _highlightFilterChecked(self):
        self._setFilterType(FilterType.Highlight)
        self.clauseChanged.emit(self._filterIndex)

    def _selectFilterChecked(self):
        self._setFilterType(FilterType.Select)
        self.clauseChanged.emit(self._filterIndex)

    def _filterRangeChanged(self):
        self.clauseChanged.emit(self._filterIndex)

    def _colorChanged(self, color):
        pix = QPixmap(22, 22)
        pix.fill(color)
        self._highlightIcon = QIcon(pix)
        self._highlightAction.setIcon(self._highlightIcon)
        self._setFilterType(FilterType.Highlight)
        self.clauseChanged.emit(self._filterIndex)
Example #41
0
class GdalTools:
    def __init__(self, iface):
        if not valid:
            return

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        #self.analysisMenu.addActions( [  ] )

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

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

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

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

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

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

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

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

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

        self.menu.addMenu(self.miscellaneousMenu)

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

    def unload(self):
        if not valid:
            return
        pass

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def doSettings(self):
        from tools.doSettings import GdalToolsSettingsDialog as Settings
        d = Settings(self.iface)
        d.exec_()
Example #42
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]
        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);;Leica IDX (*.idx);;Geodimeter JOB/ARE (*.job *.are);;Sokkia CRD (*.crd);;SurvCE RW5 (*.rw5);;STONEX DAT (*.dat);;Text dump (*.dmp)'))
        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()
                # start with 'fb_'?
                if QRegExp('fb_').indexIn(QFileInfo(ofname).baseName()):
                    ofname = QDir.cleanPath(QFileInfo(ofname).absolutePath() + 
                                    QDir().separator() + 'fb_' + QFileInfo(ofname).fileName())
                # extension is .dbf?
                if QRegExp('\.dbf$', Qt.CaseInsensitive).indexIn(ofname) == -1:
                    ofname += '.dbf'
                tempname = QDir.cleanPath(self.plugin_dir + QDir().separator() + 
                                'template' + QDir().separator() + 'fb_template.dbf')
                if not QFile(tempname).copy(ofname):
                    QMessageBox.warning(self.iface.mainWindow(),
                        tr('File warning'),
                        tr('Error copying fieldbook template, target file exists?'),
                        tr('OK'))
                    return
                fb_dbf = QgsVectorLayer(ofname, QFileInfo(ofname).baseName(), "ogr")
                if not fb_dbf or not fb_dbf.isValid():
                    QMessageBox.warning(self.iface.mainWindow(),
                        tr('File warning'),
                        tr('Fieldbook loading error'),
                        tr('OK'))
                    return
                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)
            elif QRegExp('\.dmp$', Qt.CaseInsensitive).indexIn(fname) > -1:
				fb = Dump(fname)
            elif QRegExp('\.idx$', Qt.CaseInsensitive).indexIn(fname) > -1:
				fb = Idex(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])
                    (xxx, yyy) = fb_dbf.dataProvider().addFeatures([record])
                    if not xxx:
                        QMessageBox.warning(self.iface.mainWindow(),
                            tr('File warning'),
                            tr('Fieldbook record creation error'),
                            tr('OK'))
                        return
                    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")