Esempio n. 1
0
 def keyPressEvent(self, event):
     key = event.key()
     mod = event.modifiers()
     if key == Qt.Key_Up and self.history:
         self.history_i = min(self.history_i+1, len(self.history)-1)
         self.lineInput.setText(self.history[self.history_i])
     elif key == Qt.Key_Down and self.history:
         self.history_i = max(self.history_i-1, -1)
         if self.history_i >= 0:
             self.lineInput.setText(self.history[self.history_i])
         else:
             self.lineInput.setText('')
     elif key == Qt.Key_Enter or key == Qt.Key_Return:
         if mod & Qt.ShiftModifier:
             self.complete()
         else:
             self.run()
     elif key == Qt.Key_Escape:
         txt, r = QInputDialog.getItem(self, QCoreApplication.translate("QPyShell", "Command line history"),
             QCoreApplication.translate("QPyShell", "Please select a history item:"),
             self.history, 0, False)
         if r and txt:
             self.lineInput.setText(txt)
     elif self.standalone and key == Qt.Key_Print:
         self.printContents()
     elif self.standalone and key == Qt.Key_Q and (mod & Qt.ControlModifier):
         self.close()
     else:
         QWidget.keyPressEvent(self, event)
Esempio n. 2
0
 def load(self):
     self.initTranslations()
     cfg = SimuVis4.Globals.config
     cfgsec = self.name.lower()
     if not cfg.has_section(cfgsec):
         cfg.add_section(cfgsec)
     cfg.set_def(cfgsec, 'set_default_backend', 'yes')
     cfg.set_def(cfgsec, 'zoom_step_factor', '0.189207115002721')
     cfg.set_def(cfgsec, 'mouse_wheel_step', '15')
     glb = SimuVis4.Globals
     import matplotlib
     if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion:
         SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \
             (mplMinVersion, mplMaxVersion, matplotlib.__version__))
         return False
     self.matplotlib = matplotlib
     if cfg.getboolean(cfgsec, 'set_default_backend'):
         try:
             sys.path.append(os.path.split(__file__)[0])
             matplotlib.use('module://backend_sv4agg')
         except:
             pass
     import backend_sv4agg
     self.backend_sv4agg = backend_sv4agg
     dpath = matplotlib.rcParams['datapath']
     tmp = os.path.join(dpath, 'images')
     if os.path.isdir(tmp):
         dpath = tmp
     winIcon = QIcon(os.path.join(dpath, 'matplotlib.png'))
     testAction = QAction(winIcon,
         QCoreApplication.translate('MatPlot', '&MatPlot/PyLab Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib/pylab test window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
    def __init__(self, layers):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.__layers = layers
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Edition Confirmation"))
        self.__layout = QGridLayout()

        titleLabel = QLabel(QCoreApplication.translate("VDLTools", "Do you really want to edit these layers ?"))
        self.__layout.addWidget(titleLabel, 0, 0, 1, 2)

        pos = 1
        for layer in self.__layers:
            label = QLabel(" - " + layer.name())
            self.__layout.addWidget(label, pos, 0, 1, 2)
            pos += 1

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        pos = len(self.__layers) + 1
        self.__layout.addWidget(self.__cancelButton, pos, 0)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)
        self.__layout.addWidget(self.__okButton, pos, 1)


        self.setLayout(self.__layout)
 def saveIntersectionResult(self, report, intersectedPoint):
     # save the intersection result (point) and its report
     # check first
     while True:
         if not self.settings.value("advancedIntersectionWritePoint"):
             break  # if we do not place any point, skip
         layerid = self.settings.value("advancedIntersectionLayer")
         message = QCoreApplication.translate("IntersectIt",
                                              "To place the intersection solution,"
                                              " you must select a layer in the settings.")
         status, intLayer = self.checkLayerExists(layerid, message)
         if status == 2:
             continue
         if status == 3:
             return
         if self.settings.value("advancedIntersectionWriteReport"):
             reportField = self.settings.value("reportField")
             message = QCoreApplication.translate("IntersectIt",
                                                  "To save the intersection report, please select a field for it.")
             status = self.checkFieldExists(intLayer, reportField, message)
             if status == 2:
                 continue
             if status == 3:
                 return
         break
     # save the intersection results
     if self.settings.value("advancedIntersectionWritePoint"):
         f = QgsFeature()
         f.setGeometry(QgsGeometry().fromPoint(intersectedPoint))
         if self.settings.value("advancedIntersectionWriteReport"):
             irep = intLayer.dataProvider().fieldNameIndex(reportField)
             f.addAttribute(irep, report)
         intLayer.dataProvider().addFeatures([f])
         intLayer.updateExtents()
         self.mapCanvas.refresh()
Esempio n. 5
0
    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath", QDir.home())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As")
        filename = QFileDialog.getSaveFileName(self,
                                               saveAsFileTr,
                                               pathFileName, "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate('PythonConsole',
                                                     'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                                  error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')
Esempio n. 6
0
    def __init__(self):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Display Attributes Confirmation"))
        self.resize(300, 100)
        self.__layout = QGridLayout()

        self.__confirmLabel = QLabel(
            QCoreApplication.translate("VDLTools",
                                       "Do you want to display the attributes tables for the selected features ?"))

        self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 2)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "Yes"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "No"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__okButton, 1, 0)
        self.__layout.addWidget(self.__cancelButton, 1, 1)

        self.setLayout(self.__layout)
Esempio n. 7
0
 def saveContents(self, fileName=None):
     if not fileName:
         fileTypes = {'Text':('txt',), 'HTML':('htm', 'html')}
         filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()])
         dlg = QFileDialog(self,
             QCoreApplication.translate('QPyShell', 'Select name of file to save'),
             os.getcwd(), filters)
         dlg.setFileMode(QFileDialog.AnyFile)
         dlg.setAcceptMode(QFileDialog.AcceptSave)
         if dlg.exec_() != QDialog.Accepted:
             return
         tmp = unicode(dlg.selectedFilter())
         fileType = tmp[:tmp.find('(')-1]
         dlg.setDefaultSuffix(fileTypes[fileType][0])
         files = dlg.selectedFiles()
         if not files:
             return
         fileName = unicode(files[0])
     if fileType == 'Text':
         txt = self.outputBrowser.toPlainText()
     elif fileType == 'HTML':
         txt = self.outputBrowser.toHtml()
     else:
         raise IOError('Unknown FileType: %s' % fileType)
     try:
         open(fileName, 'w').write(txt)
     except IOError:
         QMessageBox.critical(self,
             QCoreApplication.translate('QPyShell', 'Could not save file!'),
             QCoreApplication.translate('QPyShell', 'Writing failed! Make sure you have write permissions!'))
Esempio n. 8
0
    def initGui(self):
        # Actions
        self.action_convert = QAction(QIcon(path.join(_current_path, 'convert.png')),
                                      QCoreApplication.translate('RuGeocoder', 'Convert CSV to SHP'),
                                      self.iface.mainWindow())
        QObject.connect(self.action_convert, SIGNAL("triggered()"), self.run_convert)

        self.action_batch_geocoding = QAction(QIcon(path.join(_current_path, 'icon.png')),
                                              QCoreApplication.translate('RuGeocoder', 'Batch geocoding'),
                                              self.iface.mainWindow())
        QObject.connect(self.action_batch_geocoding, SIGNAL('triggered()'), self.run_batch)

        self.action_quick_geocoding = self.__quick_tlb.toggleViewAction()
        self.action_quick_geocoding.setIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))
        self.action_quick_geocoding.setText(QCoreApplication.translate('RuGeocoder', '&Quick geocoding toolbox'))

        # Add toolbar button and menu item
        self.toolbar.addAction(self.action_convert)
        self.iface.addPluginToWebMenu(self.menu_name, self.action_convert)

        self.toolbar.addAction(self.action_batch_geocoding)
        self.iface.addPluginToWebMenu(self.menu_name, self.action_batch_geocoding)

        self.toolbar.addSeparator()

        self.toolbar.addAction(self.action_quick_geocoding)
        self.iface.addPluginToWebMenu(self.menu_name, self.action_quick_geocoding)
