Пример #1
0
    def _run_loading_vfk_layer(self, filePath):
        """Calls methods for loading a VFK layer.
        
        Disables loading widgets until the loading is finished.
        
        Args:
            filePath (str): A full path to the file.
        
        """

        try:
            self.set_value_loadVfkProgressBar.emit(0)

            fileInfo = QFileInfo(filePath)
            dbPath = QDir(fileInfo.absolutePath())\
                .filePath(fileInfo.completeBaseName() + '.db')
            layerCode = self.dW.parLayerCode
            vfkDriverName = 'VFK'
            layerName = fileInfo.completeBaseName() + '|' + layerCode

            self._create_db_file(filePath, dbPath, layerCode, vfkDriverName)

            self._open_database(dbPath)

            # SpatiaLite fix - start
            if not self.dW.fixedSqliteDriver:
                dbPath = self._create_spatialite_db_file(dbPath)
            # SpatiaLite fix - end

            self._load_vfk_layer(dbPath, layerName, layerCode, vfkDriverName)

            self.loadVfkProgressBar.setMaximum(1)
            self.set_value_loadVfkProgressBar.emit(1)

            self.set_text_statusbar.emit(u'Data byla úspešně načtena.', 0,
                                         False)
        except self.dW.puError:
            QgsApplication.processEvents()
        except:
            QgsApplication.processEvents()

            self.dW.display_error_messages(
                self, u'Error loading VFK file "{}".'.format(filePath),
                u'Chyba při načítání VFK souboru.',
                u'Chyba při načítání VFK souboru "{}".'.format(filePath))
        finally:
            QgsApplication.processEvents()
            self._enable_load_widgets(True)
Пример #2
0
def getSize(layer):
    """Get layer size on disk"""
    is_zip_file = False
    file_path = layer.dataProvider().dataSourceUri()
    if file_path.find('|') != -1:
        file_path = file_path[0:file_path.find('|')]

    if file_path.startswith('/vsizip/'):
        file_path = file_path.replace('/vsizip/', '')
        is_zip_file = True

    _file = QFile(file_path)
    file_info = QFileInfo(_file)

    dirname = file_info.dir().absolutePath()
    filename = file_info.completeBaseName()

    size = 0
    if layer.storageType() == 'ESRI Shapefile' and not is_zip_file:
        for suffix in ['.shp', '.dbf', '.prj', '.shx']:
            _file = QFile(os.path.join(dirname, filename + suffix))
            file_info = QFileInfo(_file)
            size = size + file_info.size()
    elif layer.storageType() in ['GPX', 'GeoJSON', 'LIBKML'] or is_zip_file:
        size = size + file_info.size()

    return size
Пример #3
0
    def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        rasterFileInfo = QFileInfo(myPath)
        mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(),
                                      rasterFileInfo.completeBaseName())
        rasterRenderer = QgsMultiBandColorRenderer(mRasterLayer.dataProvider(),
                                                   2, 3, 4)
        mRasterLayer.setRenderer(rasterRenderer)
        #pipe = mRasterLayer.pipe()
        #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer'
        QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer])

        # create composition with composer map
        self.mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append(mRasterLayer.id())
        self.mMapRenderer.setLayerSet(layerStringList)
        self.mMapRenderer.setProjectionsEnabled(False)
        self.mComposition = QgsComposition(self.mMapRenderer)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mComposerMap)
Пример #4
0
def csv_vector_layer(csv_path, **kwargs):
    """
    Create a vector layer from a CSV file.
    :param csv_path: Path of the CSV file.
    :type csv_path: str
    :param kwargs:
    :return: Returns a QGIS memory layer containing the CSV data.
    :rtype: QgsVectorLayer
    """
    # Get file name
    csv_fi = QFileInfo(csv_path)
    layer_name = csv_fi.completeBaseName()

    delimiter = kwargs.pop('delimiter', ',')

    # Construct URL with CSV provider query items
    url = QUrl.fromLocalFile(csv_path)
    url.addQueryItem('type', 'csv')
    url.addQueryItem('delimiter', delimiter)
    url.addQueryItem('geomType', 'none')
    url.addQueryItem('subsetIndex', 'no')
    url.addQueryItem('watchFile', 'no')

    uri = url.toEncoded().data()
    csv_vl = QgsVectorLayer(uri, layer_name, 'delimitedtext')
    fields = csv_vl.fields()

    return csv_vl
Пример #5
0
def getSize(layer):
    """Get layer size on disk"""
    is_zip_file = False
    file_path = layer.dataProvider().dataSourceUri()
    if file_path.find('|') != -1:
        file_path = file_path[0:file_path.find('|')]

    if file_path.startswith('/vsizip/'):
        file_path = file_path.replace('/vsizip/', '')
        is_zip_file = True

    _file = QFile(file_path)
    file_info = QFileInfo(_file)

    dirname = file_info.dir().absolutePath()
    filename = file_info.completeBaseName()

    size = 0
    if layer.storageType() == 'ESRI Shapefile' and not is_zip_file:
        for suffix in ['.shp', '.dbf', '.prj', '.shx']:
            _file = QFile(os.path.join(dirname, filename + suffix))
            file_info = QFileInfo(_file)
            size = size + file_info.size()
    elif layer.storageType() in ['GPX', 'GeoJSON', 'LIBKML'] or is_zip_file:
        size = size + file_info.size()

    return size
    def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        rasterFileInfo = QFileInfo(myPath)
        mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(),
                                      rasterFileInfo.completeBaseName())
        rasterRenderer = QgsMultiBandColorRenderer(
            mRasterLayer.dataProvider(), 2, 3, 4)
        mRasterLayer.setRenderer(rasterRenderer)
        #pipe = mRasterLayer.pipe()
        #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer'
        QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer])

        # create composition with composer map
        self.mMapRenderer = QgsMapRenderer()
        layerStringList = QStringList()
        layerStringList.append(mRasterLayer.id())
        self.mMapRenderer.setLayerSet(layerStringList)
        self.mMapRenderer.setProjectionsEnabled(False)
        self.mComposition = QgsComposition(self.mMapRenderer)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mComposerMap)
Пример #7
0
    def __init__(self, mainwindow):
        self.mainwindow = mainwindow

        # create map canvas
        self.canvas = QgsMapCanvas(self.mainwindow.widgetMap)
        self.canvas.setCanvasColor(Qt.yellow)
        self.canvas.enableAntiAliasing(True)
        self.canvas.useQImageToRender(False)
        self.canvas.show()
        self.canvas.parentWin = mainwindow
        debugString = QString("Finished Loading Canvas...")
        self.mainwindow.statusbar.showMessage(debugString)

        # lay our widgets out in the main window
        self.layout = QVBoxLayout(self.mainwindow.widgetMap)
        self.layout.addWidget(self.canvas)

        # Link in the map tools
        QObject.connect(self.mainwindow.mpActionZoomIn, SIGNAL("triggered()"),
                        self.zoomIn)
        QObject.connect(self.mainwindow.mpActionZoomOut, SIGNAL("triggered()"),
                        self.zoomOut)
        QObject.connect(self.mainwindow.mpActionPan, SIGNAL("triggered()"),
                        self.pan)

        # Map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(self.mainwindow.mpActionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)
        self.toolZoomIn.setAction(self.mainwindow.mpActionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)
        self.toolZoomOut.setAction(self.mainwindow.mpActionZoomOut)

        ##### Lets test out a simple map
        self.layers = []
        f = "data/st99_d00.shp"
        f_string = QString(f)
        info = QFileInfo(QString(f))

        # create layer
        layer = QgsVectorLayer(QString(f), info.completeBaseName(), "ogr")

        if not layer.isValid():
            # Deal with the error
            debugString = QString("Error Loading Layer...")
            self.mainwindow.statusbar.showMessage(debugString)
            return
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        # set extent to the extent of our layer
        self.canvas.setExtent(layer.extent())

        # Set the transparency for the layer
        #layer.setTransparency(190)

        # set the map canvas layer set
        cl = QgsMapCanvasLayer(layer)
        self.layers.insert(0, cl)
        self.canvas.setLayerSet(self.layers)
