Example #1
0
    def on_gen(self):
        '''生成工程'''
        if not self.currentConfig:
            return

        #获取工程名及有效路径
        project_name = self.et_project_name.text()
        project_location = self.et_project_location.text()
        qdir = QDir(project_location)
        if not qdir.exists():
            if not qdir.mkpath(project_location):
                QMessageBox.warning(self, '警告', '路径无效!')
                return
        project_location = qdir.absolutePath()
        if not project_location.endsWith(
                '/') and not project_location.endsWith('\\'):
            project_location += os.sep
            project_location.replace('\\', '/')
        if project_name.isEmpty() or project_location.isEmpty():
            QMessageBox.warning(self, '警告', '项目名称或路径不能为空!')
            return

        self.currentConfig.project_name = app.QString2str(project_name)
        self.currentConfig.project_location = app.QString2str(project_location)

        content = self.currentConfig.toJson()
        fileInfo = QFileInfo(self.path)
        if not self.path.isEmpty():
            path = app.QString2str(self.path)
            with open(path, 'w+') as f:
                f.write(content)
        item = self.lw.currentItem()
        item.setData(QtCore.Qt.UserRole, content)

        template_name = self.currentConfig.template_source
        template_dir = app.g_pwd + os.sep + 'templates' + os.sep + template_name.encode(
            'utf-8')
        with open(template_dir + os.sep + 'config.json', 'r') as f:
            self.currentConfig.config_content = f.read()
        ret_json = app.render(self.currentConfig.config_content,
                              config=self.currentConfig)
        self.currentConfig.config = json.loads(ret_json)
        for file in self.currentConfig.config['files']:
            sourcepath = template_dir + os.sep + file['source'].encode('utf-8')
            targetdir = self.currentConfig.project_location + self.currentConfig.project_name
            targetpath = targetdir + os.sep + file['target']
            fi = QFileInfo(targetpath)
            qdir = fi.absoluteDir()
            if not qdir.exists():
                qdir.mkpath(fi.absolutePath())
            with open(sourcepath, 'r') as f:
                content = f.read()
                content = app.render(content, config=self.currentConfig)  #渲染文件
            with open(targetpath, 'w+') as f:
                f.write(content.encode('utf-8'))
        QMessageBox.information(self, '提示', '生成成功!')
Example #2
0
    def updateTable(self, id):
        filePath = QFileDialog.getOpenFileName(self, "请选择库", self.alloneEnv,
                                               "Library(*.lib)")
        if filePath.isEmpty():
            return
        fileinfo = QFileInfo(filePath)
        libPath = fileinfo.absoluteDir().absolutePath()
        libName = fileinfo.baseName()
        # 支持选择文件后与系统ALLONEDIR比较一下变成相对路径
        # 并且能够手动输入相对路径或包含$(ALLONEDIR)的相对路径
        env = QString(os.getenv('ALLONEDIR', '../..').replace('\\', '/'))
        if env.endsWith('/'):
            env.remove(env.lastIndexOf('/'), 1)
        if libPath.contains(env):
            libPath.replace(env, QString('$$ALLONEDIR'))

        self.tw_interface.setItem(id, 1, QTableWidgetItem(libPath))
        self.tw_interface.setItem(id, 0, QTableWidgetItem(libName))
Example #3
0
 def __add_layer_definition_file(self, file_name, root_group):
     """
     shamelessly copied from
     https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp
     """
     qfile = QFile(file_name)
     if not qfile.open(QIODevice.ReadOnly):
         return None
     doc = QDomDocument()
     if not doc.setContent(qfile):
         return None
     file_info = QFileInfo(qfile)
     QDir.setCurrent(file_info.absoluteDir().path())
     root = QgsLayerTreeGroup()
     ids = doc.elementsByTagName('id')
     for i in xrange(0, ids.size()):
         id_node = ids.at(i)
         id_elem = id_node.toElement()
         old_id = id_elem.text()
         layer_name = old_id[:-17]
         date_time = QDateTime.currentDateTime()
         new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz')
         id_elem.firstChild().setNodeValue(new_id)
         tree_layer_nodes = doc.elementsByTagName('layer-tree-layer')
         for j in xrange(0, tree_layer_nodes.count()):
             layer_node = tree_layer_nodes.at(j)
             layer_elem = layer_node.toElement()
             if old_id == layer_elem.attribute('id'):
                 layer_node.toElement().setAttribute('id', new_id)
     layer_tree_elem = doc.documentElement().firstChildElement(
         'layer-tree-group')
     load_in_legend = True
     if not layer_tree_elem.isNull():
         root.readChildrenFromXML(layer_tree_elem)
         load_in_legend = False
     layers = QgsMapLayer.fromLayerDefinition(doc)
     QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend)
     nodes = root.children()
     for node in nodes:
         root.takeChild(node)
     del root
     root_group.insertChildNodes(-1, nodes)
     return None