Esempio n. 9
0
 def itemAction(self, mi,):
     # FIXME: use a MIME-Handler here
     i = self.model.itemFromIndex(mi)
     t, nc = i.ncItem
     QMessageBox.information(self,
             QCoreApplication.translate('NetCDF3', 'netCDF3: Item clicked'),
             QCoreApplication.translate('NetCDF3', 'You clicked an item in the netCDF3-browser'))
Esempio n. 10
0
 def load(self):
     self.initTranslations()
     cfg = SimuVis4.Globals.config
     cfgsec = self.name.lower()
     if not cfg.has_section(cfgsec):
         cfg.add_section(cfgsec)
     cfg.set_def(cfgsec, 'show_config_warning', 'yes')
     glb = SimuVis4.Globals
     import matplotlib
     if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion:
         SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \
             (mplMinVersion, mplMaxVersion, matplotlib.__version__))
         return False
     self.matplotlib = matplotlib
     try:
         matplotlib.use('SV4Agg')
     except:
         if cfg.getboolean(cfgsec, 'show_config_warning'):
             QTimer().singleShot(8000, showConfigWarning)
     import backend_sv4agg
     self.backend_sv4agg = backend_sv4agg
     dpath = matplotlib.rcParams['datapath']
     tmp = os.path.join(dpath, 'images')
     if os.path.isdir(tmp):
         dpath = tmp
     winIcon = QIcon(os.path.join(dpath, 'matplotlib.png'))
     testAction = QAction(winIcon,
         QCoreApplication.translate('MatPlot', '&MatPlot Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib test window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
 def run(self):
     '''
     Runs the widget
     '''
     
     project = PagLuxembourg.main.current_project
     
     if not project.isPagProject():
         return
     
     # Map layers in the TOC
     maplayers = QgsMapLayerRegistry.instance().mapLayers()
     
     # Iterates through XSD types
     for type in PagLuxembourg.main.xsd_schema.types:
         if type.geometry_type is None:
             continue
         
         uri = project.getTypeUri(type)
         found = False
         
         # Check whether a layer with type data source exists in the map
         for k,v in maplayers.iteritems():
             if project.compareURIs(v.source(), uri):
                 found = True
                 layer = v
                 break
         
         if not found:
             continue
         
         self.stylizeLayer(layer, type)
     
     PagLuxembourg.main.qgis_interface.messageBar().pushSuccess(QCoreApplication.translate('StylizeProject','Success'), 
                                                                QCoreApplication.translate('StylizeProject','The layers styling is finished.'))
Esempio n. 12
0
    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip("\n").strip()
        self.name = line
        self.i18n_name = QCoreApplication.translate("TAUDEMAlgorithm", line)
        line = lines.readline().strip("\n").strip()
        self.cmdName = line
        line = lines.readline().strip("\n").strip()
        self.group = line
        self.i18n_group = QCoreApplication.translate("TAUDEMAlgorithm", line)

        line = lines.readline().strip("\n").strip()
        while line != "":
            try:
                line = line.strip("\n").strip()
                if line.startswith("Parameter"):
                    param = getParameterFromString(line)
                    self.addParameter(param)
                else:
                    self.addOutput(getOutputFromString(line))
                line = lines.readline().strip("\n").strip()
            except Exception as e:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    self.tr("Could not load TauDEM algorithm: %s\n%s" % (self.descriptionFile, line)),
                )
                raise e
        lines.close()
Esempio n. 13
0
def removeDir(path):
    result = ""
    if not QFile(path).exists():
        result = QCoreApplication.translate("QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path
    elif QFile(path).remove(): # if it is only link, just remove it without resolving.
        pass
    else:
        fltr = QDir.Dirs | QDir.Files | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QFile(item).remove():
                pass
        fltr = QDir.Dirs | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QDir().rmpath(item):
                pass
    if QFile(path).exists():
        result = QCoreApplication.translate("QgsPluginInstaller", "Failed to remove the directory:") + "\n" + path + "\n" + QCoreApplication.translate("QgsPluginInstaller", "Check permissions or remove it manually")
    # restore plugin directory if removed by QDir().rmpath()
    pluginDir = qgis.utils.home_plugin_path
    if not QDir(pluginDir).exists():
        QDir().mkpath(pluginDir)
    return result
Esempio n. 14
0
    def __init__(self, message):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Edition Confirmation"))
        self.resize(300, 100)
        self.__layout = QGridLayout()

        self.__confirmLabel = QLabel(message)

        self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 2)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "Yes"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(300)

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "No"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__okButton, 1, 0)
        self.__layout.addWidget(self.__cancelButton, 1, 1)

        self.setLayout(self.__layout)
Esempio n. 15
0
    def test(self):
        if not self.winManager:
            return
        from PyQt4.QtGui import QGraphicsScene, QGraphicsItem, QGraphicsLineItem
        from PyQt4.QtCore import QRectF, QLineF
        w = self.winManager.newWindow()
        scene = QGraphicsScene(w.graphicsView)
        scene.addItem(Items.Grid())
        scene.addItem(Items.Axes())

        line = scene.addLine(QLineF(0, 0, 0, 0))

        cross = Items.NodeCross(movable=True)
        cross.addEdge(line, 1)
        scene.addItem(cross)

        help = scene.addText(QCoreApplication.translate('Graphics', 'Press "h" for help!'))
        help.moveBy(-50, 80)

        text = Items.NodeText(QCoreApplication.translate('Graphics', 'Drag Me!'))
        text.setFlag(QGraphicsItem.ItemIsMovable, True)
        text.setFlag(QGraphicsItem.ItemIsSelectable, True)
        text.addEdge(line, 2)
        scene.addItem(text)
        w.graphicsView.setScene(scene)
Esempio n. 16
0
  def switchToolMode( self ):
      self.setCommandViewerEnabled( not self.batchCheck.isChecked() )
      self.progressBar.setVisible( self.batchCheck.isChecked() )

      self.inSelector.setType( self.inSelector.FILE if self.batchCheck.isChecked() else self.inSelector.FILE_LAYER )
      self.outSelector.clear()

      if self.batchCheck.isChecked():
        self.inFileLabel = self.label.text()
        self.outFileLabel = self.label_2.text()
        self.label.setText( QCoreApplication.translate( "GdalTools", "&Input directory" ) )
        self.label_2.setText( QCoreApplication.translate( "GdalTools", "&Output directory" ) )

        QObject.disconnect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile )
        QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit )

        QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir )
        QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir )
      else:
        self.label.setText( self.inFileLabel )
        self.label_2.setText( self.outFileLabel )

        QObject.disconnect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir )
        QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir )

        QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile )
        QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit )
