Ejemplo n.º 1
0
 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 __init__(self, parent, plugin):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.plugin = plugin
        self.mResult = ""
        self.progressBar.setRange(0, 0)
        self.progressBar.setFormat("%p%")
        self.labelName.setText(plugin["name"])
        self.buttonBox.clicked.connect(self.abort)

        url = QUrl(plugin["download_url"])

        fileName = plugin["filename"]
        tmpDir = QDir.tempPath()
        tmpPath = QDir.cleanPath(tmpDir + "/" + fileName)
        self.file = QFile(tmpPath)

        self.request = QNetworkRequest(url)
        authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"]
        if authcfg and isinstance(authcfg, basestring):
            if not QgsAuthManager.instance().updateNetworkRequest(
                    self.request, authcfg.strip()):
                self.mResult = self.tr(
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(authcfg)
                self.request = None

        if self.request is not None:
            self.reply = QgsNetworkAccessManager.instance().get(self.request)
            self.reply.downloadProgress.connect(self.readProgress)
            self.reply.finished.connect(self.requestFinished)

            self.stateChanged(4)
Ejemplo n.º 3
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 (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)
Ejemplo n.º 4
0
 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)
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
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 (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)
Ejemplo n.º 7
0
def installFromZipFile(pluginPath):
    """Install and activate plugin from the specified package
    """
    result = None

    with zipfile.ZipFile(pluginPath, 'r') as zf:
        pluginName = os.path.split(zf.namelist()[0])[0]

    pluginFileName = os.path.splitext(os.path.basename(pluginPath))[0]

    pluginsDirectory = home_plugin_path
    if not QDir(pluginsDirectory).exists():
        QDir().mkpath(pluginsDirectory)

    # If the target directory already exists as a link,
    # remove the link without resolving
    QFile(os.path.join(pluginsDirectory, pluginFileName)).remove()

    try:
        # Test extraction. If fails, then exception will be raised
        # and no removing occurs
        unzip(unicode(pluginPath), unicode(pluginsDirectory))
        # Removing old plugin files if exist
        removeDir(QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName)))
        # Extract new files
        unzip(unicode(pluginPath), unicode(pluginsDirectory))
    except:
        result = QCoreApplication.translate('BoundlessConnect',
            'Failed to unzip the plugin package\n{}.\nProbably it is broken'.format(pluginPath))

    if result is None:
        updateAvailablePlugins()
        loadPlugin(pluginName)
        plugins.getAllInstalled(testLoad=True)
        plugins.rebuild()
        plugin = plugins.all()[pluginName]

        settings = QSettings()
        if settings.contains('/PythonPlugins/' + pluginName):
            if settings.value('/PythonPlugins/' + pluginName, False, bool):
                startPlugin(pluginName)
                reloadPlugin(pluginName)
            else:
                unloadPlugin(pluginName)
                loadPlugin(pluginName)
        else:
            if startPlugin(pluginName):
                settings.setValue('/PythonPlugins/' + pluginName, True)

    return result
Ejemplo n.º 8
0
 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)
Ejemplo n.º 9
0
 def requestFinished(self):
     reply = self.sender()
     self.buttonBox.setEnabled(False)
     if reply.error() != QNetworkReply.NoError:
         self.mResult = reply.errorString()
         if reply.error() == QNetworkReply.OperationCanceledError:
             self.mResult += "<br/><br/>" + QCoreApplication.translate(
                 "QgsPluginInstaller",
                 "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options."
             )
         self.reject()
         reply.deleteLater()
         return
     self.file.open(QFile.WriteOnly)
     self.file.write(reply.readAll())
     self.file.close()
     self.stateChanged(0)
     reply.deleteLater()
     pluginDir = qgis.utils.home_plugin_path
     tmpPath = self.file.fileName()
     # make sure that the parent directory exists
     if not QDir(pluginDir).exists():
         QDir().mkpath(pluginDir)
     # if the target directory already exists as a link, remove the link without resolving:
     QFile(pluginDir + unicode(QDir.separator()) +
           self.plugin["id"]).remove()
     try:
         unzip(
             unicode(tmpPath), unicode(pluginDir)
         )  # test extract. If fails, then exception will be raised and no removing occurs
         # removing old plugin files if exist
         removeDir(QDir.cleanPath(
             pluginDir + "/" +
             self.plugin["id"]))  # remove old plugin if exists
         unzip(unicode(tmpPath), unicode(pluginDir))  # final extract.
     except:
         self.mResult = self.tr(
             "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:"
         ) + "\n" + pluginDir
         self.reject()
         return
     try:
         # cleaning: removing the temporary zip file
         QFile(tmpPath).remove()
     except:
         pass
     self.close()