Example #4
0
 def __add_layer_definition_file(self, file_name, root_group):
     """
     shamelessly copied from
     https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp
     """
     qfile = QFile(file_name)
     if not qfile.open(QIODevice.ReadOnly):
         return None
     doc = QDomDocument()
     if not doc.setContent(qfile):
         return None
     file_info = QFileInfo(qfile)
     QDir.setCurrent(file_info.absoluteDir().path())
     root = QgsLayerTreeGroup()
     ids = doc.elementsByTagName('id')
     for i in xrange(0, ids.size()):
         id_node = ids.at(i)
         id_elem = id_node.toElement()
         old_id = id_elem.text()
         layer_name = old_id[:-17]
         date_time = QDateTime.currentDateTime()
         new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz')
         id_elem.firstChild().setNodeValue(new_id)
         tree_layer_nodes = doc.elementsByTagName('layer-tree-layer')
         for j in xrange(0, tree_layer_nodes.count()):
             layer_node = tree_layer_nodes.at(j)
             layer_elem = layer_node.toElement()
             if old_id == layer_elem.attribute('id'):
                 layer_node.toElement().setAttribute('id', new_id)
     layer_tree_elem = doc.documentElement().firstChildElement('layer-tree-group')
     load_in_legend = True
     if not layer_tree_elem.isNull():
         root.readChildrenFromXML(layer_tree_elem)
         load_in_legend = False
     layers = QgsMapLayer.fromLayerDefinition(doc)
     QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend)
     nodes = root.children()
     for node in nodes:
         root.takeChild(node)
     del root
     root_group.insertChildNodes(-1, nodes)
     return None
Example #5
0
    def on_gen(self):
        '''生成工程'''
        if not self.currentConfig:
            return

        #获取工程名及有效路径
        project_name = self.et_project_name.text()
        project_location = self.et_project_location.text()
        qdir = QDir(project_location)
        if not qdir.exists():
            if not qdir.mkpath(project_location):
                QMessageBox.warning(self, '警告', '路径无效!')
                return
        project_location = qdir.absolutePath()
        if not project_location.endsWith('/') and not project_location.endsWith('\\'):
            project_location += os.sep
        if project_name.isEmpty() or project_location.isEmpty():
            QMessageBox.warning(self, '警告', '项目名称或路径不能为空!')
            return

        self.currentConfig.project_name = app.QString2str(project_name)
        self.currentConfig.project_location = app.QString2str(project_location)
        template_name = self.currentConfig.template_source
        template_dir = app.g_pwd + os.sep + 'templates' + os.sep + template_name
        with open(template_dir + os.sep + 'config.json', 'r') as f:
            self.currentConfig.config_content = f.read()
        ret_json = app.render(self.currentConfig.config_content, config=self.currentConfig)
        self.currentConfig.config = json.loads(ret_json)
        for file in self.currentConfig.config['files']:
            sourcepath = template_dir + os.sep + file['source']
            targetdir = self.currentConfig.project_location + self.currentConfig.project_name
            targetpath = targetdir + os.sep + file['target']
            fi = QFileInfo(targetpath)
            qdir = fi.absoluteDir()
            if not qdir.exists():
                qdir.mkpath(fi.absolutePath())
            with open(sourcepath, 'r') as f:
                content = f.read()
                content = app.render(content, config=self.currentConfig) #渲染文件
            with open(targetpath, 'w+') as f:
                f.write(content.encode('utf-8'))
        QMessageBox.information(self,'提示','生成成功!')
Example #6
0
  def _update_path(self):
    if not self._use_suffix:
      self._viewer.set_path(self._current_path)
      return

    self._viewer.reset_path()
    if not self._current_path:
      return

    selected_file = QFileInfo(self._current_path)
    if not selected_file.exists():
      return

    selected_dir = selected_file.absoluteDir()
    file_name = selected_file.fileName()
    if not selected_dir.exists():
      return

    if not selected_dir.cd('converted'):
      return

    suffixed_path = selected_dir.absoluteFilePath(file_name)
    self._viewer.set_path(suffixed_path)