Esempio n. 17
0
    def __onOk(self):
        """
        When the Ok button in Show Settings Dialog is pushed
        """
        values = self.__showDlg.levelVal().split(',')
        for v in values:
            if not v.isdigit():
                QMessageBox.information(
                    None, QCoreApplication.translate("VDLTools", "Error"),
                    QCoreApplication.translate("VDLTools", "Point code attribute has to be numbers separated by comma")
                )
                return

        self.__showDlg.accept()
        self.linesLayer = self.__showDlg.linesLayer()
        self.pointsLayer = self.__showDlg.pointsLayer()
        self.configTable = self.__showDlg.configTable()
        self.uriDb = self.__showDlg.uriDb()
        self.ctlDb = self.__showDlg.ctlDb()
        self.schemaDb = self.__showDlg.schemaDb()
        self.mntUrl = self.__showDlg.mntUrl()
        self.refLayers = self.__showDlg.refLayers()
        self.adjLayers = self.__showDlg.adjLayers()
        self.levelAtt = self.__showDlg.levelAtt()
        self.levelVals = self.__showDlg.levelVal()
        self.drawdownLayer = self.__showDlg.drawdownLayer()
        self.pipeDiam = self.__showDlg.pipeDiam()
        self.changedSignal.emit()
Esempio n. 18
0
    def __checkSituations(self):
        """
        To check if point with no elevation on line, and one or more elevation from other layers,
        and if there are different elevations at the same point
        """
        situations = []
        differences = []
        for p in range(len(self.__points)):
            pt = self.__points[p]
            num_lines = len(self.__selectedIds)
            zz = []
            for i in range(num_lines):
                if pt['z'][i] is not None:
                    zz.append(i)
            if len(zz) == 0:
                self.__iface.messageBar().pushMessage(
                    QCoreApplication.translate("VDLTools", "No line z ?!?"), level=QgsMessageBar.WARNING)
            elif len(zz) == 1:
                z0 = pt['z'][zz[0]]
                for i in range(num_lines, len(pt['z'])):
                    if pt['z'][i] is None:
                        continue
                    if abs(pt['z'][i]-z0) > self.ALT_TOLERANCE:
                        situations.append({'point': p, 'layer': (i-num_lines+1), 'vertex': z0})
            elif len(zz) == 2:
                z0 = pt['z'][zz[0]]
                if abs(pt['z'][zz[1]] - z0) > self.ALT_TOLERANCE:
                    differences.append({'point': p, 'v1': z0, 'v2': pt['z'][zz[1]]})
                else:
                    for i in range(num_lines, len(pt['z'])):
                        if pt['z'][i] is None:
                            continue
                        if abs(pt['z'][i]-z0) > self.ALT_TOLERANCE:
                            situations.append({'point': p, 'layer': (i-num_lines+1), 'vertex': z0})
            else:
                self.__iface.messageBar().pushMessage(
                    QCoreApplication.translate("VDLTools", "More than 2 lines z ?!?"), level=QgsMessageBar.WARNING)

        if (len(situations) > 0) or (len(differences) > 0):
            self.__setMessageDialog(situations, differences, self.__getNames())
            self.__rubberSit.reset()
            self.__rubberDif.reset()
            for situation in situations:
                pt = self.__points[situation['point']]
                point = QgsPoint(pt['x'], pt['y'])
                if self.__rubberSit.numberOfVertices() == 0:
                    self.__rubberSit.setToGeometry(QgsGeometry().fromPoint(point), None)
                else:
                    self.__rubberSit.addPoint(point)
            for difference in differences:
                pt = self.__points[difference['point']]
                point = QgsPoint(pt['x'], pt['y'])
                if self.__rubberDif.numberOfVertices() == 0:
                    self.__rubberDif.setToGeometry(QgsGeometry().fromPoint(point), None)
                else:
                    self.__rubberDif.addPoint(point)

            self.__msgDlg.show()
        else:
            self.__checkZeros()
Esempio n. 19
0
 def defineCharacteristicsFromFile(self):
     lines = open(self.descriptionFile)
     line = lines.readline().strip('\n').strip()
     self.name = line
     if '|' in self.name:
         tokens = self.name.split('|')
         self.name = tokens[0]
         self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name))
         self.cmdname = tokens[1]
     else:
         self.cmdname = self.name
         self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name))
         self.name = self.name[0].upper() + self.name[1:].lower()
     line = lines.readline().strip('\n').strip()
     self.undecoratedGroup = line
     self.group = SagaGroupNameDecorator.getDecoratedName(self.undecoratedGroup)
     self.i18n_group = QCoreApplication.translate("SAGAAlgorithm", self.group)
     line = lines.readline().strip('\n').strip()
     while line != '':
         if line.startswith('Hardcoded'):
             self.hardcodedStrings.append(line[len('Harcoded|') + 1:])
         elif line.startswith('Parameter'):
             self.addParameter(getParameterFromString(line))
         elif line.startswith('AllowUnmatching'):
             self.allowUnmatchingGridExtents = True
         elif line.startswith('Extent'):
             # An extent parameter that wraps 4 SAGA numerical parameters
             self.extentParamNames = line[6:].strip().split(' ')
             self.addParameter(ParameterExtent(self.OUTPUT_EXTENT,
                               'Output extent', '0,1,0,1'))
         else:
             self.addOutput(getOutputFromString(line))
         line = lines.readline().strip('\n').strip()
     lines.close()
Esempio n. 20
0
    def load(self):
        self.initTranslations()
        import vtk, VtkWidget, VtkWindow, Objects, Helpers
        self.vtk = vtk
        self.VtkWidget = VtkWidget
        self.VtkWindow = VtkWindow
        self.Objects = Objects
        self.Helpers = Helpers
        xpm = QPixmap()
        xpm.loadFromData(self.getFile('3dwin.xpm').read())
        winIcon = QIcon(xpm)
        self.winManager = SubWinManager(glb.mainWin.workSpace, self.VtkWindow.VtkWindow,
                QCoreApplication.translate('VtkWindow', "Vtk Window"), winIcon)
        testAction = QAction(winIcon,
            QCoreApplication.translate('VtkWindow', '&VtkWindow Test'), glb.mainWin)
        testAction.setStatusTip(QCoreApplication.translate('VtkWindow', 'Show a new Vtk test window'))
        QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
        glb.mainWin.plugInMenu.addAction(testAction)

        ftActions = glb.fileTypeActions
        ftActions.addType('application/x-3ds', '.3ds')
        ftActions.addAction(self.show3DS, ('application/x-3ds',),
            QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5)
        ftActions.addType('application/x-vrml', '.wrl')
        ftActions.addAction(self.showVRML, ('application/x-vrml',),
            QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5)

        return True
Esempio n. 21
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setWindowTitle(QCoreApplication.translate("SettingsDialogPythonConsole", "Settings Python Console"))
        self.parent = parent
        self.setupUi(self)

        self.listPath = []
        self.lineEdit.setReadOnly(True)

        self.restoreSettings()
        self.initialCheck()

        self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.png"))
        self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path"))
        self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.png"))
        self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path"))

        self.preloadAPI.stateChanged.connect(self.initialCheck)
        self.addAPIpath.clicked.connect(self.loadAPIFile)
        self.removeAPIpath.clicked.connect(self.removeAPI)
        self.compileAPIs.clicked.connect(self._prepareAPI)

        self.resetFontColor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png"))
        self.resetFontColor.setIconSize(QSize(18, 18))
        self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png"))
        self.resetFontColorEditor.setIconSize(QSize(18, 18))
        self.resetFontColor.clicked.connect(self._resetFontColor)
        self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor)