Ejemplo n.º 10
0
    def check(self, emit):
        was_complete  = self.complete
        directory     = QDir.cleanPath(posixpath.join(self.combo.currentText(), '.'))
        self.complete = len(directory) > 0 and \
                        not directory.startswith('/') and \
                        directory != './..' and \
                        not directory.startswith('./../') and \
                        directory != '..' and \
                        not directory.startswith('../')

        if self.complete:
            self.label.setStyleSheet('')
        else:
            self.label.setStyleSheet('QLabel { color : red }')

        if emit and was_complete != self.complete:
            self.page.completeChanged.emit()
  def __init__(self, parent, plugin):
    QDialog.__init__(self, parent)
    self.setupUi(self)
    self.plugin = plugin
    self.mResult = ""
    self.progressBar.setRange(0,0)
    self.progressBar.setFormat("%p%")
    self.labelName.setText(plugin["name"])
    self.buttonBox.clicked.connect(self.abort)

    url = QUrl(plugin["download_url"])

    fileName = plugin["filename"]
    tmpDir = QDir.tempPath()
    tmpPath = QDir.cleanPath(tmpDir+"/"+fileName)
    self.file = QFile(tmpPath)

    self.request = QNetworkRequest(url)
    self.reply = QgsNetworkAccessManager.instance().get( self.request )
    self.reply.downloadProgress.connect( self.readProgress )
    self.reply.finished.connect(self.requestFinished)

    self.stateChanged(4)
Ejemplo n.º 12
0
    def __init__(self, parent, plugin):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.plugin = plugin
        self.mResult = ""
        self.progressBar.setRange(0, 0)
        self.progressBar.setFormat("%p%")
        self.labelName.setText(plugin["name"])
        self.buttonBox.clicked.connect(self.abort)

        url = QUrl(plugin["download_url"])

        fileName = plugin["filename"]
        tmpDir = QDir.tempPath()
        tmpPath = QDir.cleanPath(tmpDir + "/" + fileName)
        self.file = QFile(tmpPath)

        self.request = QNetworkRequest(url)
        self.reply = QgsNetworkAccessManager.instance().get(self.request)
        self.reply.downloadProgress.connect(self.readProgress)
        self.reply.finished.connect(self.requestFinished)

        self.stateChanged(4)
Ejemplo n.º 13
0
    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)
 def requestFinished(self):
   reply = self.sender()
   self.buttonBox.setEnabled(False)
   if reply.error() != QNetworkReply.NoError:
     self.mResult = reply.errorString()
     if reply.error() == QNetworkReply.OperationCanceledError:
       self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.")
     self.reject()
     reply.deleteLater()
     return
   self.file.open(QFile.WriteOnly)
   self.file.write(reply.readAll())
   self.file.close()
   self.stateChanged(0)
   reply.deleteLater()
   pluginDir = qgis.utils.home_plugin_path
   tmpPath = self.file.fileName()
   # make sure that the parent directory exists
   if not QDir(pluginDir).exists():
     QDir().mkpath(pluginDir)
   # if the target directory already exists as a link, remove the link without resolving:
   QFile(pluginDir+unicode(QDir.separator())+self.plugin["id"]).remove()
   try:
     unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs
     # removing old plugin files if exist
     removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["id"])) # remove old plugin if exists
     unzip(unicode(tmpPath), unicode(pluginDir)) # final extract.
   except:
     self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir
     self.reject()
     return
   try:
     # cleaning: removing the temporary zip file
     QFile(tmpPath).remove()
   except:
     pass
   self.close()
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
    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)
Ejemplo n.º 18
0
 def _cleanPath(self, path ):
     """Escape \\ in the path
     """
     data = QDir.cleanPath( path ).replace( '\\', '/' ).strip()
     return data.strip('/')
Ejemplo n.º 19
0
    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)