Пример #8
0
    def __init__(self, mainwindow):
        self.mainwindow = mainwindow

        # create map canvas
        self.canvas = QgsMapCanvas(self.mainwindow.widgetMap)
        self.canvas.setCanvasColor(Qt.yellow)
        self.canvas.enableAntiAliasing(True)
        self.canvas.useQImageToRender(False)
        self.canvas.show()
        self.canvas.parentWin = mainwindow
        debugString = QString("Finished Loading Canvas...")
        self.mainwindow.statusbar.showMessage(debugString)

        # lay our widgets out in the main window
        self.layout = QVBoxLayout(self.mainwindow.widgetMap)
        self.layout.addWidget(self.canvas)

        # Link in the map tools
        QObject.connect(self.mainwindow.mpActionZoomIn, SIGNAL("triggered()"), self.zoomIn)
        QObject.connect(self.mainwindow.mpActionZoomOut, SIGNAL("triggered()"), self.zoomOut)
        QObject.connect(self.mainwindow.mpActionPan, SIGNAL("triggered()"), self.pan)

        # Map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(self.mainwindow.mpActionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)
        self.toolZoomIn.setAction(self.mainwindow.mpActionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)
        self.toolZoomOut.setAction(self.mainwindow.mpActionZoomOut)

        ##### Lets test out a simple map
        self.layers = []
        f = "data/st99_d00.shp"
        f_string = QString(f)
        info = QFileInfo(QString(f))

        # create layer
        layer = QgsVectorLayer(QString(f), info.completeBaseName(), "ogr")

        if not layer.isValid():
            # Deal with the error
            debugString = QString("Error Loading Layer...")
            self.mainwindow.statusbar.showMessage(debugString)
            return
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        # set extent to the extent of our layer
        self.canvas.setExtent(layer.extent())

        # Set the transparency for the layer
        #layer.setTransparency(190)

        # set the map canvas layer set
        cl = QgsMapCanvasLayer(layer)
        self.layers.insert(0,cl)
        self.canvas.setLayerSet(self.layers)
Пример #9
0
    def testPrintMapFromTemplate(self):
        """Test that we can get a map to render in the template."""
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        myFileInfo = QFileInfo(myPath)
        myRasterLayer = QgsRasterLayer(myFileInfo.filePath(),
                                       myFileInfo.completeBaseName())
        myRenderer = QgsMultiBandColorRenderer(
            myRasterLayer.dataProvider(), 2, 3, 4
        )
        #mRasterLayer.setRenderer( rasterRenderer )
        myPipe = myRasterLayer.pipe()
        assert myPipe.set( myRenderer ), "Cannot set pipe renderer"

        QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer])

        myMapRenderer = QgsMapRenderer()
        myLayerStringList = []
        myLayerStringList.append(myRasterLayer.id())
        myMapRenderer.setLayerSet(myLayerStringList)
        myMapRenderer.setProjectionsEnabled(False)

        myComposition = QgsComposition(myMapRenderer)
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        myTemplateFile = file(myFile, 'rt')
        myTemplateContent = myTemplateFile.read()
        myTemplateFile.close()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument)

        # now render the map, first zooming to the raster extents
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage

        myExtent = myRasterLayer.extent()
        myMap.setNewExtent(myExtent)

        myImagePath = os.path.join(str(QDir.tempPath()),
                                   'template_map_render_python.png')

        myPageNumber = 0
        myImage = myComposition.printPageAsRaster(myPageNumber)
        myImage.save(myImagePath)
        assert os.path.exists(myImagePath), 'Map render was not created.'

        # Not sure if this is a predictable way to test but its quicker than
        # rendering.
        myFileSize = QFileInfo(myImagePath).size()
        myExpectedFileSize = 100000
        myMessage = ('Expected file size to be greater than %s, got %s'
                     ' for %s' %
                     (myExpectedFileSize, myFileSize, myImagePath))
        assert myFileSize > myExpectedFileSize, myMessage
Пример #10
0
def addShapeToCanvas(shapefile_path):
    file_info = QFileInfo(shapefile_path)
    if file_info.exists():
        layer_name = file_info.completeBaseName()
    else:
        return False
    vlayer_new = QgsVectorLayer(shapefile_path, layer_name, "ogr")
    if vlayer_new.isValid():
        QgsMapLayerRegistry.instance().addMapLayers([vlayer_new])
        return True
    else:
        return False
Пример #11
0
def addShapeToCanvas(shapefile_path):
    file_info = QFileInfo(shapefile_path)
    if file_info.exists():
        layer_name = file_info.completeBaseName()
    else:
        return False
    vlayer_new = QgsVectorLayer(shapefile_path, layer_name, "ogr")
    if vlayer_new.isValid():
        QgsMapLayerRegistry.instance().addMapLayers([vlayer_new])
        return True
    else:
        return False
Пример #12
0
    def saveTemplate(self):
        """
        Creates and saves a new document template.
        """
        #Validate if the user has specified the data source
        if self.selectedDataSource() == "":
            QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \
                                            QApplication.translate("ComposerWrapper","Please specify the " \
                                                                   "data source name for the document composition."))
            return

        #If it is a new unsaved document template then prompt for the document name.
        docFile = self.documentFile()

        if docFile == None:
            docName,ok = QInputDialog.getText(self.composerView(), \
                                              QApplication.translate("ComposerWrapper","Template Name"), \
                                              QApplication.translate("ComposerWrapper","Please enter the template name below"), \
                                              )
            if ok and docName != "":
                templateDir = self._composerTemplatesPath()

                if templateDir == None:
                    QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \
                                            QApplication.translate("ComposerWrapper","Directory for document templates could not be found."))
                    return

                absPath = templateDir + "/" + docName + ".sdt"
                docFile = QFile(absPath)

            else:
                return

        docFileInfo = QFileInfo(docFile)

        if not docFile.open(QIODevice.WriteOnly):
            QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Operation Error"), \
                                            "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Could not save template file."), \
                                                      docFile.errorString()
                                                      ))
            return

        templateDoc = QDomDocument()
        self._writeXML(templateDoc, docFileInfo.completeBaseName())

        if docFile.write(templateDoc.toByteArray()) == -1:
            QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Error"), \
                                            QApplication.translate("ComposerWrapper","Could not save template file."))
            return

        docFile.close()
        self.setDocumentFile(docFile)
Пример #13
0
 def saveTemplate(self):
     """
     Creates and saves a new document template.
     """
     #Validate if the user has specified the data source
     if self.selectedDataSource() == "":
         QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \
                                         QApplication.translate("ComposerWrapper","Please specify the " \
                                                                "data source name for the document composition."))
         return
         
     #If it is a new unsaved document template then prompt for the document name.
     docFile = self.documentFile()
     
     if docFile == None:
         docName,ok = QInputDialog.getText(self.composerView(), \
                                           QApplication.translate("ComposerWrapper","Template Name"), \
                                           QApplication.translate("ComposerWrapper","Please enter the template name below"), \
                                           )
         if ok and docName != "":
             templateDir = self._composerTemplatesPath()
             
             if templateDir == None:
                 QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \
                                         QApplication.translate("ComposerWrapper","Directory for document templates could not be found."))
                 return
             
             absPath = templateDir + "/" + docName + ".sdt"            
             docFile= QFile(absPath)
         
         else:
             return
     
     docFileInfo = QFileInfo(docFile)    
     
     if not docFile.open(QIODevice.WriteOnly):
         QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Operation Error"), \
                                         "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Could not save template file."), \
                                                   docFile.errorString()
                                                   ))
         return
                                           
     templateDoc = QDomDocument()
     self._writeXML(templateDoc,docFileInfo.completeBaseName())
     
     if docFile.write(templateDoc.toByteArray()) == -1:
         QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Error"), \
                                         QApplication.translate("ComposerWrapper","Could not save template file."))
         return
     
     docFile.close()                   
     self.setDocumentFile(docFile)
    def on_pbn_set_storage_location_released(self):
        start_dir = paths.OPUS_PROJECT_CONFIGS_PATH

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,
                    QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                    QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.leOption1.setText(fileName)
    def on_pbn_set_storage_location_released(self):
        start_dir = os.path.join(os.environ['OPUS_HOME'], 'project_configs')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,
                    QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                    QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.leOption1.setText(fileName)