Esempio n. 22
0
    def run(self):
        if QSettings().value("addressLookup/mode") == 3 and self.internet_on() == True: # Nur Hintergrundkarte laden
            self.addBingAerial()
            self.canvas.refresh()
            self.canvas.mapCanvasRefreshed.connect(self.zoomStandard)
        elif QSettings().value("addressLookup/mode") == 1 and self.internet_on() == True: # Gesamte Prozedur
            self.addBingAerial()
            chk = self.check_settings()
            try:
                from geopy.geocoders.osm import Nominatim
            except:
                QMessageBox.information(self.iface.mainWindow(),QCoreApplication.translate('GeoCoding', "Geopy konnte nicht importiert werden."), "Geopy konnte nicht importiert werden.")

            if len(chk) :
                QMessageBox.information(self.iface.mainWindow(),QCoreApplication.translate('GeoCoding', "GeoCoding plugin error"), chk)
                self.zoomToPoint(self.defaultPoint, 2200000)
                return
            #Import geopy
            try:
                geocoder = Nominatim()
            except AttributeError, e:
                QMessageBox.information(self.iface.mainWindow(), QCoreApplication.translate('GeoCoding', "GeoCoding plugin error"), QCoreApplication.translate('GeoCoding', "Couldn't import Python module 'geopy.geocoders' for communication with geocoders. The problem is most probably caused by other plugins shipping with obsolete geopy versions. Please try to uninstall all other Python plugins and retry.<br>Message: %s" % e))
                self.zoomToPoint(self.defaultPoint, 2200000)
                return
            except ImportError, e:
                QMessageBox.information(self.iface.mainWindow(), QCoreApplication.translate('GeoCoding', "GeoCoding plugin error"), QCoreApplication.translate('GeoCoding', "Couldn't import Python module 'geopy' for communication with geocoders. Without it you won't be able to run GeoCoding plugin. Please report this error on the <a href=\"https://github.com/elpaso/qgis-geocoding/issues\">bug tracker</a>.<br>Message: %s" % e))
                self.zoomToPoint(self.defaultPoint, 2200000)
                return
Esempio n. 23
0
    def __init__(self):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Move/Copy Confirmation"))
        self.resize(300, 100)
        self.__layout = QGridLayout()

        self.__confirmLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Would you like to move or to copy this feature ?"))

        self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 3)

        self.__moveButton = QPushButton(QCoreApplication.translate("VDLTools", "Move"))
        self.__moveButton.setMinimumHeight(20)
        self.__moveButton.setMinimumWidth(100)

        self.__copyButton = QPushButton(QCoreApplication.translate("VDLTools", "Copy"))
        self.__copyButton.setMinimumHeight(20)
        self.__copyButton.setMinimumWidth(100)

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__moveButton, 1, 0)
        self.__layout.addWidget(self.__copyButton, 1, 1)
        self.__layout.addWidget(self.__cancelButton, 1, 2)

        self.setLayout(self.__layout)
Esempio n. 24
0
def startServerPlugin(packageName):
    """ initialize the plugin """
    global server_plugins, server_active_plugins, serverIface

    if packageName in server_active_plugins:
        return False
    if packageName not in sys.modules:
        return False

    package = sys.modules[packageName]

    errMsg = QCoreApplication.translate("Python", "Couldn't load server plugin %s") % packageName

    # create an instance of the plugin
    try:
        server_plugins[packageName] = package.serverClassFactory(serverIface)
    except:
        _unloadPluginModules(packageName)
        msg = (
            QCoreApplication.translate("Python", "%s due to an error when calling its serverClassFactory() method")
            % errMsg
        )
        showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg)
        return False

    # add to active plugins
    server_active_plugins.append(packageName)
    return True
Esempio n. 25
0
 def loadFile(self):
     mnFileName = unicode(self.mnFileNameInput.text())
     if not mnFileName:
         QMessageBox.warning(glb.mainWin,
             QCoreApplication.translate('SmileKit', 'No filename specified'),
             QCoreApplication.translate('SmileKit', 'Please enter a filename in the input box!'))
         return
     progressDlg = QProgressDialog(glb.mainWin)
     progressDlg.setRange(0, 100)
     progressDlg.setLabelText('Reading File...')
     progressDlg.show()
     a = glb.application
     def progFunc(p):
         progressDlg.setValue(p)
         if a.hasPendingEvents():
             a.processEvents()
     r = readMnFile(mnFileName, progress=progFunc)
     self.data = r
     progressDlg.close()
     self.locationFrame.setEnabled(1)
     self.statisticsFrame.setEnabled(1)
     if ncOk:
         self.ncFileFrame.setEnabled(1)
     self.statisticsButton.setCheckState(Qt.Unchecked)
     self.locNameInput.setText(r['name'])
     c = unicode(QCoreApplication.translate('SmileKit', "created %s from %s by Meteo2Nc.py (v%d)"))
     self.locCommentInput.setText(c % (time.ctime(), mnFileName, version))
     self.locLatitudeInput.setValue(r['latitude'])
     self.locLongitudeInput.setValue(r['longitude'])
     self.locHeightInput.setValue(r['height'])
     self.locTimeZoneInput.setValue(r['timezone'])
     path, tmp = os.path.split(mnFileName)
     ncFileName = os.path.join(path, makeFileName(r['name'])+'_weather.nc')
     self.ncFileNameInput.setText(ncFileName)
Esempio n. 26
0
    def collectVersions(self):
        csw = Misc.Switcher(0, "#ffffff", "#eeeeee")
        buf = ['<table><tr bgcolor="#dddddd"><th>Component/Library</th><th>Version</th></tr>']
        buf.append('<tr bgcolor="%s"><td>SimuVis4</td><td>%s</td></tr>' % (csw(), Globals.version_string))
        buf.append('<tr bgcolor="%s"><td>Python</td><td>%s | %s</td></tr>' % \
            (csw(), '.'.join([str(i) for i in sys.version_info]), sys.version))
        buf.append('<tr bgcolor="%s"><td>PyQt</td><td>%s | %s</td></tr>' % (csw(), PYQT_VERSION_STR, PYQT_VERSION))
        buf.append('<tr bgcolor="%s"><td>Qt</td><td>%s</td></tr>' % (csw(), qVersion()))

        if sys.modules.has_key('vtk'):
            v = sys.modules['vtk'].vtkVersion.GetVTKVersion()
            vl = sys.modules['vtk'].vtkVersion.GetVTKSourceVersion()
            buf.append('<tr bgcolor="%s"><td>Vtk</td><td>%s | %s</td></tr>' % (csw(), v, vl))

        if sys.modules.has_key('OpenGL'):
            v = sys.modules['OpenGL'].__version__
            buf.append('<tr bgcolor="%s"><td>PyOpenGL</td><td>%s</td></tr>' % (csw(), v))

        for p in Globals.mainWin.plugInManager.plugIns.values():
            buf.append('<tr bgcolor="%s"><td>PlugIn: %s</td><td>%s</td></tr>' % (csw(), p.name, p.version))

        if sys.platform == 'linux2':
            n = QCoreApplication.translate('AboutDlg', 'Operating System')
            d = getLinuxDistro()
            k = os.popen('uname -o -s -r', 'r').readlines()[0]
            buf.append('<tr bgcolor="%s"><td>%s</td><td>%s (%s)</td></tr>' % (csw(), n, d, k))

        if sys.platform == 'win32':
            n = QCoreApplication.translate('AboutDlg', 'Operating System')
            v, vs = getWindowsVersion()
            buf.append('<tr bgcolor="%s"><td>%s</td><td>%s</td></tr>' % (csw(), n, vs))

        buf.append('</table>')
        self.VersionView.setHtml('\n'.join(buf))