Example #7
0
class Georeferencer(QObject):

    # Step enum
    Start = 0
    Crop = 1
    Translate = 2
    Warp = 3
    Overview = 4
    Stop = 5
    Step = [0, 1, 2, 3, 4, 5]
    Label = ['Start', 'Crop', 'Translate', 'Warp', 'Overview', 'Stop']

    # Georeferencer.Step, ProcessStatus
    status = pyqtSignal(int, int)
    # Georeferencer.Step, Message
    error = pyqtSignal(int, str)

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

        # Internal variables
        self._debug = True
        self._gdalDir = QDir()
        self._step = 0
        self._status = 0
        self._translate = QFileInfo()
        self._warp = QFileInfo()
        self._overview = QFileInfo()
        self._command = ''
        self._args = ''
        self._process = QProcess()
        self._gc = Transform()
        self._rawFile = QFileInfo()
        self._pointFile = QFileInfo()
        self._cropFile = QFileInfo()
        self._translateFile = QFileInfo()
        self._geoFile = QFileInfo()

        tempDir = QDir.temp()
        self._cropFile.setFile(
            tempDir.absoluteFilePath('.ark_georef_crop.png'))
        self._translateFile = QFileInfo(
            tempDir.absoluteFilePath('.ark_georef_translate.tiff'))

        self._gdalDir = QDir(self.gdalPath())
        if self._debug:
            debug('GDAL Path: ' + self._gdalDir.absolutePath())
        self._translate.setFile(self._gdalDir, 'gdal_translate')
        self._warp.setFile(self._gdalDir, 'gdalwarp')
        self._overview.setFile(self._gdalDir, 'gdaladdo')
        if (not self._translate.exists() or not self._warp.exists()
                or not self._overview.exists()):
            self._signalError(
                'GDAL commands not found, please ensure GDAL Tools plugin is installed and has correct path set!'
            )
            return

        self._process.started.connect(self._processStarted)
        self._process.finished.connect(self._processFinished)
        self._process.error.connect(self._processError)
        self._process.readyReadStandardError.connect(self._processError)

    def step(self):
        return self._step

    def processStatus(self):
        return self._status

    def run(self, gc, rawFile, pointFile, geoFile):
        self._step = Georeferencer.Start
        if (not gc.isValid()):
            self._signalError('Invalid ground control points.')
            return
        self._gc = gc

        if (not rawFile.exists()):
            self._signalError('Raw file not found.')
            return
        self._rawFile = rawFile

        self._pointFile = pointFile
        self._geoFile = geoFile
        if not self._geoFile.absoluteDir().exists():
            self._geoFile.absoluteDir().mkpath('.')

        if (self._debug):
            debug('Raw File: \'' + self._rawFile.absoluteFilePath() + '\'')
            debug('GCP File: \'' + self._pointFile.absoluteFilePath() + '\'')
            debug('Crop File: \'' + self._cropFile.absoluteFilePath() + '\'')
            debug('Translate File: \'' +
                  self._translateFile.absoluteFilePath() + '\'')
            debug('Geo File: \'' + self._geoFile.absoluteFilePath() + '\'')

        QCoreApplication.processEvents()
        self._runCropStep()

    def _runCropStep(self):
        if self._debug:
            debug('Crop')
        self._step = Georeferencer.Crop
        self._args = []
        self._command = ''
        pixmap = QPixmap(self._rawFile.absoluteFilePath())
        if pixmap.isNull():
            self._signalError('Loading of raw image failed.')
            return
        pixmap = pixmap.copy(0, 0, pixmap.width(), int(pixmap.height() * 0.84))
        image = pixmap.toImage()
        if image.isNull():
            self._signalError('Cropping of raw image failed.')
            return
        if not image.save(self._cropFile.absoluteFilePath(), 'PNG', 100):
            self._signalError('Saving of cropped image failed.')
            return
        self._signalStatus()
        self._runTranslateStep()

    def _formatGcp(self, point):
        point = self._gc.point(point)
        return "{0:f} {1:f} {2:f} {3:f}".format(point.raw().x(),
                                                point.raw().y(),
                                                point.map().x(),
                                                point.map().y())

    def _runTranslateStep(self):
        self._step = Georeferencer.Translate
        self._args = []
        self._args.extend(['-of', 'GTiff'])
        self._args.extend(['-a_srs', self._gc.crs])
        # self._args.extend(['-gcp', self._formatGcp(1)])
        # self._args.extend(['-gcp', self._formatGcp(2)])
        # self._args.extend(['-gcp', self._formatGcp(3)])
        # self._args.extend(['-gcp', self._formatGcp(4)])
        self._args.extend([
            '-gcp',
            str(self._gc.point(1).raw().x()),
            str(self._gc.point(1).raw().y()),
            str(self._gc.point(1).map().x()),
            str(self._gc.point(1).map().y())
        ])
        self._args.extend([
            '-gcp',
            str(self._gc.point(2).raw().x()),
            str(self._gc.point(2).raw().y()),
            str(self._gc.point(2).map().x()),
            str(self._gc.point(2).map().y())
        ])
        self._args.extend([
            '-gcp',
            str(self._gc.point(3).raw().x()),
            str(self._gc.point(3).raw().y()),
            str(self._gc.point(3).map().x()),
            str(self._gc.point(3).map().y())
        ])
        self._args.extend([
            '-gcp',
            str(self._gc.point(4).raw().x()),
            str(self._gc.point(4).raw().y()),
            str(self._gc.point(4).map().x()),
            str(self._gc.point(4).map().y())
        ])
        self._args.append(self._cropFile.absoluteFilePath())
        self._args.append(self._translateFile.absoluteFilePath())
        self._command = self._translate.absoluteFilePath() + ' ' + ' '.join(
            self._args)
        self._process.start(self._translate.absoluteFilePath(), self._args)

    def _runWarpStep(self):
        self._step = Georeferencer.Warp
        self._args = []
        self._args.extend(['-order', '1'])
        self._args.extend(['-r', 'cubic'])
        self._args.extend(['-t_srs', self._gc.crs])
        self._args.extend(['-of', 'GTiff'])
        self._args.extend(['-co', 'COMPRESS=JPEG'])
        self._args.extend(['-co', 'JPEG_QUALITY=50'])
        self._args.extend(['-co', 'TILED=YES'])
        self._args.append('-dstalpha')
        self._args.append('-overwrite')
        self._args.append('\"' + self._translateFile.absoluteFilePath() + '\"')
        self._args.append('\"' + self._geoFile.absoluteFilePath() + '\"')
        self._command = self._warp.absoluteFilePath() + ' ' + ' '.join(
            self._args)
        self._process.start(self._command)

    def _runOverviewStep(self):
        self._step = Georeferencer.Overview
        self._args = []
        self._args.extend(['--config', 'COMPRESS_OVERVIEW JPEG'])
        self._args.extend(['--config', 'INTERLEAVE_OVERVIEW PIXEL'])
        self._args.extend(['-r', 'cubic'])
        self._args.append('\"' + self._geoFile.absoluteFilePath() + '\"')
        self._args.append('2 4 8 16')
        self._command = self._overview.absoluteFilePath() + ' ' + ' '.join(
            self._args)
        self._process.start(self._command)

    def _processStarted(self):
        self._status = ProcessStatus.Running
        self._signalStatus()
        if self._debug:
            debug(self.Label[self._step])
            debug(self._command)

    def _processFinished(self):
        self._status = ProcessStatus.Success
        self._signalStatus()
        if (self._step == Georeferencer.Translate):
            self._runWarpStep()
        elif (self._step == Georeferencer.Warp):
            self._runOverviewStep()
        elif (self._step == Georeferencer.Overview):
            self.writeGcpFile(self._gc, self._pointFile.absoluteFilePath())
            self._step = Georeferencer.Stop
            self._signalStatus()

    def _processError(self):
        self._status = ProcessStatus.Failure
        msg = str(self._process.readAllStandardError())
        debug(msg)
        self._signalError(msg)

    def _signalStatus(self):
        self.status.emit(self._step, self._status)

    def _signalError(self, msg):
        self.error.emit(self._step, msg)

    @staticmethod
    def gdalPath():
        return QSettings().value('/GdalTools/gdalPath', '/usr/bin')

    @staticmethod
    def loadGcpFile(path):
        inFile = QFile(path)
        if (not inFile.open(QIODevice.ReadOnly | QIODevice.Text)):
            return 'ERROR: Unable to open GCP file for reading'
        inStream = QTextStream(inFile)
        line = inStream.readLine()
        # Skip the header line if found
        if (line == 'mapX,mapY,pixelX,pixelY,enable'):
            line = inStream.readLine()
        lines = 0
        gc = Transform()
        while (line):
            lines += 1
            vals = line.split(',')
            if (len(vals) != 5):
                return None
            map = QgsPoint(float(vals[0]), float(vals[1]))
            raw = QPointF(float(vals[2]), float(vals[3]))
            enabled = bool(vals[4])
            point = GroundControlPoint(raw, map, enabled)
            gc.setPoint(lines, point)
            line = inStream.readLine()
        inFile.close()
        return gc

    @staticmethod
    def writeGcpFile(gc, path):
        outFile = QFile(path)
        if (not outFile.open(QIODevice.WriteOnly | QIODevice.Text)):
            return 'Unable to open GCP file for writing'
        outStream = QTextStream(outFile)
        outStream << gc.asCsv()
        outFile.close()