Пример #16
0
def isWritable(layer):
    if isInvalid(layer) or len(layer.vectorJoins()) > 0:
        return False
    if layer.storageType() == 'ESRI Shapefile':
        sourceList = layer.source().split('|')
        shpFile = QFileInfo(sourceList[0])
        baseFilePath = shpFile.canonicalPath() + '/' + shpFile.completeBaseName()
        shxFile = QFileInfo(baseFilePath + '.shx')
        dbfFile = QFileInfo(baseFilePath + '.dbf')
        return (shpFile.exists() and shpFile.isWritable()
                and shxFile.exists() and shxFile.isWritable()
                and dbfFile.exists() and dbfFile.isWritable())
    return True
Пример #17
0
    def _create_perimeter_layer(self, layer, perimeterLayerFilePath,
                                categoryName, perimeterLayerName, loadedLayer):
        """Creates a perimeter layer from the given layer.
        
        Args:
            layer (QgsVectorLayer): A reference to the layer.
            perimeterLayerFilePath (str): A full path to the perimeter layer.
            categoryName (str): A name of the category field the layer is about
                to be dissolved by.
            perimeterLayerName (str): A name of the perimeter layer.
            loadedLayer (bool): A reference to the loaded layer.
                This is relevant only for Windows platform.
        
        Returns:
            QgsVectorLayer: A reference to the perimeter layer.
        
        """

        fileInfo = QFileInfo(perimeterLayerFilePath)

        tempPerimeterLayerName = fileInfo.completeBaseName() + u'.temp'

        layer.removeSelection()

        tempPerimeterLayerPath = processing.runalg('qgis:dissolve', layer,
                                                   False, categoryName,
                                                   None)['OUTPUT']

        tempPerimeterLayer = QgsVectorLayer(tempPerimeterLayerPath,
                                            tempPerimeterLayerName, 'ogr')

        if loadedLayer:
            perimeterLayerName = loadedLayer.name()
            QgsMapLayerRegistry.instance().removeMapLayer(loadedLayer)

        QgsApplication.processEvents()

        processing.runalg('qgis:multiparttosingleparts', tempPerimeterLayer,
                          perimeterLayerFilePath)

        perimeterLayer = QgsVectorLayer(perimeterLayerFilePath,
                                        perimeterLayerName, 'ogr')

        QgsMapLayerRegistry.instance().addMapLayer(perimeterLayer)

        expression = QgsExpression("\"{}\" is null".format(
            self.shortCategoryName))

        self.dW.delete_features_by_expression(perimeterLayer, expression)

        return perimeterLayer
Пример #18
0
def isWritable(layer):
    if isInvalid(layer) or len(layer.vectorJoins()) > 0:
        return False
    if layer.storageType() == 'ESRI Shapefile':
        sourceList = layer.source().split('|')
        shpFile = QFileInfo(sourceList[0])
        baseFilePath = shpFile.canonicalPath(
        ) + '/' + shpFile.completeBaseName()
        shxFile = QFileInfo(baseFilePath + '.shx')
        dbfFile = QFileInfo(baseFilePath + '.dbf')
        return (shpFile.exists() and shpFile.isWritable() and shxFile.exists()
                and shxFile.isWritable() and dbfFile.exists()
                and dbfFile.isWritable())
    return True
    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                                          QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)
Пример #20
0
    def on_pbn_set_storage_location_released(self):
        start_dir = os.path.join(os.environ['OPUS_HOME'], 'project_configs')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.leOption1.setText(fileName)
Пример #21
0
    def on_pbn_set_storage_location_released(self):
        start_dir = paths.OPUS_PROJECT_CONFIGS_PATH

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.leOption1.setText(fileName)
Пример #22
0
	def action_writeGCode_triggered(self):

		if not len(self.trafoPoints) in {3, 4}:
			QMessageBox.warning(self, "not enough points", "Please select at least 3 transformation points.")
			return

		T=bilinearTrafo(self.trafoPoints, self.trafoMachinePoints)
		paths={}
		for dia in self.fitHoles:
			toolNr=self.drills[dia]
			paths[toolNr]=findPath(T.transform(self.fitHoles[dia]))
			
		fi=QFileInfo(self.currentFile)
		filename=fi.absolutePath() + "/" + fi.completeBaseName() + ".ngc"
		
		writeGCode(paths, filename, self.feedrate, self.drillDepth, self.drillSpacing)

		QMessageBox.information(self, "G-Code", "Finished!")
    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)
Пример #24
0
def zipLayer(layer):
    """Compress layer to zip file"""
    file_path = layer.dataProvider().dataSourceUri()
    if file_path.find('|') != -1:
        file_path = file_path[0:file_path.find('|')]

    if file_path.startswith('/vsizip/'):
        file_path = file_path.replace('/vsizip/', '')
        if layer.storageType() in [
                'ESRI Shapefile', 'GPX', 'GeoJSON', 'LIBKML'
        ]:
            return file_path
    _file = QFile(file_path)
    file_info = QFileInfo(_file)

    dirname = file_info.dir().absolutePath()
    filename = stripAccents(file_info.completeBaseName())
    layername = stripAccents(layer.name())

    tempdir = checkTempDir()

    zip_path = os.path.join(tempdir, layername + '.zip')
    zip_file = zipfile.ZipFile(zip_path, 'w')

    if layer.storageType() == 'ESRI Shapefile':
        for suffix in ['.shp', '.dbf', '.prj', '.shx']:
            if os.path.exists(os.path.join(dirname, filename + suffix)):
                zip_file.write(os.path.join(dirname, filename + suffix),
                               layername + suffix, zipfile.ZIP_DEFLATED)
    elif layer.storageType() == 'GeoJSON':
        zip_file.write(file_path, layername + '.geojson', zipfile.ZIP_DEFLATED)
    elif layer.storageType() == 'GPX':
        zip_file.write(file_path, layername + '.gpx', zipfile.ZIP_DEFLATED)
    elif layer.storageType() == 'LIBKML':
        zip_file.write(file_path, layername + '.kml', zipfile.ZIP_DEFLATED)
    else:
        geo_json_name = os.path.join(tempfile.tempdir, layername)
        error = QgsVectorFileWriter.writeAsVectorFormat(
            layer, geo_json_name, "utf-8", None, "GeoJSON")
        if error == QgsVectorFileWriter.NoError:
            zip_file.write(geo_json_name + '.geojson', layername + '.geojson',
                           zipfile.ZIP_DEFLATED)
    zip_file.close()
    return zip_path
Пример #25
0
    def getSize(self, layer):
        filePath = layer.dataProvider().dataSourceUri()
        if filePath.find('|') != -1:
            filePath = filePath[0:filePath.find('|')]

        file = QFile(filePath)
        fileInfo = QFileInfo(file)

        dirName = fileInfo.dir().absolutePath()
        fileName = fileInfo.completeBaseName()

        size = 0
        if layer.storageType() == 'ESRI Shapefile':
            for suffix in ['.shp', '.dbf', '.prj', '.shx']:
                file = QFile(os.path.join(dirName, fileName + suffix))
                fileInfo = QFileInfo(file)
                size = size + fileInfo.size()

        return size
Пример #26
0
    def _create_spatialite_db_file(self, dbPath):
        """Creates a SpatiaLite database file.
        
        Args:
            dbPath (str): A full path to the database.
        
        Returns:
            dbPath (str): A full path to the SpatiaLite database.
        
        """

        dbInfo = QFileInfo(dbPath)

        sdbPath = QDir(dbInfo.absolutePath())\
            .filePath(dbInfo.completeBaseName() + '.sdb')

        sdbInfo = QFileInfo(sdbPath)

        if not sdbInfo.isFile():
            self.set_text_statusbar.emit(
                u'Importuji data do SpatiaLite databáze...', 0, False)

            QgsApplication.processEvents()

            sqliteDriver = ogr.GetDriverByName('SQLite')
            spatialiteDataSource = sqliteDriver.CreateDataSource(
                sdbPath, ['SPATIALITE=YES'])

            sqliteDataSource = ogr.Open(dbPath)

            for layerCode in (
                    self.dW.parLayerCode, ) + self.dW.vertexLayerCodes:
                originalLayer = sqliteDataSource.GetLayerByName(layerCode)
                copiedLayer = spatialiteDataSource.CopyLayer(
                    originalLayer, layerCode, ['LAUNDER=NO'])

            sqliteDataSource.Destroy()
            spatialiteDataSource.Destroy()

        QgsApplication.processEvents()

        return sdbPath