Esempio n. 27
0
 def __init__(self, parent):
     SubWindow.__init__(self, parent)
     icon = QIcon(QPixmap(os.path.join(Globals.config['main:system_picture_path'], 'logwin.xpm')))
     self.setWindowIcon(icon)
     self.setWindowTitle(QCoreApplication.translate('LogWindow', 'Log Messages'))
     self.setMinimumSize(500, 100)
     self.logView = LogViewWidget(self)
     self.setWidget(self.logView)
     tmp = Globals.logLevels.items()
     tmp.sort(lambda a,b: cmp(a[1], b[1]))
     self.levels = [l[0] for l in tmp]
     self.logView.ThresholdSelector.addItems(self.levels)
     self.handler = TextBrowserHandler()
     self.handler.setBrowser(self.logView.TextArea, self)
     try:
         i = self.levels.index(Globals.config['main:log_threshold'])
         self.logView.ThresholdSelector.setCurrentIndex(i)
         self.setThreshold(i)
     except:
         self.logView.ThresholdSelector.setCurrentIndex(0)
         self.setThreshold(0)
     self.connect(self.logView.SaveButton, SIGNAL("pressed()"), self.saveWindow)
     self.connect(self.logView.ThresholdSelector, SIGNAL("activated(int)"), self.setThreshold)
     self.hideOnClose = True
     self.toggleVisibleAction.setIcon(icon)
     self.toggleVisibleAction.setText(QCoreApplication.translate('LogWindow', '&Log window'))
     self.toggleVisibleAction.setShortcut(QCoreApplication.translate('LogWindow', 'Ctrl+L'))
     self.toggleVisibleAction.setStatusTip(QCoreApplication.translate('LogWindow', 'Log window'))
Esempio n. 28
0
 def saveWindow(self, fileName=None, fileType=None):
     if not fileName:
         fileTypes = {'Text':('txt',), 'HTML':('htm', 'html')}
         filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()])
         dlg = QFileDialog(self,
             QCoreApplication.translate('LogWindow', 'Select name of file to save'),
             Globals.defaultFolder or '', filters)
         dlg.setFileMode(QFileDialog.AnyFile)
         dlg.setAcceptMode(QFileDialog.AcceptSave)
         if dlg.exec_() != QDialog.Accepted:
             return
         tmp = str(dlg.selectedFilter())
         fileType = tmp[:tmp.find('(')-1]
         dlg.setDefaultSuffix(fileTypes[fileType][0])
         files = dlg.selectedFiles()
         if not files:
             return
         fileName = unicode(files[0])
         Globals.defaultFolder, tmp = os.path.split(fileName)
     if fileType == 'Text':
         txt = self.logView.TextArea.toPlainText()
     elif fileType == 'HTML':
         txt = self.logView.TextArea.toHtml()
     else:
         raise Errors.IOError('Unknown FileType: %s' % fileType)
     try:
         open(fileName, 'w').write(txt)
     except IOError:
         QMessageBox.critical(self,
             QCoreApplication.translate('LogWindow', 'Could not save file!'),
             QCoreApplication.translate('LogWindow', 'Writing failed! Make sure you have write permissions!'))
Esempio n. 29
0
    def initGui(self):
        """startup"""

        # run
        run_icon = QIcon('%s/%s' % (self.context.ppath,
                                    'images/MetaSearch.png'))
        self.action_run = QAction(run_icon, 'MetaSearch',
                                  self.iface.mainWindow())
        self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch',
                                     'MetaSearch plugin'))
        self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch',
                                     'Search Metadata Catalogues'))

        self.action_run.triggered.connect(self.run)

        self.iface.addToolBarIcon(self.action_run)
        self.iface.addPluginToWebMenu(self.web_menu, self.action_run)

        # help
        help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png'))
        self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow())
        self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch',
                                      'MetaSearch plugin help'))
        self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch',
                                      'Get Help on MetaSearch'))
        self.action_help.triggered.connect(self.help)

        self.iface.addPluginToWebMenu(self.web_menu, self.action_help)

        # prefab the dialog but not open it yet
        self.dialog = MetaSearchDialog(self.iface)
Esempio n. 30
0
def startPlugin(packageName):
  """ initialize the plugin """
  global plugins, active_plugins, iface

  if packageName in active_plugins: return False

  package = sys.modules[packageName]

  errMsg = QCoreApplication.translate("Python", "Couldn't load plugin %1" ).arg(packageName)

  # create an instance of the plugin
  try:
    plugins[packageName] = package.classFactory(iface)
  except:
    _unloadPluginModules(packageName)
    msg = QCoreApplication.translate("Python", "%1 due an error when calling its classFactory() method").arg(errMsg)
    showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg)
    return False

  # initGui
  try:
    plugins[packageName].initGui()
  except:
    del plugins[packageName]
    _unloadPluginModules(packageName)
    msg = QCoreApplication.translate("Python", "%1 due an error when calling its initGui() method" ).arg( errMsg )
    showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg)
    return False

  # add to active plugins
  active_plugins.append(packageName)

  return True
Esempio n. 31
0
def tr(text):
    """We define a tr() alias here since the utilities implementation below
    is not a class and does not inherit from QObject.

    .. note:: see http://tinyurl.com/pyqt-differences

    :param text: String to be translated
    :type text: str, unicode

    :returns: Translated version of the given string if available, otherwise
        the original string.
    :rtype: str, unicode
    """
    # Ensure it's in unicode
    text = get_unicode(text)
    # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
    return QCoreApplication.translate('@default', text)
Esempio n. 32
0
def saveDialog(parent, filtering="Shapefiles (*.shp *.SHP)"):
    settings = QSettings()
    dirName = settings.value("/UI/lastShapefileDir")
    encode = settings.value("/UI/encoding")
    fileDialog = QgsEncodingFileDialog(
        parent, QCoreApplication.translate("fTools", "Save output shapefile"),
        dirName, filtering, encode)
    fileDialog.setDefaultSuffix("shp")
    fileDialog.setFileMode(QFileDialog.AnyFile)
    fileDialog.setAcceptMode(QFileDialog.AcceptSave)
    fileDialog.setConfirmOverwrite(True)
    if not fileDialog.exec_() == QDialog.Accepted:
        return None, None
    files = fileDialog.selectedFiles()
    settings.setValue("/UI/lastShapefileDir",
                      QFileInfo(unicode(files[0])).absolutePath())
    return (unicode(files[0]), unicode(fileDialog.encoding()))
Esempio n. 33
0
def unloadPlugin(packageName):
  """ unload and delete plugin! """
  global plugins, active_plugins
  
  if not plugins.has_key(packageName): return False
  if packageName not in active_plugins: return False

  try:
    plugins[packageName].unload()
    del plugins[packageName]
    active_plugins.remove(packageName)
    _unloadPluginModules(packageName)
    return True
  except Exception, e:
    msg = QCoreApplication.translate("Python", "Error while unloading plugin %1").arg(packageName)
    showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg)
    return False
Esempio n. 34
0
def sql_load_fr_db(sql, dbconnection=None):
    try:
        if not isinstance(dbconnection, DbConnectionManager):
            dbconnection = DbConnectionManager()
        result = dbconnection.execute_and_fetchall(sql)
    except Exception as e:
        textstring = utils.returnunicode(
            QCoreApplication.translate(
                u'sql_load_fr_db',
                u"""DB error!\n SQL causing this error:%s\nMsg:\n%s""")) % (
                    utils.returnunicode(sql), utils.returnunicode(str(e)))
        utils.MessagebarAndLog.warning(bar_msg=utils.sql_failed_msg(),
                                       log_msg=textstring,
                                       duration=4)
        return False, []
    else:
        return True, result
Esempio n. 35
0
    def switchToolMode(self):
        self.setCommandViewerEnabled(not self.batchCheck.isChecked())
        self.progressBar.setVisible(self.batchCheck.isChecked())
        self.recurseCheck.setVisible(self.batchCheck.isChecked())

        self.inSelector.clear()

        if self.batchCheck.isChecked():
            self.inFileLabel = self.label.text()
            self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory"))

            QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
            QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir)
        else:
            self.label.setText(self.inFileLabel)

            QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
            QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir)
Esempio n. 36
0
 def __init__(self, iface):
     """
     Constructor
     :param iface: interface
     """
     QgsMapTool.__init__(self, iface.mapCanvas())
     self.__iface = iface
     self.__canvas = iface.mapCanvas()
     self.__icon_path = ':/plugins/VDLTools/icons/intersect_icon.png'
     self.__text = QCoreApplication.translate("VDLTools",
                                              "From intersection")
     self.setCursor(Qt.ArrowCursor)
     self.__lineLayerID = None
     self.__pointLayerID = None
     self.__counter = 0
     self.__rubber = None
     self.__ownSettings = None
     self.__isEditing = 0
 def contextMenuEvent(self, e):
     menu = QMenu(self)
     iconRun = QgsApplication.getThemeIcon("console/iconRunConsole.png")
     iconClear = QgsApplication.getThemeIcon("console/iconClearConsole.png")
     iconHideTool = QgsApplication.getThemeIcon("console/iconHideToolConsole.png")
     iconSettings = QgsApplication.getThemeIcon("console/iconSettingsConsole.png")
     menu.addAction(iconHideTool,
         QCoreApplication.translate("PythonConsole", "Hide/Show Toolbar"),
         self.hideToolBar)
     menu.addSeparator()
     showEditorAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Show Editor"),
         self.showEditor)
     menu.addSeparator()
     runAction = menu.addAction(iconRun,
         QCoreApplication.translate("PythonConsole", "Enter Selected"),
         self.enteredSelected,
         QKeySequence(Qt.CTRL + Qt.Key_E))
     clearAction = menu.addAction(iconClear,
         QCoreApplication.translate("PythonConsole", "Clear console"),
         self.clearConsole)
     menu.addSeparator()
     copyAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Copy"),
         self.copy, QKeySequence.Copy)
     menu.addSeparator()
     selectAllAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Select All"),
         self.selectAll, QKeySequence.SelectAll)
     menu.addSeparator()
     menu.addAction(iconSettings,
         QCoreApplication.translate("PythonConsole", "Settings"),
         self.parent.openSettings)
     runAction.setEnabled(False)
     clearAction.setEnabled(False)
     copyAction.setEnabled(False)
     selectAllAction.setEnabled(False)
     showEditorAction.setEnabled(True)
     if self.hasSelectedText():
         runAction.setEnabled(True)
         copyAction.setEnabled(True)
     if not self.text(3) == '':
         selectAllAction.setEnabled(True)
         clearAction.setEnabled(True)
     if self.parent.tabEditorWidget.isVisible():
         showEditorAction.setEnabled(False)
     menu.exec_(self.mapToGlobal(e.pos()))
Esempio n. 38
0
    def _(s, context=u'script'):
        """
		Translates a string of text.

		Arguments:
		s			--	The string to translate.

		Keyword arguments:
		context		--	The translation context. (default=u'script')

		Returns:
		The translated string.
		"""

        return str(
            QCoreApplication.translate(context,
                                       s,
                                       encoding=QCoreApplication.UnicodeUTF8))
Esempio n. 39
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/QuickDigitize/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Quick Digitize'),
                        callback=self.run,
                        parent=self.iface.mainWindow())
        self.settingsAction = QAction(
            QCoreApplication.translate("Spline", "Settings"),
            self.iface.mainWindow())
        self.settingsAction.setObjectName("splineAction")
        self.settingsAction.triggered.connect(self.openSettings)

        self.iface.addPluginToVectorMenu(u"Digitize Spline",
                                         self.settingsAction)

        self.settingsAction.triggered.connect(self.openSettings)
Esempio n. 40
0
 def __init__(self, iface):
     """
     Constructor
     :param iface: interface
     """
     QgsMapTool.__init__(self, iface.mapCanvas())
     self.__iface = iface
     self.icon_path = ':/plugins/VDLTools/icons/duplicate_icon.png'
     self.text = QCoreApplication.translate("VDLTools",
                                            "Duplicate a feature")
     self.setCursor(Qt.ArrowCursor)
     self.__isEditing = False
     self.__layer = None
     self.__lastFeatureId = None
     self.__selectedFeature = None
     self.__rubberBand = None
     self.__newFeature = None
     self.__dstDlg = None
Esempio n. 41
0
def handleAlgorithmResults(alg, progress=None, showResults=True):
    wrongLayers = []
    htmlResults = False
    if progress is None:
        progress = SilentProgress()
    progress.setText(QCoreApplication.translate('Postprocessing', 'Loading resulting layers'))
    i = 0
    for out in alg.outputs:
        progress.setPercentage(100 * i / float(len(alg.outputs)))
        if out.hidden or not out.open:
            continue
        if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
            try:
                if out.value.startswith('memory:'):
                    layer = out.memoryLayer
                    QgsMapLayerRegistry.instance().addMapLayers([layer])
                else:
                    if ProcessingConfig.getSetting(
                            ProcessingConfig.USE_FILENAME_AS_LAYER_NAME):
                        name = os.path.basename(out.value)
                    else:
                        name = out.description
                    dataobjects.load(out.value, name, alg.crs,
                                     RenderingStyles.getStyle(alg.commandLineName(),
                                                              out.name))
            except Exception as e:
                wrongLayers.append(out.description)
        elif isinstance(out, OutputHTML):
            ProcessingResults.addResult(out.description, out.value)
            htmlResults = True
        i += 1

    QApplication.restoreOverrideCursor()
    if wrongLayers:
        msg = "The following layers were not correctly generated.<ul>"
        msg += "".join(["<li>%s</li>" % lay for lay in wrongLayers]) + "</ul>"
        msg += "You can check the log messages to find more information about the execution of the algorithm"
        progress.error(msg)

    if showResults and htmlResults and not wrongLayers:
        dlg = ResultsDialog()
        dlg.exec_()

    return len(wrongLayers) == 0