Пример #27
0
    def zipLayer(self, layer):
        filePath = layer.dataProvider().dataSourceUri()
        if filePath.find('|') != -1:
            filePath = filePath[0:filePath.find('|')]

        file = QFile(filePath)
        fileInfo = QFileInfo(file)

        dirName = fileInfo.dir().absolutePath()
        fileName = fileInfo.completeBaseName()

        tempdir = tempfile.tempdir
        if tempdir is None:
            tempdir = tempfile.mkdtemp()

        zipPath = os.path.join(tempdir, layer.name() + '.zip')
        zipFile = zipfile.ZipFile(zipPath, 'w')

        if layer.storageType() == 'ESRI Shapefile':
            for suffix in ['.shp', '.dbf', '.prj', '.shx']:
                if os.path.exists(os.path.join(dirName, fileName + suffix)):
                    zipFile.write(os.path.join(dirName, fileName + suffix),
                                  fileName + suffix, zipfile.ZIP_DEFLATED)
        elif layer.storageType() == 'GeoJSON':
            zipFile.write(filePath,
                          layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
        else:
            geoJsonName = os.path.join(tempfile.tempdir, layer.name())
            error = QgsVectorFileWriter.writeAsVectorFormat(
                layer, geoJsonName, "utf-8", None, "GeoJSON")
            if error == QgsVectorFileWriter.NoError:
                zipFile.write(geoJsonName + '.geojson',
                              layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
        '''
        elif layer.storageType() == 'LIBKML':
            kmlName = os.path.join(tempfile.tempdir, layer.name())
            error = QgsVectorFileWriter.writeAsVectorFormat(layer, kmlName, "utf-8", None, "GeoJSON")
            if error == QgsVectorFileWriter.NoError:
                zipFile.write(kmlName + '.geojson', layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
        '''
        zipFile.close()
        return zipPath
Пример #28
0
    def getSize(self, layer):
        filePath = layer.dataProvider().dataSourceUri()
        if filePath.find('|') != -1:
            filePath = filePath[0:filePath.find('|')]

        file = QFile(filePath)
        fileInfo = QFileInfo(file)

        dirName = fileInfo.dir().absolutePath()
        fileName = fileInfo.completeBaseName()

        size = 0
        if layer.storageType() == 'ESRI Shapefile':
            for suffix in ['.shp', '.dbf', '.prj', '.shx']:
                file = QFile(os.path.join(dirName, fileName + suffix))
                fileInfo = QFileInfo(file)
                size = size + fileInfo.size()
        elif layer.storageType() in ['GPX', 'GeoJSON', 'LIBKML']:
            size = size + fileInfo.size()

        return size
Пример #29
0
 def open_file_dialog(self, title, filters, existence):
     """Opens a file dialog.
     
     Args:
         title (str): A title of the file dialog.
         filters (str): Available filter(s) of the file dialog.
         existence (bool):
             True when the file has to exist
             (QFileDialog.getOpenFileNameAndFilter).
             False when the file does not have to exist
             (QFileDialog.getSaveFileNameAndFilter).
     
     Returns:
         str: A path to the selected file.
     
     """
     
     sender = self.sender().objectName()
     
     lastUsedFilePath = self._get_settings(sender + '-' + 'lastUsedFilePath')
     lastUsedFilter = self._get_settings(sender + '-' + 'lastUsedFilter')
     
     if existence:
         filePath, usedFilter = QFileDialog.getOpenFileNameAndFilter(
             self, title, lastUsedFilePath, filters, lastUsedFilter)
     else:
         filePath, usedFilter = QFileDialog.getSaveFileNameAndFilter(
             self, title, lastUsedFilePath, filters, lastUsedFilter)
         
         fileInfo = QFileInfo(filePath)
         
         if platform.system() == u'Linux' and fileInfo.suffix() != u'shp':
             filePath = QDir(fileInfo.absolutePath())\
                 .filePath(fileInfo.completeBaseName() + u'.shp')
     
     if filePath and usedFilter:
         self._set_settings(sender + '-' + 'lastUsedFilePath', filePath)
         self._set_settings(sender + '-' + 'lastUsedFilter', usedFilter)
     
     return filePath
Пример #30
0
def zipLayer(layer):
    """Compress layer to zip file"""
    file_path = layer.dataProvider().dataSourceUri()
    if file_path.find('|') != -1:
        file_path = file_path[0:file_path.find('|')]

    if file_path.startswith('/vsizip/'):
        file_path = file_path.replace('/vsizip/', '')
        if layer.storageType() in ['ESRI Shapefile', 'GPX', 'GeoJSON', 'LIBKML']:
            return file_path

    _file = QFile(file_path)
    file_info = QFileInfo(_file)

    dirname = file_info.dir().absolutePath()
    filename = file_info.completeBaseName()

    tempdir = checkTempDir()

    zip_path = os.path.join(tempdir, layer.name() + '.zip')
    zip_file = zipfile.ZipFile(zip_path, 'w')


    if layer.storageType() == 'ESRI Shapefile':
        for suffix in ['.shp', '.dbf', '.prj', '.shx']:
            if os.path.exists(os.path.join(dirname, filename + suffix)):
                zip_file.write(os.path.join(dirname, filename + suffix), layer.name() + suffix, zipfile.ZIP_DEFLATED)
    elif layer.storageType() == 'GeoJSON':
        zip_file.write(file_path, layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
    elif layer.storageType() == 'GPX':
        zip_file.write(file_path, layer.name() + '.gpx', zipfile.ZIP_DEFLATED)
    elif layer.storageType() == 'LIBKML':
        zip_file.write(file_path, layer.name() + '.kml', zipfile.ZIP_DEFLATED)
    else:
        geo_json_name = os.path.join(tempfile.tempdir, layer.name())
        error = QgsVectorFileWriter.writeAsVectorFormat(layer, geo_json_name, "utf-8", None, "GeoJSON")
        if error == QgsVectorFileWriter.NoError:
            zip_file.write(geo_json_name + '.geojson', layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
    zip_file.close()
    return zip_path
Пример #31
0
    def zipLayer(self, layer):
        filePath = layer.dataProvider().dataSourceUri()
        if filePath.find('|') != -1:
            filePath = filePath[0:filePath.find('|')]

        file = QFile(filePath)
        fileInfo = QFileInfo(file)

        dirName = fileInfo.dir().absolutePath()
        fileName = fileInfo.completeBaseName()

        tempdir = tempfile.tempdir
        if tempdir is None:
            tempdir = tempfile.mkdtemp()

        zipPath = os.path.join(tempdir, layer.name() + '.zip')
        zipFile = zipfile.ZipFile(zipPath, 'w')

        if layer.storageType() == 'ESRI Shapefile':
            for suffix in ['.shp', '.dbf', '.prj', '.shx']:
                if os.path.exists(os.path.join(dirName, fileName + suffix)):
                    zipFile.write(os.path.join(dirName, fileName + suffix), fileName + suffix, zipfile.ZIP_DEFLATED)
        elif layer.storageType() == 'GeoJSON':
            zipFile.write(filePath, layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
        else:
            geoJsonName = os.path.join(tempfile.tempdir, layer.name())
            error = QgsVectorFileWriter.writeAsVectorFormat(layer, geoJsonName, "utf-8", None, "GeoJSON")
            if error == QgsVectorFileWriter.NoError:
                zipFile.write(geoJsonName + '.geojson', layer.name() + '.geojson', zipfile.ZIP_DEFLATED)

        '''
        elif layer.storageType() == 'LIBKML':
            kmlName = os.path.join(tempfile.tempdir, layer.name())
            error = QgsVectorFileWriter.writeAsVectorFormat(layer, kmlName, "utf-8", None, "GeoJSON")
            if error == QgsVectorFileWriter.NoError:
                zipFile.write(kmlName + '.geojson', layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
        '''
        zipFile.close()
        return zipPath
Пример #32
0
    def zipLayer(self, layer):
        filePath = layer.dataProvider().dataSourceUri()
        if filePath.find('|') != -1:
            filePath = filePath[0:filePath.find('|')]

        file = QFile(filePath)
        fileInfo = QFileInfo(file)

        dirName = fileInfo.dir().absolutePath()
        fileName = fileInfo.completeBaseName()
        zipPath = os.path.join(tempfile.tempdir, layer.name() + '.zip')
        zipFile = zipfile.ZipFile(zipPath, 'w')

        if os.path.exists(os.path.join(dirName, fileName + '.shp')):
            zipFile.write(os.path.join(dirName, fileName + '.shp'), fileName + '.shp', zipfile.ZIP_DEFLATED)
        if os.path.exists(os.path.join(dirName, fileName + '.dbf')):
            zipFile.write(os.path.join(dirName, fileName + '.dbf'), fileName + '.dbf', zipfile.ZIP_DEFLATED)
        if os.path.exists(os.path.join(dirName, fileName + '.prj')):
            zipFile.write(os.path.join(dirName, fileName + '.prj'), fileName + '.prj', zipfile.ZIP_DEFLATED)
        if os.path.exists(os.path.join(dirName, fileName + '.shx')):
            zipFile.write(os.path.join(dirName, fileName + '.shx'), fileName + '.shx', zipfile.ZIP_DEFLATED)
        zipFile.close()
        return zipPath
    def testCase(self):
        TEST_DATA_DIR = unitTestDataPath()
        vectorFileInfo = QFileInfo( TEST_DATA_DIR + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )

        QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append( mVectorLayer.id() )
        mMapRenderer.setLayerSet( layerStringList )
        mMapRenderer.setProjectionsEnabled( False )

        mComposition = QgsComposition( mMapRenderer )
        mComposition.setPaperSize( 297, 210 )

        mLabel = QgsComposerLabel( mComposition )
        mComposition.addComposerLabel( mLabel )

        self.evaluation_test( mComposition, mLabel )
        self.feature_evaluation_test( mComposition, mLabel, mVectorLayer )
        self.page_evaluation_test( mComposition, mLabel, mVectorLayer )
Пример #34
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        vectorFileInfo = QFileInfo( self.TEST_DATA_DIR + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )

        QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append( mVectorLayer.id() )
        mMapRenderer.setLayerSet( layerStringList )
        mMapRenderer.setProjectionsEnabled( True )
        mMapRenderer.setMapUnits( QGis.Meters )

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid( 2154 )
        mMapRenderer.setDestinationCrs( crs )

        self.mComposition = QgsComposition( mMapRenderer )
        self.mComposition.setPaperSize( 297, 210 )

        # fix the renderer, fill with green
        props = { "color": "0,127,0" }
        fillSymbol = QgsFillSymbolV2.createSimple( props )
        renderer = QgsSingleSymbolRendererV2( fillSymbol )
        mVectorLayer.setRendererV2( renderer )

        # the atlas map
        self.mAtlasMap = QgsComposerMap( self.mComposition, 20, 20, 130, 130 )
        self.mAtlasMap.setFrameEnabled( True )
        self.mComposition.addComposerMap( self.mAtlasMap )

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer( mVectorLayer )
        self.mAtlas.setEnabled( True )
        self.mComposition.setAtlasMode( QgsComposition.ExportAtlas )

        # an overview
        mOverview = QgsComposerMap( self.mComposition, 180, 20, 50, 50 )
        mOverview.setFrameEnabled( True )
        mOverview.setOverviewFrameMap( self.mAtlasMap.id() )
        self.mComposition.addComposerMap( mOverview )
        nextent = QgsRectangle( 49670.718, 6415139.086, 699672.519, 7065140.887 )
        mOverview.setNewExtent( nextent )

        # set the fill symbol of the overview map
        props2 = { "color": "127,0,0,127" }
        fillSymbol2 = QgsFillSymbolV2.createSimple( props2 )
        mOverview.setOverviewFrameMapSymbol( fillSymbol2 )

        # header label
        self.mLabel1 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel1 )
        self.mLabel1.setText( "[% \"NAME_1\" %] area" )
        self.mLabel1.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect( QRectF( 150, 5, 60, 15 ) )

        qWarning( "header label font: %s exactMatch:%s" % ( self.mLabel1.font().toString(), self.mLabel1.font().exactMatch() ) )

        # feature number label
        self.mLabel2 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel2 )
        self.mLabel2.setText( "# [%$feature || ' / ' || $numfeatures%]" )
        self.mLabel2.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect( QRectF( 150, 200, 60, 15 ) )

        qWarning( "feature number label font: %s exactMatch:%s" % ( self.mLabel2.font().toString(), self.mLabel2.font().exactMatch() ) )

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
    def importXMLFromFile(self):
        """ NO DOCUMENTATION """
        assert self.has_selected_item()
        # print "importXMLFromFile"
        # First, prompt the user for the filename to read in
        start_dir = ""
        opus_home = os.environ.get("OPUS_HOME")
        if opus_home:
            start_dir_test = os.path.join(opus_home, "project_configs")
            if start_dir_test:
                start_dir = start_dir_test
        configDialog = QFileDialog()
        filter_str = QString("*.xml")
        fd = configDialog.getOpenFileName(
            self.manager.base_widget, "Please select an xml file to import...", start_dir, filter_str
        )
        # Check for cancel
        if len(fd) == 0:
            return
        fileName = QString(fd)
        fileNameInfo = QFileInfo(QString(fd))
        fileNameInfoBaseName = fileNameInfo.completeBaseName()
        fileNameInfoName = fileNameInfo.fileName().trimmed()
        fileNameInfoPath = fileNameInfo.absolutePath().trimmed()

        # Pass that in to create a new XMLConfiguration
        xml_config = XMLConfiguration(str(fileNameInfoName), str(fileNameInfoPath))

        xml_node = xml_config.full_tree.getroot()
        if len(xml_node) == 0:
            raise ValueError("Loading node from XML file failed. " "No node definition found")
        xml_node = xml_node[0]

        parent_node = self.selected_item().node

        allowed_parent_tags = {
            "tool": ["tool_group"],
            "class_module": ["tool"],
            "path_to_tool_modules": ["tool_library"],
            "tool_library": ["data_manager"],
            "tool_group": ["tool_library"],
            "params": ["tool"],
            "param": ["params"],
            "tool_config": ["tool_set"],
            "tool_set": ["tool_sets"],
            "tool_sets": ["data_manager"],
        }
        if parent_node.tag not in allowed_parent_tags[xml_node.tag]:
            MessageBox.error(
                mainwindow=self.view,
                text="Invalid Xml insert",
                detailed_text=(
                    'Xml insert of node of type "%s" failed.  '
                    'Invalid type of parent node is "%s" - needs to be one of %s'
                    % (xml_node.tag, parent_node.tag, str(allowed_parent_tags[xml_node.tag]))
                ),
            )
            return

        # Insert it into the parent node from where the user clicked
        name = xml_node.get("name") if xml_node.get("name") is not None else ""
        if self.model.insertRow(0, self.selected_index(), xml_node) is False:
            MessageBox.error(
                mainwindow=self.view,
                text="Xml Insert Failed",
                detailed_text=(
                    'Xml insert of node with name "%s" failed - '
                    "most likely because there is already a node with that name." % name
                ),
            )
            return
Пример #36
0
    def saveTemplate(self):
        """
        Creates and saves a new document template.
        """
        #Validate if the user has specified the data source
        if not self.selectedDataSource():
            QMessageBox.critical(self.composerView(),
                                 QApplication.translate("ComposerWrapper","Error"),
                                QApplication.translate("ComposerWrapper","Please specify the "
                                            "data source name for the document composition."))
            return
            
        #If it is a new unsaved document template then prompt for the document name.
        docFile = self.documentFile()
        
        if docFile is None:
            docName,ok = QInputDialog.getText(self.composerView(),
                            QApplication.translate("ComposerWrapper","Template Name"),
                            QApplication.translate("ComposerWrapper","Please enter the template name below"),
                            )

            if ok and docName:
                templateDir = self._composerTemplatesPath()
                
                if templateDir is None:
                    QMessageBox.critical(self.composerView(),
                        QApplication.translate("ComposerWrapper","Error"),
                        QApplication.translate("ComposerWrapper",
                        "Directory for document templates cannot not be found."))

                    return

                absPath = templateDir + "/" + docName + ".sdt"

                #Check if there is an existing document with the same name
                caseInsenDic = CaseInsensitiveDict(documentTemplates())
                if docName in caseInsenDic:
                    result = QMessageBox.warning(self.composerView(),
                            QApplication.translate("ComposerWrapper",
                                                   "Existing Template"),
                                            u"'{0}' {1}.\nDo you want to replace the "
                                            "existing template?".format(docName,
                                            QApplication.translate("ComposerWrapper",
                                                                   "already exists")),
                                            QMessageBox.Yes|QMessageBox.No)

                    if result == QMessageBox.Yes:
                        #Delete the existing template
                        delFile = QFile(absPath)
                        remStatus = delFile.remove()
                        if not remStatus:
                            QMessageBox.critical(self.composerView(),
                            QApplication.translate("ComposerWrapper",
                                                   "Delete Error"),
                                            "'{0}' {1}.".format(docName,
                            QApplication.translate("ComposerWrapper",
                            "template could not be removed by the system,"
                            " please remove it manually from the document templates directory.")))
                            return

                    else:
                        return

                docFile= QFile(absPath)
            
            else:
                return
        
        docFileInfo = QFileInfo(docFile)
        
        if not docFile.open(QIODevice.WriteOnly):
            QMessageBox.critical(self.composerView(),
                                 QApplication.translate("ComposerWrapper",
                                "Save Operation Error"),
                                "{0}\n{1}".format(QApplication.translate("ComposerWrapper",
                                "Could not save template file."),
                                                      docFile.errorString()
                                ))

            return
                                              
        templateDoc = QDomDocument()
        template_name = docFileInfo.completeBaseName()
        self._writeXML(templateDoc, template_name)
        
        if docFile.write(templateDoc.toByteArray()) == -1:
            QMessageBox.critical(self.composerView(),
            QApplication.translate("ComposerWrapper","Save Error"),
            QApplication.translate("ComposerWrapper","Could not save template file."))

            return

        else:
            self.mainWindow().setWindowTitle(template_name)
        
        docFile.close()
Пример #37
0
'''
QGIS Processing script
(c) 2017 Andreas Plesch
save style in qml file
'''
##X3D=group
##save_raster_style=name
##input_raster=raster
##style_file=output file

import shutil
from PyQt4.QtCore import QFile, QFileInfo, QDir

#saveNamedStyle always writes to .qml
fileInfo = QFileInfo(style_file)
style_file = fileInfo.path() + QDir.separator() + fileInfo.completeBaseName() + ".qml"

file=QFile(style_file)
#touch, create since saveStyle only writes file if it exists
file.open(QFile.ReadWrite)
file.close()

r = processing.getObject(input_raster)
print(r.saveNamedStyle(style_file))
#saveNamedStyle always writes to .qml
#copy back
#fileInfo = QFileInfo(style_file)
#style_file = fileInfo.path() + QDir.separator() + fileInfo.completeBaseName() + ".qml"
#shutil.copy(qml, style_file)

Пример #38
0
    def upload_document(self,
                        path,
                        doc_type='',
                        doc_type_code='',
                        use_temp_dir=True,
                        clear_all=True):
        """
        Uploads the document specified in path to the folder of the given
        document type based on the specified document type folder mapping.
        :param path: Absolute path of the file to be uploaded.
        :type path: str
        :param doc_type: Name of the document type.
        :type doc_type: str
        :param doc_type_code: Code of the document type which is used to
        identify the document type. If doc_type has already been specified
        then the value of this parameter is skipped.
        :type doc_type_code: str
        :param use_temp_dir: Specify True to upload the document in the Temp
        directory using an auto-generated name then move it to the correct
        document type repository using the :func:'persist_documents' method.
        If set to False, the document will be directly uploaded to the
        corresponding document type folder. Default is True.
        :type use_temp_dir: bool
        :param clear_all: True to clear all previously uploaded documents (in
        the current session) for the given document type.
        :return: Returns the AtomPub document object, else None if it was
        not successfully created.
        :rtype: cmislib.domain.Document
        """
        if not doc_type and not doc_type_code:
            msg = 'Please specify the document type name or code.'
            raise CmisDocumentMapperException(msg)

        if not self._cmis_mgr:
            msg = 'CmisManager object not specified.'
            raise CmisDocumentMapperException(msg)

        # Get doc_type from code
        if doc_type_code and not doc_type_code:  # @gkahiu code underneath may never be reached
            doc_type_m = self.mapping_by_code(doc_type_code)
            if not doc_type_m:
                msg = u'Document type could not be retrieved from {0} ' \
                      u'document type code.'.format(doc_type_code)
                raise CmisDocumentMapperException(msg)
            else:
                doc_type = doc_type_m.doc_type

        if not doc_type in self._doc_type_mapping:
            msg = 'Mapping for the specified document type name not found.'
            raise CmisDocumentMapperException(msg)

        if use_temp_dir:
            dest_folder = self._cmis_mgr.context_temp_folder
        else:
            dest_folder = self.document_type_folder(doc_type)

        # Try create the folder if it does not exist
        if not dest_folder:
            if use_temp_dir:
                status = self._cmis_mgr.create_temp_folder()
                if not status:
                    msg = 'Temp directory could not be created.'
                    raise CmisDocumentMapperException(msg)
                else:
                    dest_folder = self._cmis_mgr.context_temp_folder
            else:
                dest_folder = self.create_document_type_folder(doc_type)

        # Clear all documents of the given type, if option has been specified
        if clear_all:
            self.remove_all_documents(doc_type)

        if use_temp_dir:
            doc_name = str(uuid4())
        else:
            # Get name of the file without the extension
            fi = QFileInfo(path)
            doc_name = fi.completeBaseName()

        # Determine whether file is text or binary
        read_mode = 'rb'
        mime_type, encoding = guess_type(path)
        text_idx = mime_type.find('text')
        if text_idx != -1:
            read_mode = 'r'

        if not mime_type:
            msg = 'MIME type could not be determined.'
            raise CmisDocumentMapperException(msg)

        # Manually set the valid MIME type for PDF
        if mime_type == 'pdf':
            mime_type = 'application/pdf'

        cmis_doc = None
        with open(path, read_mode) as f:
            cmis_doc = dest_folder.createDocument(doc_name,
                                                  contentFile=f,
                                                  contentType=mime_type)

        # Update reference of uploaded documents.
        if not doc_type in self._uploaded_docs:
            self._uploaded_docs[doc_type] = []

        if cmis_doc:
            doc_info = UploadedDocInfo(cmis_doc=cmis_doc,
                                       temp_dir=use_temp_dir)

            uploaded_type_docs = self._uploaded_docs[doc_type]
            uploaded_type_docs.append(doc_info)

        return cmis_doc
Пример #39
0
    def saveTemplate(self):
        """
        Creates and saves a new document template.
        """
        # Validate if the user has specified the data source
        if not self.selectedDataSource():
            QMessageBox.critical(
                self.composerView(),
                QApplication.translate("ComposerWrapper", "Error"),
                QApplication.translate(
                    "ComposerWrapper", "Please specify the "
                    "data source name for the document composition."))
            return

        # Assert if the referenced table name has been set
        if not self.selected_referenced_table():
            QMessageBox.critical(
                self.composerView(),
                QApplication.translate("ComposerWrapper", "Error"),
                QApplication.translate(
                    "ComposerWrapper", "Please specify the "
                    "referenced table name for the selected data source."))
            return

        # If it is a new unsaved document template then prompt for the document name.
        docFile = self.documentFile()

        if docFile is None:
            docName, ok = QInputDialog.getText(
                self.composerView(),
                QApplication.translate("ComposerWrapper", "Template Name"),
                QApplication.translate("ComposerWrapper",
                                       "Please enter the template name below"),
            )

            if not ok:
                return

            if ok and not docName:
                QMessageBox.critical(
                    self.composerView(),
                    QApplication.translate("ComposerWrapper", "Error"),
                    QApplication.translate("ComposerWrapper",
                                           "Please enter a template name!"))
                self.saveTemplate()

            if ok and docName:
                templateDir = self._composerTemplatesPath()

                if templateDir is None:
                    QMessageBox.critical(
                        self.composerView(),
                        QApplication.translate("ComposerWrapper", "Error"),
                        QApplication.translate(
                            "ComposerWrapper",
                            "Directory for document templates cannot not be found."
                        ))

                    return

                absPath = templateDir + "/" + docName + ".sdt"

                #Check if there is an existing document with the same name
                caseInsenDic = CaseInsensitiveDict(documentTemplates())
                if docName in caseInsenDic:
                    result = QMessageBox.warning(
                        self.composerView(),
                        QApplication.translate("ComposerWrapper",
                                               "Existing Template"),
                        u"'{0}' {1}.\nDo you want to replace the "
                        "existing template?".format(
                            docName,
                            QApplication.translate("ComposerWrapper",
                                                   "already exists")),
                        QMessageBox.Yes | QMessageBox.No)

                    if result == QMessageBox.Yes:
                        #Delete the existing template
                        delFile = QFile(absPath)
                        remStatus = delFile.remove()
                        if not remStatus:
                            QMessageBox.critical(
                                self.composerView(),
                                QApplication.translate("ComposerWrapper",
                                                       "Delete Error"),
                                "'{0}' {1}.".format(
                                    docName,
                                    QApplication.translate(
                                        "ComposerWrapper",
                                        "template could not be removed by the system,"
                                        " please remove it manually from the document templates directory."
                                    )))
                            return

                    else:
                        return

                docFile = QFile(absPath)

            else:
                return

        docFileInfo = QFileInfo(docFile)

        if not docFile.open(QIODevice.WriteOnly):
            QMessageBox.critical(
                self.composerView(),
                QApplication.translate("ComposerWrapper",
                                       "Save Operation Error"),
                "{0}\n{1}".format(
                    QApplication.translate("ComposerWrapper",
                                           "Could not save template file."),
                    docFile.errorString()))

            return

        templateDoc = QDomDocument()
        template_name = docFileInfo.completeBaseName()

        # Catch exception raised when writing items' elements
        try:
            self._writeXML(templateDoc, template_name)
        except Exception as exc:
            msg = unicode(exc)
            QMessageBox.critical(
                self.composerView(),
                QApplication.translate("ComposerWrapper", "Save Error"), msg)
            docFile.close()
            docFile.remove()

            return

        if docFile.write(templateDoc.toByteArray()) == -1:
            QMessageBox.critical(
                self.composerView(),
                QApplication.translate("ComposerWrapper", "Save Error"),
                QApplication.translate("ComposerWrapper",
                                       "Could not save template file."))

            return

        else:
            self.mainWindow().setWindowTitle(template_name)

        self.setDocumentFile(docFile)
        docFile.close()

        if self.copy_template_file:
            self.copy_template_file.close()
Пример #40
0
class FileSystemItem(QObject):
    """
    An element in the FileSystemModel.
    """
    iconProvider = QFileIconProvider()
    fileExtensions = ['*.qlr']
    xmlSearchableTags = ['title', 'abstract','layername', 'attribution']


    def __init__(self, file, recurse = True, recursion_counter = None, namingregex = None):
        super(FileSystemItem, self).__init__()

        # Raise exception if root path has too many child elements
        if recursion_counter:
            recursion_counter.increment()

        if isinstance(file, QFileInfo):
            self.fileinfo = file
        else:
            self.fileinfo = QFileInfo(file)
        self.fullpath = self.fileinfo.absoluteFilePath()
        self.basename = self.fileinfo.completeBaseName()
        self.displayname = self.fileinfo.fileName() if self.fileinfo.isDir() else self.fileinfo.completeBaseName()
        if namingregex:
            self.displayname = namingregex.match(self.displayname).group(1)
        self.icon = FileSystemItem.iconProvider.icon(self.fileinfo)
        self.isdir = self.fileinfo.isDir()
        self.children = [] if self.isdir else None
        if self.isdir and recurse:
            qdir = QDir(self.fullpath)
            for finfo in qdir.entryInfoList(
                    FileSystemItem.fileExtensions , QDir.Files | QDir.AllDirs | QDir.NoDotAndDotDot,QDir.Name):
                self.children.append(FileSystemItem(finfo, recurse, recursion_counter, namingregex))
        else:
            # file
            # Populate this if and when needed
            self.searchablecontent = None

    def filtered(self, filter):
        """
        Filters the root path.
        :filter is a string. Is it contained in the basename or displayname then this item will be rendered.
        :return: the directory item. If nothing is found returns None.
        """
        if not filter:
            return self
        filterlower = filter.lower()
        namematch = self.name_matches(filter)
        if self.isdir:
            if namematch:
                # Stop searching. Return this dir and all sub items
                return FileSystemItem(self.fullpath, True)
            else:
                # Only return dir if at least one sub item is a filter match
                diritem = FileSystemItem(self.fullpath, False)
                for child in self.children:
                    childmatch = child.filtered(filter)
                    if childmatch is not None:
                        diritem.children.append((childmatch))
                if len(diritem.children) > 0:
                    return diritem
        else:
            if self.searchablecontent is None:
                self.searchablecontent = self.get_searchable_content().lower()
            if namematch or self.content_matches(filter):
                return FileSystemItem(self.fullpath, False)
        return None

    def matches(self, searchterm):
        """Returns true if this item mathces the searchterm"""
        return self.name_matches(searchterm) or self.content_matches(searchterm)

    def name_matches(self, searchterm):
        """Returns true if the searchterm matches the name of this item"""
        lowered = searchterm.lower()
        return lowered in self.basename.lower() or lowered in self.displayname.lower()

    def content_matches(self, searchterm):
        """Returns True if the searchterm matches content of this item"""
        if self.isdir:
            return False
        lowered = searchterm.lower()
        if self.searchablecontent is None:
                self.searchablecontent = self.get_searchable_content().lower()
        return lowered in self.searchablecontent

    def get_searchable_content(self):
        """
        Pulls out tags from the object and returns them in order to be used by the filtered() method.
        """
        f = QFile(self.fileinfo.absoluteFilePath())
        f.open(QIODevice.ReadOnly)
        #stream = QTextStream(f)
        #stream.setCodec("UTF-8")
        try:
            doc = QDomDocument()
            doc.setContent( f.readAll() )
            docelt = doc.documentElement()

            texts = []

            for tagName in FileSystemItem.xmlSearchableTags:
                nodes = docelt.elementsByTagName(tagName)
                for i in range(nodes.count()):
                    node = nodes.at(i)
                    value = node.firstChild().toText().data()
                    #print value
                    texts.append( value )

            # Add keywords
            nodes = docelt.elementsByTagName("keywordList")
            for i in range(nodes.count()):
                kwnode = nodes.at(i)
                valnodes = kwnode.toElement().elementsByTagName("value")
                for j in range(valnodes.count()):
                    value = valnodes.at(j).firstChild().toText().data()
                    texts.append(value)

            return u' '.join(texts)
        finally:
            f.close()
Пример #41
0
Файл: scj.py Проект: Ptaah/SCJ
class SCJ(QThread):
    lock = QMutex()
    def __init__(self, file=None, format=None, createDir=False):
        super(SCJ, self).__init__()
        self.format = format
        self.filename = file
        self.file = QFileInfo(self.filename)
        self.file.makeAbsolute()
        self.suffix = self.file.suffix()
        if createDir:
            self.outputdir = u"%s-%s" % (self.file.path(), self.format)
        else:
            self.outputdir = self.file.path()
        self.output = u"%s%c%s.%s" % ( self.outputdir,
                                       QDir.separator().unicode(),
                                       self.file.completeBaseName(),
                                       self.format)
        if self.format != "mp3":
            self.command = [ u"/usr/bin/sox", u"-S", u"%s" % self.filename,
                             u"-t", u"%s" % self.format, u"%s" % self.output ]
            self.pipecmd = None
        else:
            self.command = [ u"/usr/bin/sox", u"-S", u"%s" % self.filename,
                             u"-t", u"wav", u"-" ]
            self.pipecmd = [ u"/usr/bin/ffmpeg", u"-y", u"-i", u"-",
                             u"-f", u"%s" % self.format, u"%s" % self.output ]
        self.value = 0
        self.process = None
        self.retCode = None
        self.running = False
        self.log = QString(u"")

    def setProgress(self, value):
        self.value = value
        self.emit(SIGNAL("progress(int)"), self.value)

    def mkdir(self, path):
        directory = QDir(path)
        SCJ.lock.lock()
        if not directory.exists() :
            if not directory.mkpath(path) :
                self.emit(SIGNAL("error(QString)"),
                          QString(self.trUtf8("Cannot create %s" % path)))
        SCJ.lock.unlock()

    def run(self):
        self.running = True
        self.mkdir(self.outputdir)
        self.process = Process( self.command,
                                    stdinput = None)
        if self.pipecmd :
            self.pipe = Process( self.pipecmd, stdinput = self.process.stdout)
            self.process.stdout.close()
        self.emit(SIGNAL("void started()"))
        while self.retCode == None :
            try:
                self.progression()
            except IOError as e:
                pass

            self.retCode = self.process.poll()
            self.usleep(10)
        self.running = False
        self.end()

    def resume(self):
        if self.process :
            try :
                self.process.send_signal(signal.SIGCONT)
            except OSError :
                pass

    def stop(self):
        if self.process :
            try :
                self.process.send_signal(signal.SIGSTOP)
            except OSError :
                pass

    def cancel(self):
        if self.process :
            try :
                try:
                    self.process.terminate()
                    self.process.wait()
                except Exception as e:
                    self.process.kill()
            except OSError as e :
                pass
        self.running = False

    def end(self):
        if self.retCode != 0 :
            self.emit(SIGNAL("error(QString)"), self.trUtf8("Code de retour sox : %d\n%s" %
                             (self.retCode, self.log)))
        else:
            if mp3tags : self.set_tags()
            self.setProgress(100)
        self.emit(SIGNAL("finished()"))

    def progression(self):
        """
        Recupération de la progression du process en cours
        """
        line = self.process.stderr.readline()
        if re.match(u'^In:.*', line):
            val = re.findall(u"[\.\d]+%", line)[0]
            self.setProgress(float(val[:-1]))
        else :
            self.log.append(line)

    def set_tags(self):
        """
        Update audio file metadata (Id3 tags...)
        """
        if self.format != "mp3":
            return
        tags =  mutagen.File(u"%s" % self.filename, easy = True)
        audio = EasyID3(u"%s" % self.output)
        for key in tags.keys():
            # Ugly hack to have the year in the mp3 metadata
            if key == "year":
                audio["date"] = tags[key]
            else:
                if key in audio.valid_keys :
                    audio[key] = tags[key]
        audio.save()
Пример #42
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

        QgsMapLayerRegistry.instance().addMapLayers([mVectorLayer])

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        mMapRenderer.setLayerSet(layerStringList)
        mMapRenderer.setProjectionsEnabled(True)
        mMapRenderer.setMapUnits(QGis.Meters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        mMapRenderer.setDestinationCrs(crs)

        self.mComposition = QgsComposition(mMapRenderer)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbolV2.createSimple(props)
        renderer = QgsSingleSymbolRendererV2(fillSymbol)
        mVectorLayer.setRendererV2(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.setOverviewFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbolV2.createSimple(props2)
        mOverview.setOverviewFrameMapSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%$feature || ' / ' || $numfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()

        shutil.rmtree(tmppath, True)
    def importXMLFromFile(self):
        ''' NO DOCUMENTATION '''
        assert self.has_selected_item()
        # print "importXMLFromFile"
        # First, prompt the user for the filename to read in
        start_dir = ''
        opus_home = os.environ.get('OPUS_HOME')
        if opus_home:
            start_dir_test = os.path.join(opus_home, 'project_configs')
            if start_dir_test:
                start_dir = start_dir_test
        configDialog = QFileDialog()
        filter_str = QString("*.xml")
        fd = configDialog.getOpenFileName(
            self.manager.base_widget, "Please select an xml file to import...",
            start_dir, filter_str)
        # Check for cancel
        if len(fd) == 0:
            return
        fileName = QString(fd)
        fileNameInfo = QFileInfo(QString(fd))
        fileNameInfoBaseName = fileNameInfo.completeBaseName()
        fileNameInfoName = fileNameInfo.fileName().trimmed()
        fileNameInfoPath = fileNameInfo.absolutePath().trimmed()

        # Pass that in to create a new XMLConfiguration
        xml_config = XMLConfiguration(str(fileNameInfoName),
                                      str(fileNameInfoPath))

        xml_node = xml_config.full_tree.getroot()
        if len(xml_node) == 0:
            raise ValueError('Loading node from XML file failed. '
                             'No node definition found')
        xml_node = xml_node[0]

        parent_node = self.selected_item().node

        allowed_parent_tags = {"tool": ["tool_group"], \
                               "class_module": ["tool"], \
                                    "path_to_tool_modules": ["tool_library"], \
                               "tool_library": ["data_manager"], \
                               "tool_group": ["tool_library"], \
                               "params": ["tool"], \
                               "param": ["params"], \
                               "tool_config": ["tool_set"], \
                               "tool_set": ["tool_sets"], \
                               "tool_sets": ["data_manager"]}
        if parent_node.tag not in allowed_parent_tags[xml_node.tag]:
            MessageBox.error(
                mainwindow=self.view,
                text='Invalid Xml insert',
                detailed_text=
                ('Xml insert of node of type "%s" failed.  '
                 'Invalid type of parent node is "%s" - needs to be one of %s'
                 % (xml_node.tag, parent_node.tag,
                    str(allowed_parent_tags[xml_node.tag]))))
            return

        # Insert it into the parent node from where the user clicked
        name = xml_node.get('name') if xml_node.get('name') is not None else ''
        if self.model.insertRow(0, self.selected_index(), xml_node) is False:
            MessageBox.error(
                mainwindow=self.view,
                text='Xml Insert Failed',
                detailed_text=
                ('Xml insert of node with name "%s" failed - '
                 'most likely because there is already a node with that name.'
                 % name))
            return
Пример #44
0
    def _create_perimeter(self):
        """Calls methods for creating and loading perimeter layer."""

        try:
            succes, layer = self.dW.check_layer(self)

            if not succes:
                return

            if layer.featureCount() == 0:
                self.set_text_statusbar.emit(
                    u'Aktivní vrstva neobsahuje žádný prvek.', 10, True)
                return

            editing = self.dW.check_editing()

            title = u'Uložit vrstvu obvodu jako...'
            filters = u'.shp (*.shp)'

            perimeterLayerFilePath = self.dW.open_file_dialog(
                title, filters, False)

            if perimeterLayerFilePath:
                self.set_text_statusbar.emit(u'Vytvářím vrstvu obvodu...', 0,
                                             False)

                fileInfo = QFileInfo(perimeterLayerFilePath)

                if not fileInfo.suffix() == u'shp':
                    perimeterLayerFilePath = \
                        fileInfo.absoluteFilePath() + u'.shp'
                    fileInfo = QFileInfo(perimeterLayerFilePath)

                selectedFeaturesIds = layer.selectedFeaturesIds()

                perimeterLayerName = fileInfo.completeBaseName()

                loadedLayer = self.dW.check_loaded_layers(
                    perimeterLayerFilePath)

                perimeterLayer = self._create_perimeter_layer(
                    layer, perimeterLayerFilePath, self.categoryName,
                    perimeterLayerName, loadedLayer)

                QgsApplication.processEvents()

                loadedLayer = self.dW.check_loaded_layers(
                    perimeterLayerFilePath)

                if loadedLayer:
                    self.iface.actionDraw().trigger()
                    self.set_perimeter_layer(loadedLayer, False)
                    self.sync_perimeter_map_layer_combo_box()
                else:
                    QgsMapLayerRegistry.instance().addMapLayer(perimeterLayer)

                layer.selectByIds(selectedFeaturesIds)

                self.iface.setActiveLayer(layer)

                if editing:
                    self.toggleEditingAction.trigger()

                self.set_text_statusbar.emit(u'Obvod byl úspešně vytvořen.',
                                             15, False)
        except:
            self.dW.display_error_messages(self, u'Error creating perimeter.',
                                           u'Chyba při vytváření obvodu.')