Esempio n. 42
0
def __getMasterPassword():
    """
    Private module function to get the password from the user.
    """
    global MasterPassword

    pw, ok = QInputDialog.getText(
        None,
        QCoreApplication.translate("Crypto", "Master Password"),
        QCoreApplication.translate("Crypto", "Enter the master password:"******"MasterPassword")
        try:
            if masterPassword:
                if verifyPassword(pw, masterPassword):
                    MasterPassword = pwEncode(pw)
                else:
                    E5MessageBox.warning(
                        None,
                        QCoreApplication.translate(
                            "Crypto", "Master Password"),
                        QCoreApplication.translate(
                            "Crypto",
                            """The given password is incorrect."""))
            else:
                E5MessageBox.critical(
                    None,
                    QCoreApplication.translate("Crypto", "Master Password"),
                    QCoreApplication.translate(
                        "Crypto",
                        """There is no master password registered."""))
        except ValueError as why:
            E5MessageBox.warning(
                None,
                QCoreApplication.translate("Crypto", "Master Password"),
                QCoreApplication.translate(
                    "Crypto",
                    """<p>The given password cannot be verified.</p>"""
                    """<p>Reason: {0}""".format(str(why))))
Esempio n. 43
0
def delete_srids(execute_able_object, keep_epsg_code):
    if isinstance(execute_able_object, DbConnectionManager):
        if not execute_able_object.dbtype == u'spatialite':
            return None

    delete_srid_sql_aux = r"""delete from spatial_ref_sys_aux where srid NOT IN ('%s', '4326');""" % keep_epsg_code
    try:
        execute_able_object.execute(delete_srid_sql_aux)
    except:
        pass

    delete_srid_sql = r"""delete from spatial_ref_sys where srid NOT IN ('%s', '4326');""" % keep_epsg_code
    try:
        execute_able_object.execute(delete_srid_sql)
    except:
        utils.MessagebarAndLog.info(log_msg=utils.returnunicode(
            QCoreApplication.translate(u'delete_srids',
                                       u'Removing srids failed using: %s')) %
                                    str(delete_srid_sql))
Esempio n. 44
0
 def closeAndControl(self):
     self.projectFinder.close()
     for search in self.projectFinder.searches.values():
         if search.dateEvaluated is None:
             box = QMessageBox(
                 QMessageBox.Warning, "Quick Finder",
                 QCoreApplication.translate(
                     "Configuration dialog",
                     "Some searches are still not recorded to the file. Do you want to record them now ? "
                 ),
                 QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.Close,
                 self)
             ret = box.exec_()
             if ret == QMessageBox.Cancel:
                 return False
             elif ret == QMessageBox.Yes:
                 self.refreshProjectSearch()
                 return False
     return True
Esempio n. 45
0
    def paintEvent(self, event):
        """ redraws the whole widget's area """

        PyQt4.QtGui.QFrame.paintEvent(self, event)

        # check whether there's a survey to show
        if len(self.sondaggio) == 0:
            p = PyQt4.QtGui.QPainter(self)
            p.drawText(
                self.rect(),
                PyQt4.QtCore.Qt.AlignCenter | PyQt4.QtCore.Qt.AlignVCenter,
                ru(
                    QCoreApplication.translate(u'SurveyWidget',
                                               u"No data to display")))
            return

        painter = PyQt4.QtGui.QPainter(self)

        self.drawSurveys(self.rect(), painter)
    def _validateGeometry(self, layer_name, geometry, feature_id):
        clean_geometry = self._getCleanGeometry(geometry)

        if clean_geometry is None:
            self.features_errors.append((
                layer_name, feature_id,
                QCoreApplication.translate(
                    'Importer',
                    'Invalid geometry, maybe all vertices have the same coordinates'
                ), self._getCentroid(geometry)))
            return None

        errors = clean_geometry.validateGeometry()

        for error in errors:
            self.features_errors.append(
                (layer_name, feature_id, error.what(), error.where()))

        return clean_geometry if len(errors) == 0 else None
Esempio n. 47
0
    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
        self.mapCanvas = iface.mapCanvas()
        self.duplicateTool = None
        self.intersectTool = None
        self.profileTool = None
        self.subProfileTool = None
        self.drawdownTool = None
        self.pointerTool = None
        self.moveTool = None
        self.multiAttributesTool = None
        self.showSettings = None
        self.rebuildIndex = None
        self.controlTool = None
        if VDLTools.MORE_TOOLS:
            self.importMeasures = None

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

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

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

        # Declare instance attributes
        self.actions = []
        self.menu = QCoreApplication.translate("VDLTools", "&VDL Tools")
        self.toolbar = self.iface.addToolBar("VDLTools")
        self.toolbar.setObjectName("VDLTools")
Esempio n. 48
0
    def openScriptFile(self):
        lastDirPath = self.settings.value("pythonConsole/lastDirPath", "")
        openFileTr = QCoreApplication.translate("PythonConsole", "Open File")
        fileList = QFileDialog.getOpenFileNames(self, openFileTr, lastDirPath,
                                                "Script file (*.py)")
        if fileList:
            for pyFile in fileList:
                for i in range(self.tabEditorWidget.count()):
                    tabWidget = self.tabEditorWidget.widget(i)
                    if tabWidget.path == pyFile:
                        self.tabEditorWidget.setCurrentWidget(tabWidget)
                        break
                else:
                    tabName = QFileInfo(pyFile).fileName()
                    self.tabEditorWidget.newTabEditor(tabName, pyFile)

                    lastDirPath = QFileInfo(pyFile).path()
                    self.settings.setValue("pythonConsole/lastDirPath", pyFile)
                    self.updateTabListScript(pyFile, action='append')
Esempio n. 49
0
    def popupError(self, error=None, url=None):
        """Popups an Error message bar for network errors."""
        disambiguation = self.tr_disambiguation[self.resourceType]
        widget = iface.messageBar().createMessage(
            self.tr('Connection problem', disambiguation),
            self.tr('Could not connect to scripts/models repository',
                    disambiguation))
        if error and url:
            QgsMessageLog.logMessage(
                self.tr(u"Network error code: {} on URL: {}").format(
                    error, url), u"Processing", QgsMessageLog.CRITICAL)
            button = QPushButton(QCoreApplication.translate(
                "Python", "View message log"),
                                 pressed=show_message_log)
            widget.layout().addWidget(button)

        iface.messageBar().pushWidget(widget,
                                      level=QgsMessageBar.CRITICAL,
                                      duration=5)
    def __init__(self, filename, parent=None):
        '''
        Constructor.
        '''

        super(ImportDxfDialog, self).__init__(parent)
        Importer.__init__(self, filename)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        # Filename
        self.lblFilename.setText(filename)

        # Setup tables
        self.tabLayersMapping.setHorizontalHeaderLabels([
            QCoreApplication.translate('ImportDxfDialog', 'DXF Layer'),
            QCoreApplication.translate('ImportDxfDialog', 'QGIS Layer'),
            QCoreApplication.translate('ImportDxfDialog', 'Enabled')
        ])
        self.tabLayersMapping.setColumnWidth(0, 460)
        self.tabLayersMapping.setColumnWidth(1, 200)
        self.tabFieldsMapping.setHorizontalHeaderLabels([
            QCoreApplication.translate('ImportDxfDialog', 'QGIS Field'),
            QCoreApplication.translate('ImportDxfDialog', 'Value'),
            QCoreApplication.translate('ImportDxfDialog', 'Enabled')
        ])
        self.tabFieldsMapping.setColumnWidth(0, 200)
        self.tabFieldsMapping.setColumnWidth(1, 460)

        # Load dxf layers
        self._loadDxfLayers(filename)

        # If DXF is not valid, return
        if not self.valid:
            return

        # Don't trigger events if loading from config file
        self.is_loading_mapping = False

        # Load the QGIS layers
        self._loadQgisLayers()

        # Load the default mapping
        self.mapping = Mapping()

        self._loadLayersMapping()
Esempio n. 51
0
    def __checkIfExist(self):
        """
        To check if the data we want to import is already in the table
        """
        if self.__iter < len(self.__data):
            data = self.__data[self.__iter]

            # check if already in table
            query = self.__db.exec_(
                """SELECT ST_AsText(geometry3d) FROM %s.%s WHERE st_dwithin('%s', geometry3d, 0.03)"""
                % (data['schema_table'], data['name_table'], data['geom']))
            if query.lastError().isValid():
                self.__iface.messageBar().pushMessage(
                    query.lastError().text(),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)
            else:
                in_base = False
                point = None
                while next(query):
                    point = query.value(0)
                    in_base = True
                if in_base:
                    self.__data[self.__iter]['point'] = point
                    self.__confDlg = ImportConfirmDialog()
                    self.__confDlg.setMessage(
                        QCoreApplication.translate(
                            "VDLTools", "There is already a " + point +
                            " in table " + data['schema_table'] + """.""" +
                            data['name_table'] +
                            ".\n Would you like to add it anyway ? "))
                    self.__confDlg.rejected.connect(self.__cancelAndNext)
                    self.__confDlg.accepted.connect(self.__confirmAndNext)
                    self.__confDlg.okButton().clicked.connect(
                        self.__onConfirmOk)
                    self.__confDlg.cancelButton().clicked.connect(
                        self.__onConfirmCancel)
                    self.__confDlg.show()
                else:
                    self.__confirmAndNext()
        else:
            self.__insert()
Esempio n. 52
0
    def asPolygonV2(geometry, iface):
        """
        To get the feature geometry from a polygon as a QgsCurvePolygonV2
        :param geometry: the feature geometry
        :param iface: interface
        :return: the polygon as QgsCurvePolygonV2 , and true if it has curves or false if it hasn't, or none
        """
        wktPolygon = geometry.exportToWkt()
        curved = []
        if wktPolygon.startswith('PolygonZ'):
            polygon = wktPolygon.replace('PolygonZ', '')
        elif wktPolygon.startswith('Polygon'):
            polygon = wktPolygon.replace('Polygon', '')
        elif wktPolygon.startswith('CurvePolygonZ'):
            polygon = wktPolygon.replace('CurvePolygonZ', '')
        elif wktPolygon.startswith('CurvePolygon'):
            polygon = wktPolygon.replace('CurvePolygon', '')
        else:
            iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "This geometry is not yet implemented"),
                level=QgsMessageBar.WARNING)
            return None
        polygon = polygon.strip()[1:-1]
        lines = polygon.split('),')
        polygonV2 = QgsCurvePolygonV2()
        for i in range(0, len(lines)):
            line = lines[i]
            if line.startswith('CircularStringZ'):
                curved.append(True)
                line = line.replace('CircularStringZ', '')
            elif line.startswith('CircularString'):
                curved.append(True)
                line = line.replace('CircularString', '')
            else:
                curved.append(False)
            line = line.strip()[1:-1]

            if i == 0:
                polygonV2.setExteriorRing(GeometryV2.__createLine(line.split(','), curved[i]))
            else:
                polygonV2.addInteriorRing(GeometryV2.__createLine(line.split(','), curved[i]))
        return polygonV2, curved
Esempio n. 53
0
    def populateModel(self, serverList):
        """
        Called after the model is initialized. Adds the servers to the root.
        """

        self.rootItem = RootTreeItem("Servere",
                                     None)  # Also provides the header

        if not len(serverList.getTable()) > 0:
            # If there's no servers :(
            self.rootItem.appendChild(
                LDAPErrorItem(
                    QCoreApplication.translate("LDAPTreeItemModel",
                                               "No servers defined"), None,
                    self.rootItem))
            return

        for server in serverList.getTable():
            tmp = ServerTreeItem([server.name], server, self.rootItem)
            self.rootItem.appendChild(tmp)
Esempio n. 54
0
 def __init__(self, iface):
     """
     Constructor
     :param iface: interface
     """
     self.__iface = iface
     self.icon_path = ':/plugins/VDLTools/icons/settings_icon.png'
     self.text = QCoreApplication.translate("VDLTools", "Settings")
     self.__showDlg = None
     self.__ctlDb = None
     self.__configTable = None
     self.__uriDb = None
     self.__schemaDb = None
     self.__memoryPointsLayer = None
     self.__memoryLinesLayer = None
     self.__mntUrl = None
     self.__project_loaded()
     QgsProject.instance().readProject.connect(self.__project_loaded)
     self.__linesLayer = None
     self.__fieldnames = None
Esempio n. 55
0
 def __init__(self, iface):
     """
     Constructor
     :param iface: interface
     """
     QgsMapTool.__init__(self, iface.mapCanvas())
     self.__iface = iface
     self.icon_path = ':/plugins/VDLTools/icons/profile_2_icon.png'
     self.text = QCoreApplication.translate("VDLTools",
                                            "Line for MNT profile")
     self.setCursor(Qt.ArrowCursor)
     self.__isSelected = False
     self.__dockWdg = None
     self.__rubberLine = None
     self.__rubberDots = None
     self.ownSettings = None
     self.__line = None
     self.__startVertex = None
     self.__isfloating = False
     self.__dockGeom = None
Esempio n. 56
0
    def ask_and_update_settings(self,
                                objects_with_get_settings,
                                settingskey,
                                msg=''):

        old_string = utils.anything_to_string_representation(
            self.update_stored_settings(objects_with_get_settings))

        new_string = PyQt4.QtGui.QInputDialog.getText(
            None,
            ru(
                QCoreApplication.translate(u'ExportToFieldLogger',
                                           "Edit settings string")), msg,
            PyQt4.QtGui.QLineEdit.Normal, old_string)
        if not new_string[1]:
            return False

        new_string_text = ru(new_string[0])

        self.update_settings(new_string_text, settingskey)
Esempio n. 57
0
 def __init__(self, iface):
     """
     Constructor
     :param iface: interface
     """
     QgsMapTool.__init__(self, iface.mapCanvas())
     self.__iface = iface
     self.icon_path = ':/plugins/VDLTools/icons/extrapolate_icon.png'
     self.text = QCoreApplication.translate(
         "VDLTools", "Extrapolate the elevation of a vertex and a "
         "point at the extremity of a line")
     self.__layer = None
     self.setCursor(Qt.ArrowCursor)
     self.__isEditing = False
     self.__lastFeatureId = None
     self.__rubber = None
     self.__confDlg = None
     self.__selectedVertex = None
     self.__elevation = None
     self.__selectedFeature = None
Esempio n. 58
0
    def test_qgis_translations(self):
        """Test that translations work."""

        parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir)

        dir_path = os.path.abspath(parent_path)

        file_path = os.path.join(dir_path, 'i18n', 'af.qm')

        translator = QTranslator()

        translator.load(file_path)

        QCoreApplication.installTranslator(translator)

        expected_message = 'Goeie more'

        real_message = QCoreApplication.translate("@default", 'Good morning')

        self.assertEqual(real_message, expected_message)
Esempio n. 59
0
    def __init__(self, parent=None):
        QDockWidget.__init__(self, parent)
        self.setObjectName("IPython Console")
        self.setWindowTitle(
            QCoreApplication.translate("IPython Console", "IPython Console"))
        self.setAllowedAreas(Qt.BottomDockWidgetArea)

        self.container = QWidget()
        self.layout = QVBoxLayout(self.container)

        self.kernel_manager = QtKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel_manager.start_channels()

        self.console = IPythonWidget(local_kernel=LOCALHOST)
        self.console.kernel_manager = self.kernel_manager
        print dir(self.console)

        self.layout.addWidget(self.console)
        self.setWidget(self.container)
Esempio n. 60
0
 def setConnection(self):
     """
     To set a connection to the initialized database
     :return: database connection
     """
     db = QSqlDatabase.addDatabase('QPSQL')
     db.setHostName(self.__host)
     db.setDatabaseName(self.__dbName)
     db.setUserName(self.__username)
     db.setPassword(self.__pwd)
     db.setPort(int(self.__port))
     ok = db.open()
     if not ok:
         self.__iface.messageBar().pushMessage(
             QCoreApplication.translate("VDLNetwork", "Database Error: ") +
             db.lastError().text(),
             level=QgsMessageBar.CRITICAL,
             duration=0)
         return None
     return db