Beispiel #1
0
    def testQgsCentroidFillSymbolLayerV2(self):
        """
        Create a new style from a .sld file and match test
        """
        mTestName = 'QgsCentroidFillSymbolLayerV2'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsCentroidFillSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'regular_star'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'#55aaff'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'#00ff00'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Beispiel #2
0
    def testQgsSVGFillSymbolLayer(self):
        """
        Create a new style from a .sld file and match test
        """
        mTestName = 'QgsSVGFillSymbolLayer'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSVGFillSymbolLayer(""))
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 'accommodation_camping.svg'
        mValue = os.path.basename(mSymbolLayer.svgFilePath())
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 6
        mValue = mSymbolLayer.patternWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Beispiel #3
0
    def testQgsSvgMarkerSymbolLayer(self):
        """
        Create a new style from a .sld file and match test
        """
        mTestName = 'QgsSvgMarkerSymbolLayer'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsSvgMarkerSymbolLayer.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSvgMarkerSymbolLayer(""))
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 'skull.svg'
        mValue = os.path.basename(mSymbolLayer.path())
        print(("VALUE", mSymbolLayer.path()))
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 12
        mValue = mSymbolLayer.size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 45
        mValue = mSymbolLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Beispiel #4
0
    def _add_raster_layer(self, raster_layer, layer_name, save_style=False):
        """Add a raster layer to the folder.

        :param raster_layer: The layer to add.
        :type raster_layer: QgsRasterLayer

        :param layer_name: The name of the layer in the datastore.
        :type layer_name: str

        :param save_style: If we have to save a QML too. Default to False.
        :type save_style: bool

        :returns: A two-tuple. The first element will be True if we could add
            the layer to the datastore. The second element will be the layer
            name which has been used or the error message.
        :rtype: (bool, str)

        .. versionadded:: 4.0
        """
        if not self.is_writable():
            return False, 'The destination is not writable.'

        output = QFileInfo(self.uri.filePath(layer_name + '.tif'))

        source = QFileInfo(raster_layer.source())
        if source.exists() and source.suffix() in ['tiff', 'tif']:
            # If it's tiff file based.
            QFile.copy(source.absoluteFilePath(), output.absoluteFilePath())

        else:
            # If it's not file based.
            renderer = raster_layer.renderer()
            provider = raster_layer.dataProvider()
            crs = raster_layer.crs()

            pipe = QgsRasterPipe()
            pipe.set(provider.clone())
            pipe.set(renderer.clone())

            file_writer = QgsRasterFileWriter(output.absoluteFilePath())
            file_writer.Mode(1)

            file_writer.writeRaster(
                pipe,
                provider.xSize(),
                provider.ySize(),
                provider.extent(),
                crs)

            del file_writer

        if save_style:
            style_path = QFileInfo(self.uri.filePath(layer_name + '.qml'))
            raster_layer.saveNamedStyle(style_path.absoluteFilePath())

        assert output.exists()
        return True, output.baseName()
Beispiel #5
0
 def removeCert(certFile):
     certFile = certFile.replace("'", "")
     file = QFile(certFile)
     # set permission to allow removing on Win.
     # On linux and Mac if file is set with QFile::>ReadUser
     # does not create problem removing certs
     if not file.setPermissions(QFile.WriteOwner):
         raise Exception('Cannot change permissions on {}: error code: {}'.format(file.fileName(), file.error()))
     if not file.remove():
         raise Exception('Cannot remove {}: error code: {}'.format(file.fileName(), file.error()))
    def convert_metadata(self):
        """Method invoked when OK button is clicked."""
        # Converter parameter
        converter_parameter = {}
        # Target exposure
        if self.target_exposure_combo_box.isEnabled():
            exposure_index = self.target_exposure_combo_box.currentIndex()
            exposure_key = self.target_exposure_combo_box.itemData(
                exposure_index, Qt.UserRole)
            converter_parameter['exposure'] = exposure_key

        # Metadata
        current_metadata = self.keyword_io.read_keywords(self.layer)
        old_metadata = convert_metadata(
            current_metadata, **converter_parameter)

        # Input
        input_layer_path = self.layer.source()
        input_directory_path = os.path.dirname(input_layer_path)
        input_file_name = os.path.basename(input_layer_path)
        input_base_name = os.path.splitext(input_file_name)[0]
        input_extension = os.path.splitext(input_file_name)[1]

        # Output
        output_path = self.output_path_line_edit.text()
        output_directory_path = os.path.dirname(output_path)
        output_file_name = os.path.basename(output_path)
        output_base_name = os.path.splitext(output_file_name)[0]

        # Copy all related files, if exists
        extensions = [
            # Vector layer
            '.shp', '.geojson', '.qml', '.shx', '.dbf', '.prj', 'qpj',
            # Raster layer
            '.tif', '.tiff', '.asc',
        ]
        for extension in extensions:
            source_path = os.path.join(
                input_directory_path, input_base_name + extension)
            if not os.path.exists(source_path):
                continue
            target_path = os.path.join(
                output_directory_path, output_base_name + extension)
            QFile.copy(source_path, target_path)

        # Replace the metadata with the old one
        output_file_path = os.path.join(
            output_directory_path, output_base_name + input_extension
        )
        write_iso19115_metadata(
            output_file_path, old_metadata, version_35=True)
    def createSimpleMemorial(self):
        tempDoc = QDomDocument()
        simple = QFile(self.simpleMemorial)
        simple.open(QIODevice.ReadOnly)
        loaded = tempDoc.setContent(simple)
        simple.close()
        
        element = tempDoc.documentElement()
         
        nodes = element.elementsByTagName("table")
         
        table = nodes.item(0).toElement()

        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO", 7, 0))
        table.appendChild(tr)
        
        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2))
        tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0))
        tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2))
        tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0))
        tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0))
        table.appendChild(tr)
        
        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0))
        table.appendChild(tr)
         
        convergence = float(self.convergenciaEdit.text())
             
        rowCount = self.tableWidget.rowCount()
        
        for i in range(0,rowCount):
            lineElement = tempDoc.createElement("tr")
             
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,0).text(), 0, 0))
             
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,1).text(), 0, 0))
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,2).text(), 0, 0))
 
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,3).text(), 0, 0))
 
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,4).text(), 0, 0))
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,5).text(), 0, 0))
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,6).text(), 0, 0))
            
            table.appendChild(lineElement)
            
        simple = open(self.simpleMemorial, "w", encoding='utf-8')
        simple.write(tempDoc.toString())
        simple.close()
Beispiel #8
0
    def testQgsSvgMarkerSymbolLayer(self):
        """
        Create a new style from a .sld file and match test
        """
        mTestName = 'QgsSvgMarkerSymbolLayer'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' %
                                            (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsSvgMarkerSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSvgMarkerSymbolLayer(""))
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 'skull.svg'
        mValue = os.path.basename(mSymbolLayer.path())
        print(("VALUE", mSymbolLayer.path()))
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 12
        mValue = mSymbolLayer.size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 45
        mValue = mSymbolLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Beispiel #9
0
    def upload_files(self, layer, field_index, features):
        """
        Upload given features' source files to remote server and return a dict
        formatted as changeAttributeValues expects to update 'datos' attribute
        to a remote location.
        """
        if not QSettings().value(
                'Asistente-LADM_COL/sources/document_repository', False, bool):
            self.message_with_duration_emitted.emit(
                QCoreApplication.translate(
                    "SourceHandler",
                    "The source files were not uploaded to the document repository because you have that option unchecked. You can still upload the source files later using the 'Upload Pending Source Files' menu."
                ), Qgis.Info, 10)
            return dict()

        # Test if we have Internet connection and a valid service
        dlg = self.qgis_utils.get_settings_dialog()
        res, msg = dlg.is_source_service_valid()

        if not res:
            msg['text'] = QCoreApplication.translate(
                "SourceHandler",
                "No file could be uploaded to the document repository. You can do it later from the 'Upload Pending Source Files' menu. Reason: {}"
            ).format(msg['text'])
            self.message_with_duration_emitted.emit(
                msg['text'], Qgis.Info,
                20)  # The data is still saved, so always show Info msg
            return dict()

        file_features = [
            feature for feature in features if not feature[field_index] == NULL
            and os.path.isfile(feature[field_index])
        ]
        total = len(features)
        not_found = total - len(file_features)

        upload_dialog = UploadProgressDialog(len(file_features), not_found)
        upload_dialog.show()
        count = 0
        upload_errors = 0
        new_values = dict()

        for feature in file_features:
            data_url = feature[field_index]
            file_name = os.path.basename(data_url)

            nam = QNetworkAccessManager()
            #reply.downloadProgress.connect(upload_dialog.update_current_progress)

            multiPart = QHttpMultiPart(QHttpMultiPart.FormDataType)
            textPart = QHttpPart()
            textPart.setHeader(QNetworkRequest.ContentDispositionHeader,
                               QVariant("form-data; name=\"driver\""))
            textPart.setBody(QByteArray().append('Local'))

            filePart = QHttpPart()
            filePart.setHeader(
                QNetworkRequest.ContentDispositionHeader,
                QVariant("form-data; name=\"file\"; filename=\"{}\"".format(
                    file_name)))
            file = QFile(data_url)
            file.open(QIODevice.ReadOnly)

            filePart.setBodyDevice(file)
            file.setParent(
                multiPart
            )  # we cannot delete the file now, so delete it with the multiPart

            multiPart.append(filePart)
            multiPart.append(textPart)

            service_url = '/'.join([
                QSettings().value(
                    'Asistente-LADM_COL/sources/service_endpoint',
                    DEFAULT_ENDPOINT_SOURCE_SERVICE),
                SOURCE_SERVICE_UPLOAD_SUFFIX
            ])
            request = QNetworkRequest(QUrl(service_url))
            reply = nam.post(request, multiPart)
            #reply.uploadProgress.connect(upload_dialog.update_current_progress)
            reply.error.connect(self.error_returned)
            multiPart.setParent(reply)

            # We'll block execution until we get response from the server
            loop = QEventLoop()
            reply.finished.connect(loop.quit)
            loop.exec_()

            response = reply.readAll()
            data = QTextStream(response, QIODevice.ReadOnly)
            content = data.readAll()

            if content is None:
                self.log.logMessage(
                    "There was an error uploading file '{}'".format(data_url),
                    PLUGIN_NAME, Qgis.Critical)
                upload_errors += 1
                continue

            try:
                response = json.loads(content)
            except json.decoder.JSONDecodeError:
                self.log.logMessage(
                    "Couldn't parse JSON response from server for file '{}'!!!"
                    .format(data_url), PLUGIN_NAME, Qgis.Critical)
                upload_errors += 1
                continue

            if 'error' in response:
                self.log.logMessage(
                    "STATUS: {}. ERROR: {} MESSAGE: {} FILE: {}".format(
                        response['status'], response['error'],
                        response['message'], data_url), PLUGIN_NAME,
                    Qgis.Critical)
                upload_errors += 1
                continue

            reply.deleteLater()

            if 'url' not in response:
                self.log.logMessage(
                    "'url' attribute not found in JSON response for file '{}'!"
                    .format(data_url), PLUGIN_NAME, Qgis.Critical)
                upload_errors += 1
                continue

            url = self.get_file_url(response['url'])
            new_values[feature.id()] = {field_index: url}

            count += 1
            upload_dialog.update_total_progress(count)

        if not_found > 0:
            self.message_with_duration_emitted.emit(
                QCoreApplication.translate(
                    "SourceHandler",
                    "{} out of {} records {} not uploaded to the document repository because {} file path is NULL or it couldn't be found in the local disk!"
                ).format(
                    not_found, total,
                    QCoreApplication.translate("SourceHandler", "was")
                    if not_found == 1 else QCoreApplication.translate(
                        "SourceHandler", "were"),
                    QCoreApplication.translate("SourceHandler", "its")
                    if not_found == 1 else QCoreApplication.translate(
                        "SourceHandler", "their")), Qgis.Info, 0)
        if len(new_values):
            self.message_with_duration_emitted.emit(
                QCoreApplication.translate(
                    "SourceHandler",
                    "{} out of {} files {} uploaded to the document repository and {} remote location stored in the database!"
                ).format(
                    len(new_values), total,
                    QCoreApplication.translate("SourceHandler", "was")
                    if len(new_values) == 1 else QCoreApplication.translate(
                        "SourceHandler", "were"),
                    QCoreApplication.translate("SourceHandler", "its")
                    if len(new_values) == 1 else QCoreApplication.translate(
                        "SourceHandler", "their")), Qgis.Info, 0)
        if upload_errors:
            self.message_with_duration_emitted.emit(
                QCoreApplication.translate(
                    "SourceHandler",
                    "{} out of {} files could not be uploaded to the document repository because of upload errors! See log for details."
                ).format(upload_errors, total), Qgis.Info, 0)

        return new_values
Beispiel #10
0
    def installFromZipFile(self):
        settings = QSettings()
        lastDirectory = settings.value(
            '/Qgis/plugin-installer/lastZipDirectory', '.')
        filePath, _ = QFileDialog.getOpenFileName(
            iface.mainWindow(), self.tr('Open file'), lastDirectory,
            self.tr('Plugin packages (*.zip *.ZIP)'))
        if filePath == '':
            return

        settings.setValue('/Qgis/plugin-installer/lastZipDirectory',
                          QFileInfo(filePath).absoluteDir().absolutePath())

        error = False
        infoString = None

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

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

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

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

        try:
            # Test extraction. If fails, then exception will be raised
            # and no removing occurs
            unzip(str(filePath), str(pluginsDirectory))
            # Removing old plugin files if exist
            removeDir(
                QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName)))
            # Extract new files
            unzip(str(filePath), str(pluginsDirectory))
        except:
            error = True
            infoString = (
                self.tr("Plugin installation failed"),
                self.
                tr("Failed to unzip the plugin package\n{}.\nProbably it is broken"
                   .format(zipFilePath)))

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

            if settings.contains('/PythonPlugins/' + pluginName):
                if settings.value('/PythonPlugins/' + pluginName, False, bool):
                    startPlugin(pluginName)
                    reloadPlugin(pluginName)
                else:
                    unloadPlugin(pluginName)
                    loadPlugin(pluginName)
            else:
                if startPlugin(pluginName):
                    settings.setValue('/PythonPlugins/' + pluginName, True)
            infoString = (self.tr("Plugin installed successfully"), "")

        if infoString[0]:
            level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO
            msg = "<b>%s:</b>%s" % (infoString[0], infoString[1])
            iface.messageBar().pushMessage(msg, level)
Beispiel #11
0
class InstanceUUIDExtractor():
    """
    Class constructor
    """

    def __init__(self, path):
        """
        Initatlize class variables
        """
        self.file_path = path
        self.file = None
        self.new_list = []
        self.doc = QDomDocument()
        self.node = QDomNode()

    def set_file_path(self, path):
        """
        Update the path based on the new file being read
        :param path:
        :return:
        """
        self.file_path = path

    def unset_path(self):
        """Clear the current document path"""
        self.file_path = None

    def set_document(self):
        """
        :return:
        """
        self.file = QFile(self.file_path)
        if self.file.open(QIODevice.ReadOnly):
            self.doc.setContent(self.file)
        self.file.close()

    def update_document(self):
        '''Update the current instance by clearing the document in the cache '''
        self.doc.clear()
        self.set_document()

    def on_file_passed(self):
        """
        Pass the raw file to an xml document object and format the its filename to GeoODK standards
        :return:
        """
        try:
            self.set_document()
            self.read_uuid_element()
            self.doc.clear()
            self.file.close()
            self.rename_file()
        except:
            pass

    def read_uuid_element(self):
        """
        get the uuid element and text from the xml document from the mobile divice
        """
        node = self.doc.elementsByTagName("meta")
        for i in range(node.count()):
            node = node.item(i).firstChild().toElement()
            self.node = node.text()
        return self.node

    def document_entities(self, profile):
        """
        Get entities in the document
        :return:
        """
        self.set_document()
        node_list = []
        nodes = self.doc.elementsByTagName(profile)
        node = nodes.item(0).childNodes()
        if node:
            for j in range(node.count()):
                node_val = node.item(j)
                node_list.append(node_val.nodeName())
        return node_list

    def profile_entity_nodes(self, profile):
        '''
        Fetch and return QDomNodeList for entities of a
        profile
        :rtype: QDomNodeList
        '''
        self.set_document()
        nodes = self.doc.elementsByTagName(profile)
        return nodes.item(0).childNodes()

    def document_entities_with_data(self, profile, selected_entities):
        """
        Get entities in the dom document matching user
        selected entities
        :rtype: OrderedDict
        """

        instance_data = OrderedDict()
        self.set_document()
        nodes = self.doc.elementsByTagName(profile)
        entity_nodes = nodes.item(0).childNodes()
        for attrs in range(entity_nodes.count()):
            if entity_nodes.item(attrs).nodeName() in selected_entities:
                name_entity = entity_nodes.item(attrs).nodeName()
                attr_nodes = self.doc.elementsByTagName(name_entity)
                instance_data[attr_nodes] = name_entity
        return instance_data

    def attribute_data_from_nodelist(self, args_list):
        """
        process nodelist data before Importing  attribute data into db
        """
        repeat_instance_data = OrderedDict()
        attribute_data = OrderedDict()
        for attr_nodes, entity in args_list.items():
            '''The assuption is that there are repeated entities from mobile sub forms. handle them separately'''
            if attr_nodes.count() > 1:
                for i in range(attr_nodes.count()):
                    attrib_node = attr_nodes.at(i).childNodes()
                    attr_list = OrderedDict()
                    for j in range(attrib_node.count()):
                        field_name = attrib_node.at(j).nodeName()
                        field_value = attrib_node.at(j).toElement().text()
                        attr_list[field_name] = field_value
                    repeat_instance_data['{}'.format(i) + entity] = attr_list
            else:
                '''Entities must appear onces in the form'''
                node_list_var = OrderedDict()
                attr_node = attr_nodes.at(0).childNodes()
                for j in range(attr_node.count()):
                    field_name = attr_node.at(j).nodeName()
                    field_value = attr_node.at(j).toElement().text()
                    node_list_var[field_name] = field_value
                attribute_data[entity] = node_list_var
        return attribute_data, repeat_instance_data

    def read_attribute_data_from_node(self, node, entity_name):
        """Read attribute data from a node item"""
        node_list_var = OrderedDict()
        attributes = OrderedDict()
        attr_node = node.at(0).childNodes()
        for j in range(attr_node.count()):
            field_name = attr_node.at(j).nodeName()
            field_value = attr_node.at(j).toElement().text()
            node_list_var[field_name] = field_value
        attributes[entity_name] = node_list_var
        return attributes

    def str_definition(self, instance=None):
        """
        Check if the instance file has entry social tenure
        :return:
        """
        if instance:
            self.set_file_path(instance)
            self.set_document()
        attributes = {}
        nodes = self.doc.elementsByTagName('social_tenure')
        entity_nodes = nodes.item(0).childNodes()
        if entity_nodes:
            for j in range(entity_nodes.count()):
                node_val = entity_nodes.item(j).toElement()
                attributes[node_val.nodeName()] = node_val.text().rstrip()
        return attributes

    def has_str_captured_in_instance(self, instance):
        """
        Bool if the str inclusion is required based on whether is captured or not
        :return:
        """
        count = len(self.str_definition(instance))
        return True if count > 1 else False

    def entity_atrributes(self):
        """
        Get collected data from the entity in the document
        :return:
        """
        pass

    def uuid_element(self):
        """
        Format the guuid from the file
        :return:
        """
        return self.node.replace(":", "")

    def rename_file(self):
        """
        Remane the existing instance file with Guuid from the mobile divice to conform with GeoODk naming
        convention
        :return:
        """
        if isinstance(self.file, QFile):
            dir_n, file_n = os.path.split(self.file_path)
            os.chdir(dir_n)
            if not file_n.startswith(UUID):
                new_file_name = self.uuid_element() + ".xml"
                isrenamed = self.file.setFileName(new_file_name)
                os.rename(file_n, new_file_name)
                self.new_list.append(new_file_name)
                return isrenamed
            else:
                self.new_list.append(self.file.fileName())
            self.file.close()
        else:
            return

    def file_list(self):
        """
        check through the list of document to ensure they are complete file path
        """
        complete_file = []
        for fi in self.new_list:
            if os.path.isfile(fi):
                complete_file.append(fi)
            else:
                continue
        return complete_file

    def close_document(self):
        '''Close all the open documents and unset current paths'''
        self.file_path = None
        self.doc.clear()
        self.new_list = None
Beispiel #12
0
    def imprimirPlanol(self, x, y, escala, rotacion, midaPagina, templateFile,
                       fitxerSortida, tipusSortida):
        tInicial = time.time()

        template = QFile(templateFile)
        doc = QDomDocument()
        doc.setContent(template, False)

        layout = QgsLayout(self.project)
        # page=QgsLayoutItemPage(layout)
        # page.setPageSize(midaPagina)
        # layout.pageCollection().addPage(page)

        # layout.initializeDefaults()
        # p=layout.pageCollection().pages()[0]
        # p.setPageSize(midaPagina)

        context = QgsReadWriteContext()
        [items, ok] = layout.loadFromTemplate(doc, context)
        # p=layout.pageCollection().pages()[0]
        # p.setPageSize(midaPagina)

        if ok:
            refMap = layout.referenceMap()

            titol = layout.itemById('idNomMapa')
            dataMapa = layout.itemById('idData')
            if self.leTitol.text() != '':
                titol.setText(self.leTitol.text())  #comentat pk peta
            else:
                titol.setText('')
            try:
                t = time.localtime()
                dataMapa.setText(strftime('%b-%d-%Y %H:%M', t))
            except:
                pass

            rect = refMap.extent()
            vector = QgsVector(x - rect.center().x(), y - rect.center().y())
            rect += vector
            refMap.setExtent(rect)
            refMap.setScale(escala)
            refMap.setMapRotation(rotacion)
            #Depenent del tipus de sortida...

            exporter = QgsLayoutExporter(layout)
            # image_settings = exporter.ImageExportSettings()
            # image_settings.dpi = 30

            # result = exporter.exportToImage('d:/dropbox/qpic/preview.png',  image_settings)
            # imatge = QPixmap('d:/dropbox/qpic/preview.png')
            # self.ui.lblImatgeResultat.setPixmap(imatge)

            if tipusSortida == 'PDF':
                settings = QgsLayoutExporter.PdfExportSettings()
                settings.dpi = 300
                settings.exportMetadata = False

                # fitxerSortida='d:/sortida_'+timestamp+'.PDF'
                fitxerSortida += '.PDF'
                result = exporter.exportToPdf(
                    fitxerSortida, settings)  #Cal desar el resultat (???)

                print(fitxerSortida)

            if tipusSortida == 'PNG':
                settings = QgsLayoutExporter.ImageExportSettings()
                settings.dpi = 300

                # fitxerSortida='d:/sortida_'+timestamp+'.PNG'
                fitxerSortida += '.PNG'
                result = exporter.exportToImage(
                    fitxerSortida, settings)  #Cal desar el resultat (???)

            #Obra el document si està marcat checkObrirResultat
            QDesktopServices().openUrl(QUrl(fitxerSortida))

            segonsEmprats = round(time.time() - tInicial, 1)  #???
            layersTemporals = self.project.mapLayersByName(
                "Capa temporal d'impressió")

            estatDirtybit = self.parent.canvisPendents
            for layer in layersTemporals:
                self.project.removeMapLayer(layer.id())
            self.parent.setDirtyBit(estatDirtybit)
    def requestFinished(self):
        reply = self.sender()
        self.buttonBox.setEnabled(False)
        if reply.error() != QNetworkReply.NoError:
            self.mResult = reply.errorString()
            if reply.error() == QNetworkReply.OperationCanceledError:
                self.mResult += "<br/><br/>" + QCoreApplication.translate(
                    "QgsPluginInstaller",
                    "If you haven't canceled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options."
                )
            self.reject()
            reply.deleteLater()
            return
        elif reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 301:
            redirectionUrl = reply.attribute(
                QNetworkRequest.RedirectionTargetAttribute)
            self.redirectionCounter += 1
            if self.redirectionCounter > 4:
                self.mResult = QCoreApplication.translate(
                    "QgsPluginInstaller", "Too many redirections")
                self.reject()
                reply.deleteLater()
                return
            else:
                if redirectionUrl.isRelative():
                    redirectionUrl = reply.url().resolved(redirectionUrl)
                # Fire a new request and exit immediately in order to quietly destroy the old one
                self.url = redirectionUrl
                self.requestDownloading()
                reply.deleteLater()
                return

        self.file.open(QFile.WriteOnly)
        self.file.write(reply.readAll())
        self.file.close()
        self.stateChanged(0)
        reply.deleteLater()
        pluginDir = qgis.utils.home_plugin_path
        tmpPath = self.file.fileName()
        # make sure that the parent directory exists
        if not QDir(pluginDir).exists():
            QDir().mkpath(pluginDir)
        # if the target directory already exists as a link, remove the link without resolving:
        QFile(pluginDir + str(QDir.separator()) + self.plugin["id"]).remove()
        try:
            unzip(
                str(tmpPath), str(pluginDir)
            )  # test extract. If fails, then exception will be raised and no removing occurs
            # removing old plugin files if exist
            removeDir(QDir.cleanPath(
                pluginDir + "/" +
                self.plugin["id"]))  # remove old plugin if exists
            unzip(str(tmpPath), str(pluginDir))  # final extract.
        except:
            self.mResult = self.tr(
                "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:"
            ) + "\n" + pluginDir
            self.reject()
            return
        try:
            # cleaning: removing the temporary zip file
            QFile(tmpPath).remove()
        except:
            pass
        self.close()
Beispiel #14
0
class XFORMDocument:
    """
    class to generate an Xml file that is needed for data collection
    using mobile device. The class creates the file and QDOM sections
    for holding data once the file is called
    """
    def __init__(self, fname):
        """
        Initalize the class so that we have a new file
        everytime document generation method is called
        """
        self.dt_text = QDate()
        self.file_handler = FilePaths()
        self.doc = QDomDocument()
        self.form = None
        self.fname = fname
        self.doc_with_entities = []
        self.supports_doc = self.document()

    def document(self):
        """
        use the globally defined Document name for supporting document
        :return:
        """
        global DOCUMENT
        return DOCUMENT

    def form_name(self):
        """
        Format the name for the new file to be created. We need to ensure it is
        .xml file.
        :return:
        """
        if len(self.fname.split(".")) > 1:
            return self.fname
        else:
            return self.fname + "{}".format(DOCEXTENSION)

    def set_form_name(self, local_name):
        """
        Allow the user to update the name of the file. This method
        will be called to return a new file with the local_name given
        :param local_name: string
        :return: QFile
        """
        self.fname = local_name + "{}".format(DOCEXTENSION)
        self.form.setFileName(self.fname)
        self.create_form()

        return self.fname

    def create_form(self):
        """
        Create an XML file that will be our XFORM Document for reading and writing
        We want a new file when everytime we are creating XForm
        type: file
        :return: file
        """
        self.form = QFile(os.path.join(FORM_HOME, self.form_name()))
        if not QFileInfo(self.form).suffix() == DOCEXTENSION:
            self.form_name()

        if not self.form.open(QIODevice.ReadWrite | QIODevice.Truncate
                              | QIODevice.Text):
            return self.form.OpenError

    def create_node(self, name):
        """
        Create a XML element node
        :param name:
        :return: node
        :rtype: QelementNode
        """
        return self.doc.createElement(name)

    def create_text_node(self, text):
        """
        Create an XML text node
        :param text:
        :return:
        """
        return self.doc.createTextNode(text)

    def create_node_attribute(self, node, key, value):
        """
        Create an attribute and attach it to the node
        :param node: Qnode
        :param key: Qnode name
        :param value: Qnode value
        :return: QNode
        """
        return node.setAttribute(key, value)

    def xform_document(self):
        """
        :return: QDomDocument
        """
        return self.doc

    def write_to_form(self):
        """
        Write data to xml file from the base calling class to an output file created earlier
        :return:
        """
        if isinstance(self.form, QFile):
            self.form.write(self.doc.toByteArray())
            self.form.close()
            self.doc.clear()
        else:
            return None

    def update_form_data(self):
        """
        Update the xml file with changes that the user has made.
        Particular section of the document will be deleted or added
        :return:
        """
        pass
Beispiel #15
0
    def createSimpleMemorial(self):
        tempDoc = QDomDocument()
        simple = QFile(self.simpleMemorial)
        simple.open(QIODevice.ReadOnly)
        loaded = tempDoc.setContent(simple)
        simple.close()

        element = tempDoc.documentElement()

        nodes = element.elementsByTagName("table")

        table = nodes.item(0).toElement()

        tr = tempDoc.createElement("tr")
        tr.appendChild(
            self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO",
                                   7, 0))
        table.appendChild(tr)

        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2))
        tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0))
        tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2))
        tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0))
        tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0))
        table.appendChild(tr)

        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0))
        table.appendChild(tr)

        convergence = float(self.convergenciaEdit.text())

        rowCount = self.tableWidget.rowCount()

        for i in range(0, rowCount):
            lineElement = tempDoc.createElement("tr")

            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 0).text(), 0,
                                       0))

            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 1).text(), 0,
                                       0))
            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 2).text(), 0,
                                       0))

            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 3).text(), 0,
                                       0))

            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 4).text(), 0,
                                       0))
            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 5).text(), 0,
                                       0))
            lineElement.appendChild(
                self.createCellElement(tempDoc,
                                       self.tableWidget.item(i, 6).text(), 0,
                                       0))

            table.appendChild(lineElement)

        simple = open(self.simpleMemorial, "w", encoding='utf-8')
        simple.write(tempDoc.toString())
        simple.close()
    def installFromZipFile(self, filePath):
        if not os.path.isfile(filePath):
            return

        settings = QgsSettings()
        settings.setValue(settingsGroup + '/lastZipDirectory',
                          QFileInfo(filePath).absoluteDir().absolutePath())

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

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

        if not pluginName:
            msg_box = QMessageBox()
            msg_box.setIcon(QMessageBox.Warning)
            msg_box.setWindowTitle(self.tr("QGIS Python Install from ZIP Plugin Installer"))
            msg_box.setText(self.tr("The Zip file is not a valid QGIS python plugin. No root folder was found inside."))
            msg_box.setStandardButtons(QMessageBox.Ok)
            more_info_btn = msg_box.addButton(self.tr("More Information"), QMessageBox.HelpRole)
            msg_box.exec()
            if msg_box.clickedButton() == more_info_btn:
                QgsHelp.openHelp("plugins/plugins.html#the-install-from-zip-tab")
            return

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

        pluginDirectory = QDir.cleanPath(os.path.join(pluginsDirectory, pluginName))

        # If the target directory already exists as a link,
        # remove the link without resolving
        QFile(pluginDirectory).remove()

        password = None
        infoString = None
        success = False
        keepTrying = True

        while keepTrying:
            try:
                # Test extraction. If fails, then exception will be raised and no removing occurs
                unzip(filePath, pluginsDirectory, password)
                # Removing old plugin files if exist
                removeDir(pluginDirectory)
                # Extract new files
                unzip(filePath, pluginsDirectory, password)
                keepTrying = False
                success = True
            except Exception as e:
                success = False
                if 'password' in str(e):
                    infoString = self.tr('Aborted by user')
                    if 'Bad password' in str(e):
                        msg = self.tr('Wrong password. Please enter a correct password to the zip file.')
                    else:
                        msg = self.tr('The zip file is encrypted. Please enter password.')
                    # Display a password dialog with QgsPasswordLineEdit
                    dlg = QDialog()
                    dlg.setWindowTitle(self.tr('Enter password'))
                    buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal)
                    buttonBox.rejected.connect(dlg.reject)
                    buttonBox.accepted.connect(dlg.accept)
                    lePass = QgsPasswordLineEdit()
                    layout = QVBoxLayout()
                    layout.addWidget(QLabel(msg))
                    layout.addWidget(lePass)
                    layout.addWidget(buttonBox)
                    dlg.setLayout(layout)
                    keepTrying = dlg.exec_()
                    password = lePass.text()
                else:
                    infoString = self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(filePath))
                    keepTrying = False

        if success:
            updateAvailablePlugins()
            self.processDependencies(pluginName)
            loadPlugin(pluginName)
            plugins.getAllInstalled()
            plugins.rebuild()

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

            self.exportPluginsToManager()
            msg = "<b>%s</b>" % self.tr("Plugin installed successfully")
        else:
            msg = "<b>%s:</b> %s" % (self.tr("Plugin installation failed"), infoString)

        level = Qgis.Info if success else Qgis.Critical
        iface.pluginManagerInterface().pushMessage(msg, level)
    def sendOutputFile(self, handler):
        format_dict = WFSFormats[self.format]

        # read the GML
        gml_path = join(self.tempdir, '{}.gml'.format(self.filename))
        output_layer = QgsVectorLayer(gml_path, 'qgis_server_wfs_features',
                                      'ogr')

        # Temporary file where to write the output
        temporary = QTemporaryFile(
            join(QDir.tempPath(),
                 'request-WFS-XXXXXX.{}'.format(format_dict['filenameExt'])))
        temporary.open()
        output_file = temporary.fileName()
        temporary.close()

        if output_layer.isValid():
            try:
                # create save options
                options = QgsVectorFileWriter.SaveVectorOptions()
                # driver name
                options.driverName = format_dict['ogrProvider']
                # file encoding
                options.fileEncoding = 'utf-8'

                # coordinate transformation
                if format_dict['forceCRS']:
                    options.ct = QgsCoordinateTransform(
                        output_layer.crs(),
                        QgsCoordinateReferenceSystem(format_dict['forceCRS']),
                        QgsProject.instance())

                # datasource options
                if format_dict['ogrDatasourceOptions']:
                    options.datasourceOptions = format_dict[
                        'ogrDatasourceOptions']

                # write file
                if Qgis.QGIS_VERSION_INT >= 31003:
                    write_result, error_message = QgsVectorFileWriter.writeAsVectorFormatV2(
                        output_layer, output_file,
                        QgsProject.instance().transformContext(), options)
                else:
                    write_result, error_message = QgsVectorFileWriter.writeAsVectorFormat(
                        output_layer, output_file, options)

                if write_result != QgsVectorFileWriter.NoError:
                    handler.appendBody(b'')
                    self.logger.critical(error_message)
                    return False

            except Exception as e:
                handler.appendBody(b'')
                self.logger.critical(str(e))
                return False

            if format_dict['zip']:
                # compress files
                import zipfile
                # noinspection PyBroadException
                try:
                    import zlib  # NOQA
                    compression = zipfile.ZIP_DEFLATED
                except Exception:
                    compression = zipfile.ZIP_STORED

                # create the zip file
                zip_file_path = join(self.tempdir, '%s.zip' % self.filename)
                with zipfile.ZipFile(zip_file_path, 'w') as zf:
                    # add all files
                    zf.write(join(
                        self.tempdir,
                        '%s.%s' % (self.filename, format_dict['filenameExt'])),
                             compress_type=compression,
                             arcname='%s.%s' %
                             (self.typename, format_dict['filenameExt']))

                    for e in format_dict['extToZip']:
                        file_path = join(self.tempdir,
                                         '%s.%s' % (self.filename, e))
                        if exists(file_path):
                            zf.write(file_path,
                                     compress_type=compression,
                                     arcname='%s.%s' % (self.typename, e))

                    zf.close()

                f = QFile(zip_file_path)
                if f.open(QFile.ReadOnly):
                    ba = f.readAll()
                    handler.appendBody(ba)
                    return True

            else:
                # return the file created without zip
                f = QFile(output_file)
                if f.open(QFile.ReadOnly):
                    ba = f.readAll()
                    handler.appendBody(ba)
                    return True

        handler.appendBody(b'')
        self.logger.critical('Error no output file')
        return False
Beispiel #18
0
    def loadTemplate(self, filePath):
        """
        Loads a document template into the view and updates the necessary STDM-related composer items.
        """
        if not QFile.exists(filePath):
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("OpenTemplateConfig",
                                       "Open Template Error"),
                QApplication.translate(
                    "OpenTemplateConfig",
                    "The specified template does not exist."))
            return

        copy_file = filePath.replace('sdt', 'cpy')

        # remove existing copy file
        if QFile.exists(copy_file):
            copy_template = QFile(copy_file)
            copy_template.remove()

        orig_template_file = QFile(filePath)

        self.setDocumentFile(orig_template_file)

        # make a copy of the original
        result = orig_template_file.copy(copy_file)

        #templateFile = QFile(filePath)

        # work with copy
        templateFile = QFile(copy_file)

        self.copy_template_file = templateFile

        if not templateFile.open(QIODevice.ReadOnly):
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper",
                                       "Open Operation Error"),
                "{0}\n{1}".format(
                    QApplication.translate("ComposerWrapper",
                                           "Cannot read template file."),
                    templateFile.errorString()))
            return

        templateDoc = QDomDocument()

        if templateDoc.setContent(templateFile):
            table_config_collection = TableConfigurationCollection.create(
                templateDoc)
            '''
            First load vector layers for the table definitions in the config
            collection before loading the composition from file.
            '''
            load_table_layers(table_config_collection)

            self.clearWidgetMappings()

            #Load items into the composition and configure STDM data controls
            self.composition().loadFromTemplate(templateDoc)

            #Load data controls
            composerDS = ComposerDataSource.create(templateDoc)

            #Set title by appending template name
            title = QApplication.translate("STDMPlugin",
                                           "STDM Document Designer")

            composer_el = templateDoc.documentElement()
            if not composer_el is None:
                template_name = ""
                if composer_el.hasAttribute("title"):
                    template_name = composer_el.attribute("title", "")
                elif composer_el.hasAttribute("_title"):
                    template_name = composer_el.attribute("_title", "")

                if template_name:
                    win_title = "{0} - {1}".format(title, template_name)
                    self.mainWindow().setWindowTitle(template_name)

            self._configure_data_controls(composerDS)

            #Load symbol editors
            spatialFieldsConfig = SpatialFieldsConfiguration.create(
                templateDoc)
            self._configureSpatialSymbolEditor(spatialFieldsConfig)

            #Load photo editors
            photo_config_collection = PhotoConfigurationCollection.create(
                templateDoc)
            self._configure_photo_editors(photo_config_collection)

            # Load table editors
            self._configure_table_editors(table_config_collection)

            #Load chart property editors
            chart_config_collection = ChartConfigurationCollection.create(
                templateDoc)
            self._configure_chart_editors(chart_config_collection)

            # Load QR code property editors
            qrc_config_collection = QRCodeConfigurationCollection.create(
                templateDoc)
            self._configure_qr_code_editors(qrc_config_collection)

            self._sync_ids_with_uuids()
Beispiel #19
0
    def sendOutputFile(self, handler):
        formatDict = WFSFormats[self.format]
        # read the GML
        outputLayer = QgsVectorLayer(
            os.path.join(self.tempdir, '%s.gml' % self.filename),
            'qgis_server_wfs_features', 'ogr')
        if outputLayer.isValid():
            try:
                # create save options
                options = QgsVectorFileWriter.SaveVectorOptions()
                # driver name
                options.driverName = formatDict['ogrProvider']
                # file encoding
                options.fileEncoding = 'utf-8'
                # coordinate transformation
                if formatDict['forceCRS']:
                    options.ct = QgsCoordinateTransform(
                        outputLayer.crs(),
                        QgsCoordinateReferenceSystem(formatDict['forceCRS']),
                        QgsProject.instance())
                # datasource options
                if formatDict['ogrDatasourceOptions']:
                    options.datasourceOptions = formatDict[
                        'ogrDatasourceOptions']

                # write file
                write_result, error_message = QgsVectorFileWriter.writeAsVectorFormat(
                    outputLayer,
                    os.path.join(
                        self.tempdir,
                        '%s.%s' % (self.filename, formatDict['filenameExt'])),
                    options)
                if write_result != QgsVectorFileWriter.NoError:
                    handler.appendBody(b'')
                    QgsMessageLog.logMessage(error_message,
                                             "wfsOutputExtension",
                                             Qgis.Critical)
                    return False
            except Exception as e:
                handler.appendBody(b'')
                QgsMessageLog.logMessage(str(e), "wfsOutputExtension",
                                         Qgis.Critical)
                return False

            if formatDict['zip']:
                # compress files
                import zipfile
                try:
                    import zlib
                    compression = zipfile.ZIP_DEFLATED
                except:
                    compression = zipfile.ZIP_STORED
                # create the zip file
                with zipfile.ZipFile(
                        os.path.join(self.tempdir, '%s.zip' % self.filename),
                        'w') as zf:
                    # add all files
                    zf.write(os.path.join(
                        self.tempdir,
                        '%s.%s' % (self.filename, formatDict['filenameExt'])),
                             compress_type=compression,
                             arcname='%s.%s' %
                             (self.typename, formatDict['filenameExt']))
                    for e in formatDict['extToZip']:
                        if os.path.exists(
                                os.path.join(self.tempdir,
                                             '%s.%s' % (self.filename, e))):
                            zf.write(os.path.join(self.tempdir, '%s.%s' %
                                                  (self.filename, e)),
                                     compress_type=compression,
                                     arcname='%s.%s' % (self.typename, e))
                    zf.close()
                f = QFile(os.path.join(self.tempdir, '%s.zip' % self.filename))
                if (f.open(QFile.ReadOnly)):
                    ba = f.readAll()
                    handler.appendBody(ba)
                    return True
            else:
                # return the file created without zip
                f = QFile(
                    os.path.join(
                        self.tempdir,
                        '%s.%s' % (self.filename, formatDict['filenameExt'])))
                if (f.open(QFile.ReadOnly)):
                    ba = f.readAll()
                    handler.appendBody(ba)
                    return True

        handler.appendBody(b'')
        QgsMessageLog.logMessage('Error no output file', "wfsOutputExtension",
                                 Qgis.Critical)
        return False
Beispiel #20
0
 def signature_downloaded(filename):
     if not QFile.copy(filename, destination):
         self.show_error(
             'Error writing to file [{0}]. Check that the file does not exist already.'
             .format(destination))
Beispiel #21
0
    def download(self):
        """Downloading the file.

        :returns: True if success, otherwise returns a tuple with format like
            this (QNetworkReply.NetworkError, error_message)

        :raises: IOError - when cannot create output_path
        """
        # Prepare output path
        self.output_file = QFile(self.output_path)
        if not self.output_file.open(QFile.WriteOnly):
            raise IOError(self.output_file.errorString())

        # Prepare downloaded buffer
        self.downloaded_file_buffer = QByteArray()

        # Request the url
        request = QNetworkRequest(self.url)
        self.reply = self.manager.get(request)
        self.reply.readyRead.connect(self.get_buffer)
        self.reply.finished.connect(self.write_data)
        self.manager.requestTimedOut.connect(self.request_timeout)

        if self.progress_dialog:
            # progress bar
            def progress_event(received, total):
                """Update progress.

                :param received: Data received so far.
                :type received: int

                :param total: Total expected data.
                :type total: int
                """
                # noinspection PyArgumentList
                QgsApplication.processEvents()

                self.progress_dialog.adjustSize()

                human_received = humanize_file_size(received)
                human_total = humanize_file_size(total)

                label_text = tr(
                    "%s : %s of %s" %
                    (self.prefix_text, human_received, human_total))

                self.progress_dialog.setLabelText(label_text)
                self.progress_dialog.setMaximum(total)
                self.progress_dialog.setValue(received)

            # cancel
            def cancel_action():
                """Cancel download."""
                self.reply.abort()
                self.reply.deleteLater()

            self.reply.downloadProgress.connect(progress_event)
            self.progress_dialog.canceled.connect(cancel_action)

        # Wait until finished
        # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
        # returns False even after finished slot is called. So, that's why we
        # are adding self.finished_flag (see #864)
        while not self.reply.isFinished() and not self.finished_flag:
            # noinspection PyArgumentList
            QgsApplication.processEvents()

        result = self.reply.error()
        try:
            http_code = int(
                self.reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
        except TypeError:
            # If the user cancels the request, the HTTP response will be None.
            http_code = None

        self.reply.abort()
        self.reply.deleteLater()

        if result == QNetworkReply.NoError:
            return True, None

        elif result == QNetworkReply.UnknownNetworkError:
            return False, tr(
                'The network is unreachable. Please check your internet '
                'connection.')

        elif http_code == 408:
            msg = tr('Sorry, the server aborted your request. '
                     'Please try a smaller area.')
            LOGGER.debug(msg)
            return False, msg

        elif http_code == 509:
            msg = tr(
                'Sorry, the server is currently busy with another request. '
                'Please try again in a few minutes.')
            LOGGER.debug(msg)
            return False, msg

        elif result == QNetworkReply.ProtocolUnknownError or \
                result == QNetworkReply.HostNotFoundError:
            # See http://doc.qt.io/qt-5/qurl-obsolete.html#encodedHost
            encoded_host = self.url.toAce(self.url.host())
            LOGGER.exception('Host not found : %s' % encoded_host)
            return False, tr(
                'Sorry, the server is unreachable. Please try again later.')

        elif result == QNetworkReply.ContentNotFoundError:
            LOGGER.exception('Path not found : %s' % self.url.path())
            return False, tr('Sorry, the layer was not found on the server.')

        else:
            return result, self.reply.errorString()
Beispiel #22
0
    def installFromZipFile(self, filePath):
        if not os.path.isfile(filePath):
            return

        settings = QgsSettings()
        settings.setValue(settingsGroup + '/lastZipDirectory',
                          QFileInfo(filePath).absoluteDir().absolutePath())

        error = False
        infoString = None

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

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

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

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

        try:
            # Test extraction. If fails, then exception will be raised
            # and no removing occurs
            unzip(str(filePath), str(pluginsDirectory))
            # Removing old plugin files if exist
            removeDir(
                QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName)))
            # Extract new files
            unzip(str(filePath), str(pluginsDirectory))
        except:
            error = True
            infoString = (
                self.tr("Plugin installation failed"),
                self.
                tr("Failed to unzip the plugin package\n{}.\nProbably it is broken"
                   .format(filePath)))

        if infoString is None:
            updateAvailablePlugins()
            loadPlugin(pluginName)
            plugins.getAllInstalled()
            plugins.rebuild()
            self.exportPluginsToManager()

            if settings.contains('/PythonPlugins/' + pluginName):
                if settings.value('/PythonPlugins/' + pluginName, False, bool):
                    startPlugin(pluginName)
                    reloadPlugin(pluginName)
                else:
                    unloadPlugin(pluginName)
                    loadPlugin(pluginName)
            else:
                if startPlugin(pluginName):
                    settings.setValue('/PythonPlugins/' + pluginName, True)
            infoString = (self.tr("Plugin installed successfully"), "")

        if infoString[0]:
            level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO
            msg = "<b>%s</b>" % infoString[0]
            if infoString[1]:
                msg += "<b>:</b> %s" % infoString[1]
            iface.pluginManagerInterface().pushMessage(msg, level)
Beispiel #23
0
    def referencing_column_value(self, field_values):
        """
        Uploads documents based on the file name specified in the source
        column.
        :param field_values: Pair of field names and corresponding values i.e.
        {field1:value1, field2:value2, field3:value3...}
        :type field_values: dict
        :return: Ignore type since te source document manager will handle the
        supporting document uploads.
        :rtype: IgnoreType
        """
        if self.source_document_manager is None or self.entity is None:
            return IgnoreType

        if self.document_type_id is None:
            msg = QApplication.translate(
                'SourceDocumentTranslator',
                'Document type has not been set for the source document '
                'translator.')
            raise RuntimeError(msg)

        if self.source_directory is None:
            msg = QApplication.translate(
                'SourceDocumentTranslator',
                'Source directory for {0} has not been set.'.format(
                    self.document_type))
            raise RuntimeError(msg)

        source_dir = QDir()
        if not source_dir.exists(self.source_directory):
            msg = QApplication.translate(
                'SourceDocumentTranslator',
                'Source directory for {0} does not exist.'.format(
                    self.document_type))
            raise IOError(msg)

        if len(field_values) == 0:
            return IgnoreType

        source_column = list(field_values.keys())[0]

        # Check if the source column is in the field_values
        if not source_column in field_values:
            return IgnoreType

        # Get file name
        doc_file_name = field_values.get(source_column)

        if not doc_file_name:
            return IgnoreType

        # Separate files
        docs = doc_file_name.split(';')

        # Create document container
        doc_container = QVBoxLayout()

        # Register container
        self.source_document_manager.registerContainer(doc_container,
                                                       self.document_type_id)

        for d in docs:
            if not d:
                continue

            # Normalize slashes
            d_name = d.replace('\\', '/').strip()

            # Build absolute document path
            abs_doc_path = '{0}/{1}'.format(self.source_directory, d_name)

            if not QFile.exists(abs_doc_path):
                msg = QApplication.translate(
                    'SourceDocumentTranslator',
                    'Supporting document {0} does not exist.'.format(
                        abs_doc_path))

                raise IOError(msg)

            # Upload supporting document
            self.source_document_manager.insertDocumentFromFile(
                abs_doc_path, self.document_type_id, self.entity)

        # Move file to 'uploaded' directory

        # Documents are handles by the source document manager so we just
        # instruct the system to ignore the return value
        return IgnoreType
Beispiel #24
0
    def load_viewer(self, document_widget, visible=True):
        """
        Open a new instance of the viewer or activate an existing one if the
        document had been previously loaded.
        :param document_widget: Contains all the necessary information required
        to load the specific document.
        :type document_widget: DocumentWidget
        :param visible: True to show the view manager after the viewer has
        been loaded, otherwise it will be the responsibility of the caller to
        enable visibility.
        :type visible: bool
        :returns: True if the document was successfully loaded, else False.
        :rtype: bool
        """
        doc_identifier = document_widget.file_identifier()

        if doc_identifier in self._doc_viewers:

            doc_sw = self._doc_viewers[doc_identifier]

            self._mdi_area.setActiveSubWindow(doc_sw)
            doc_sw.showNormal()

        else:
            abs_doc_path = self.absolute_document_path(document_widget)

            if not QFile.exists(abs_doc_path):
                msg = QApplication.translate(
                    "DocumentViewManager",
                    "The selected document does not exist."
                    "\nPlease check the supporting documents' "
                    "repository setting.")
                QMessageBox.critical(
                    self,
                    QApplication.translate("DocumentViewManager",
                                           "Invalid Document"), msg)

                return False

            file_info = QFileInfo(abs_doc_path)
            ext = file_info.suffix().lower()
            if ext == 'pdf':
                os.startfile(abs_doc_path)
                return True

            doc_viewer = self._create_viewer(document_widget)

            doc_viewer.load_document(abs_doc_path)

            self._doc_viewers[doc_identifier] = doc_viewer

            self._mdi_area.addSubWindow(doc_viewer)

            doc_viewer.show()

        if not self.isVisible() and visible:
            self.setVisible(True)

        if self.isMinimized():
            self.showNormal()

        self.center()

        return True
Beispiel #25
0
    def accept(self):
        project_name = self.project_name_le.text()
        if project_name.endswith('.qgs'):
            project_name = project_name[:-4]
        if not project_name:
            QMessageBox.critical(self, self.tr("OQ-Consolidate: Error"),
                                 self.tr("Please specify the project name"))
            return

        outputDir = self.leOutputDir.text()
        if not outputDir:
            QMessageBox.critical(
                self, self.tr("OQ-Consolidate: Error"),
                self.tr("Please specify the output directory."))
            return
        outputDir = os.path.join(outputDir, get_valid_filename(project_name))

        # create main directory if not exists
        d = QDir(outputDir)
        if not d.exists():
            if not d.mkpath("."):
                QMessageBox.critical(
                    self, self.tr("OQ-Consolidate: Error"),
                    self.tr("Can't create directory to store the project."))
                return

        # create directory for layers if not exists
        if d.exists("layers"):
            res = QMessageBox.question(
                self, self.tr("Directory exists"),
                self.tr("Output directory already contains 'layers'"
                        " subdirectory. Maybe this directory was used to"
                        " consolidate another project. Continue?"),
                QMessageBox.Yes | QMessageBox.No)
            if res == QMessageBox.No:
                return
        else:
            if not d.mkdir("layers"):
                QMessageBox.critical(
                    self, self.tr("OQ-Consolidate: Error"),
                    self.tr("Can't create directory for layers."))
                return

        # copy project file
        projectFile = QgsProject.instance().fileName()
        if projectFile:
            f = QFile(projectFile)
            newProjectFile = os.path.join(outputDir, '%s.qgs' % project_name)
            f.copy(newProjectFile)
        else:
            newProjectFile = os.path.join(outputDir, '%s.qgs' % project_name)
            f = QFileInfo(newProjectFile)
            p = QgsProject.instance()
            p.write(f)

        # start consolidate thread that does all real work
        self.workThread = consolidatethread.ConsolidateThread(
            self.iface, outputDir, newProjectFile,
            self.checkBoxZip.isChecked())
        self.workThread.rangeChanged.connect(self.setProgressRange)
        self.workThread.updateProgress.connect(self.updateProgress)
        self.workThread.processFinished.connect(self.processFinished)
        self.workThread.processInterrupted.connect(self.processInterrupted)
        self.workThread.processError.connect(self.processError)
        self.workThread.exceptionOccurred.connect(self.exceptionOccurred)

        self.btnClose.setText(self.tr("Cancel"))
        self.btnOk.setEnabled(False)
        self.buttonBox.rejected.disconnect(self.reject)
        self.btnClose.clicked.connect(self.stopProcessing)

        self.workThread.start()
Beispiel #26
0
    def load_template_into_layout(layout: QgsLayout, file_path: str):
        """
        Loads a document template into the view and updates the necessary STDM-related composer items.
        """
        copy_file = file_path.replace('sdt', 'cpy')

        # remove existing copy file
        if QFile.exists(copy_file):
            copy_template = QFile(copy_file)
            copy_template.remove()

        orig_template_file = QFile(file_path)

        layout.setCustomProperty('variable_template_path', file_path)

        # make a copy of the original
        orig_template_file.copy(copy_file)

        # work with copy
        template_file = QFile(copy_file)

        if not template_file.open(QIODevice.ReadOnly):
            raise IOError(template_file.errorString())

        template_doc = QDomDocument()
        if template_doc.setContent(template_file):
            # First load vector layers for the table definitions in the config
            # collection before loading the composition from file.

            #  table_config_collection = TableConfigurationCollection.create(template_doc)

            # Load items into the composition and configure STDM data controls
            context = QgsReadWriteContext()
            try:
                layout.loadFromTemplate(template_doc, context)
            except:
                pass

            LayoutUtils.sync_ids_with_uuids(layout)

        template_file.close()
Beispiel #27
0
                    cfg["Value"] = "value_fr"
                    layer.editFormConfig().setWidgetConfig(idx, cfg)
            # value maps
            if layer.editFormConfig().widgetType(idx) == 'ValueMap':
                cfg = layer.editFormConfig().widgetConfig(idx)
                for key in cfg.keys():
                    trans = get_table_translation(cur, cfg[key])
                    if trans:
                        cfg[trans] = cfg[key]
                        del cfg[key]
                layer.editFormConfig().setWidgetConfig(idx, cfg)

# update styles from other project
if 'style_file' in config_data:
    errMsg = ''
    file = QFile(config_data['style_file'])
    file.open(QFile.ReadOnly | QFile.Text)
    doc = QDomDocument()
    doc.setContent(file)
    root = doc.elementsByTagName('qgis.custom.style')
    nodes = root.at(0).childNodes()
    for i in range(0, nodes.count()):
        elem = nodes.at(i).toElement()
        if elem.tagName() != 'layer' or not elem.hasAttribute('id'):
            continue
        layer_id = elem.attribute('id')
        if layer_id not in style_layer_ids:
            print('skipping ', layer_id)
        layer = QgsProject.instance().mapLayer(layer_id)
        if not layer:
            print('layer not found', layer_id)
 def cleanTempPki():
     pkies = glob.glob(os.path.join(tempfile.gettempdir(), 'tmp*_{*}.pem'))
     for fn in pkies:
         f = QFile(fn)
         f.setPermissions(QFile.WriteOwner)
         f.remove()
 def _download_file(self, url, out_path):
     reply = self.__sync_request(url)
     local_file = QFile(out_path)
     local_file.open(QIODevice.WriteOnly)
     local_file.write(reply)
     local_file.close()
Beispiel #30
0
 def read_cached_dfd_qlr(self):
     #return file(unicode(self.cached_kf_qlr_filename)).read()
     f = QFile(self.cached_dfd_qlr_filename)
     f.open(QIODevice.ReadOnly)
     return f.readAll()
Beispiel #31
0
    def getInstalledPlugin(self, key, path, readOnly):
        """ get the metadata of an installed plugin """
        def metadataParser(fct):
            """ plugin metadata parser reimplemented from qgis.utils
                for better control on wchich module is examined
                in case there is an installed plugin masking a core one """
            global errorDetails
            cp = configparser.ConfigParser()
            try:
                with codecs.open(metadataFile, "r", "utf8") as f:
                    cp.read_file(f)
                return cp.get('general', fct)
            except Exception as e:
                if not errorDetails:
                    errorDetails = e.args[0]  # set to the first problem
                return ""

        def pluginMetadata(fct):
            """ calls metadataParser for current l10n.
                If failed, fallbacks to the standard metadata """
            locale = QLocale.system().name()
            if locale and fct in translatableAttributes:
                value = metadataParser("{}[{}]".format(fct, locale))
                if value:
                    return value
                value = metadataParser("{}[{}]".format(fct,
                                                       locale.split("_")[0]))
                if value:
                    return value
            return metadataParser(fct)

        if not QDir(path).exists():
            return

        global errorDetails  # to communicate with the metadataParser fn
        plugin = dict()
        error = ""
        errorDetails = ""
        version = None

        if not os.path.exists(os.path.join(path, '__init__.py')):
            error = "broken"
            errorDetails = QCoreApplication.translate("QgsPluginInstaller",
                                                      "Missing __init__.py")

        metadataFile = os.path.join(path, 'metadata.txt')
        if os.path.exists(metadataFile):
            version = normalizeVersion(pluginMetadata("version"))

        if version:
            qgisMinimumVersion = pluginMetadata("qgisMinimumVersion").strip()
            if not qgisMinimumVersion:
                qgisMinimumVersion = "0"
            qgisMaximumVersion = pluginMetadata("qgisMaximumVersion").strip()
            if not qgisMaximumVersion:
                qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
            # if compatible, add the plugin to the list
            if not isCompatible(pyQgisVersion(), qgisMinimumVersion,
                                qgisMaximumVersion):
                error = "incompatible"
                errorDetails = "{} - {}".format(qgisMinimumVersion,
                                                qgisMaximumVersion)
        elif not os.path.exists(metadataFile):
            error = "broken"
            errorDetails = QCoreApplication.translate("QgsPluginInstaller",
                                                      "Missing metadata file")
        else:
            error = "broken"
            e = errorDetails
            errorDetails = QCoreApplication.translate(
                "QgsPluginInstaller", u"Error reading metadata")
            if e:
                errorDetails += ": " + e

        if not version:
            version = "?"

        if error[:16] == "No module named ":
            mona = error.replace("No module named ", "")
            if mona != key:
                error = "dependent"
                errorDetails = mona

        icon = pluginMetadata("icon")
        if QFileInfo(icon).isRelative():
            icon = path + "/" + icon

        changelog = pluginMetadata("changelog")
        changelogFile = os.path.join(path, "CHANGELOG")
        if not changelog and QFile(changelogFile).exists():
            with open(changelogFile) as f:
                changelog = f.read()

        plugin = {
            "id":
            key,
            "plugin_id":
            None,
            "name":
            pluginMetadata("name") or key,
            "description":
            pluginMetadata("description"),
            "about":
            pluginMetadata("about"),
            "icon":
            icon,
            "category":
            pluginMetadata("category"),
            "tags":
            pluginMetadata("tags"),
            "changelog":
            changelog,
            "author_name":
            pluginMetadata("author_name") or pluginMetadata("author"),
            "author_email":
            pluginMetadata("email"),
            "homepage":
            pluginMetadata("homepage"),
            "tracker":
            pluginMetadata("tracker"),
            "code_repository":
            pluginMetadata("repository"),
            "version_installed":
            version,
            "library":
            path,
            "pythonic":
            True,
            "experimental":
            pluginMetadata("experimental").strip().upper() in ["TRUE", "YES"],
            "deprecated":
            pluginMetadata("deprecated").strip().upper() in ["TRUE", "YES"],
            "trusted":
            False,
            "version_available":
            "",
            "zip_repository":
            "",
            "download_url":
            path,  # warning: local path as url!
            "filename":
            "",
            "downloads":
            "",
            "average_vote":
            "",
            "rating_votes":
            "",
            "available":
            False,  # Will be overwritten, if any available version found.
            "installed":
            True,
            "status":
            "orphan",  # Will be overwritten, if any available version found.
            "error":
            error,
            "error_details":
            errorDetails,
            "readonly":
            readOnly
        }
        return plugin
Beispiel #32
0
class QgsPluginInstallerInstallingDialog(
        QDialog, Ui_QgsPluginInstallerInstallingDialogBase):
    # ----------------------------------------- #

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

        url = QUrl(plugin["download_url"])

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

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

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

            self.stateChanged(4)

    def exec_(self):
        if self.request is None:
            return QDialog.Rejected

        QDialog.exec_(self)

    # ----------------------------------------- #
    def result(self):
        return self.mResult

    # ----------------------------------------- #
    def stateChanged(self, state):
        messages = [
            self.tr("Installing..."),
            self.tr("Resolving host name..."),
            self.tr("Connecting..."),
            self.tr("Host connected. Sending request..."),
            self.tr("Downloading data..."),
            self.tr("Idle"),
            self.tr("Closing connection..."),
            self.tr("Error")
        ]
        self.labelState.setText(messages[state])

    # ----------------------------------------- #
    def readProgress(self, done, total):
        if total > 0:
            self.progressBar.setMaximum(total)
            self.progressBar.setValue(done)

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

    # ----------------------------------------- #
    def abort(self):
        if self.reply.isRunning():
            self.reply.finished.disconnect()
            self.reply.abort()
            del self.reply
        self.mResult = self.tr("Aborted by user")
        self.reject()
Beispiel #33
0
def foreign_key_parent_tables(table_name, search_parent=True, filter_exp=None):
    """
    Function that searches for foreign key references in the specified table.
    :param table_name: Name of the database table.
    :type table_name: str
    :param search_parent: Select True if table_name is the child and
    parent tables are to be retrieved, else child tables will be
    returned.
    :type search_parent: bool
    :param filter_exp: A regex expression to filter related table names.
    :type filter_exp: QRegExp
    :return: A list of tuples containing the local column name, foreign table
    name, corresponding foreign column name and constraint name.
    :rtype: list
    """
    # Check if the view for listing foreign key references exists
    fk_ref_view = pg_table_exists("foreign_key_references")

    # Create if it does not exist
    if not fk_ref_view:
        script_path = PLUGIN_DIR + "/scripts/foreign_key_references.sql"

        script_file = QFile(script_path)
        if script_file.exists():
            if not script_file.open(QIODevice.ReadOnly):
                return None

            reader = QTextStream(script_file)
            sql = reader.readAll()
            if sql:
                t = text(sql)
                _execute(t)

        else:
            return None

    if search_parent:
        ref_table = "foreign_table_name"
        search_table = "table_name"
    else:
        ref_table = "table_name"
        search_table = "foreign_table_name"

    # Fetch foreign key references
    sql = "SELECT column_name,{0},foreign_column_name, constraint_name FROM " \
          "foreign_key_references where {1} =:tb_name".format(ref_table,
                                                               search_table)

    t = text(sql)
    result = _execute(t, tb_name=table_name)

    fk_refs = []

    for r in result:
        rel_table = r[ref_table]

        fk_ref = r["column_name"], rel_table, \
                 r["foreign_column_name"], r["constraint_name"]

        if not filter_exp is None:
            if filter_exp.indexIn(rel_table) >= 0:
                fk_refs.append(fk_ref)

                continue

        fk_refs.append(fk_ref)

    return fk_refs
Beispiel #34
0
    def saveTemplate(self):
        """
        Creates and saves a new document template.
        """
        # Validate if the user has specified the data source

        if not LayoutUtils.get_stdm_data_source_for_layout(self.composition()):
            QMessageBox.critical(
                self.mainWindow(),
                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 LayoutUtils.get_stdm_referenced_table_for_layout(
                self.composition()):
            QMessageBox.critical(
                self.mainWindow(),
                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.
        #template_path = self.composition().customProperty('variable_template_path', None)
        template_path = self.variable_template_path

        if template_path is None:
            docName, ok = QInputDialog.getText(
                self.mainWindow(),
                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.mainWindow(),
                    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.mainWindow(),
                        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.mainWindow(),
                        QApplication.translate("ComposerWrapper",
                                               "Existing Template"),
                        "'{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:
                        return
                    else:
                        # Delete the existing template
                        delFile = QFile(absPath)
                        remove_status = delFile.remove()
                        if not remove_status:
                            QMessageBox.critical(
                                self.mainWindow(),
                                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

                docFile = QFile(absPath)
                template_path = absPath
        else:
            docFile = QFile(template_path)

            # else:
            # return

        docFileInfo = QFileInfo(docFile)

        if not docFile.open(QIODevice.WriteOnly):
            QMessageBox.critical(
                self.mainWindow(),
                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 DummyException as exc:
            msg = str(exc)
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper", "Save Error"), msg)
            docFile.close()
            docFile.remove()

            return

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

            return

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

        self.composition().setCustomProperty('variable_template_path',
                                             template_path)

        docFile.close()
Beispiel #35
0
class MultipartFile(QFile):
    """Wrapper class to support reading a file in chunks and post each part separately."""
    def __init__(self, filename):
        super().__init__(filename)
        self._file = QFile(filename)
        self._bytes_left = 0
        self._file.readyRead.connect(self.on_readyRead)
        self._file.aboutToClose.connect(self.on_aboutToClose)
        self._file.bytesWritten.connect(self.on_bytesWritten)
        self._file.channelBytesWritten.connect(self.on_channelBytesWritten)
        self._file.channelReadyRead.connect(self.on_channelReadyRead)
        self._file.readChannelFinished.connect(self.on_readChannelFinished)

    def set_part_size(self, size):
        self._bytes_left = size
        self._original_size = size

    def commitTransaction(self):
        QgsMessageLog.logMessage('commitTransaction')
        return self._file.commitTransaction()

    def currentReadChannel(self):
        QgsMessageLog.logMessage('currentReadChannel')
        return self._file.currentReadChannel()

    def currentWriteChannel(self):
        QgsMessageLog.logMessage('currentWriteChannel')
        return self._file.currentWriteChannel()

    def errorString(self):
        QgsMessageLog.logMessage('errorString')
        return self._file.errorString()
    
    def getChar(self):
        if self._bytes_left > 0:
            QgsMessageLog.logMessage('getChar')
            self._bytes_left = self._bytes_left - 1
            return self._file.getChar()
        else:
            QgsMessageLog.logMessage('getChar(no bytes left)')
            return None

    def isOpen(self):
        QgsMessageLog.logMessage('isOpen')
        return self._file.isOpen()

    def isReadable(self):
        QgsMessageLog.logMessage('isReadable')
        return self._file.isReadable()

    def isTextModeEnabled(self):
        QgsMessageLog.logMessage('isTextModeEnabled')
        return self._file.isTextModeEnabled()

    def isTransactionStarted(self):
        QgsMessageLog.logMessage('isTransactionStarted')
        return self._file.isTransactionStarted()

    def isWritable(self):
        QgsMessageLog.logMessage('isWritable')
        return self._file.isWritable()

    def openMode(self):
        QgsMessageLog.logMessage('openMode')
        return self._file.openMode()

    def peek(self, maxlen):
        QgsMessageLog.logMessage('peek {0} {1}'.format(maxlen, self._bytes_left))
        if maxlen > self._bytes_left:
            maxlen = self._bytes_left
        return self._file.peek(maxlen)

    def read(self, max_size):
        QgsMessageLog.logMessage('read {0}'.format(max_size))
        return self._file.read(max_size)

    def readAll(self):
        QgsMessageLog.logMessage('readAll')
        data = self._file.read(self._bytes_left)
        self._bytes_left = self._bytes_left - len(data)
        return data

    def readChannelCount(self):
        QgsMessageLog.logMessage('readChannelCount')
        return self._file.readChannelCount()

    def readLine(self):
        QgsMessageLog.logMessage('readLine')
        return None

    def rollbackTransaction(self):
        QgsMessageLog.logMessage('rollbackTransaction')
        return self._file.rollbackTransaction()

    def setCurrentReadChannel(self, channel):
        QgsMessageLog.logMessage('setCurrentReadChannel {0}'.format(channel))
        return self._file.setCurrentReadChannel(channel)

    def setErrorString(self, errorString):
        QgsMessageLog.logMessage('setErrorString {0}'.format(errorString))
        return self._file.setErrorString(errorString)

    def setOpenMode(self, mode):
        QgsMessageLog.logMessage('setOpenMode {0}'.format(mode))
        return self._file.setOpenMode(mode)

    def setTextModeEnabled(self, enabled):
        QgsMessageLog.logMessage('setTextModeEnabled {0}'.format(enabled))
        return self._file.setTextModeenabled(enabled)

    def skip(self, maxSize):
        QgsMessageLog.logMessage('skip {0} {1}'.format(maxSize, self._bytes_left))
        if maxSize > self._bytes_left:
            maxSize = self._bytes_left
        return self._file.skip(maxSize)

    def startTransaction(self):
        QgsMessageLog.logMessage('startTransaction')
        return self._file.startTransaction()

    def ungetChar(self, c):
        QgsMessageLog.logMessage('ungetChar {0}'.format(c))
        return None

    def writeChannelCount(self):
        QgsMessageLog.logMessage('writeChannelCount')
        return self._file.writeChannelCount()

    def atEnd(self):
        QgsMessageLog.logMessage('atEnd')
        if self._bytes_left == 0:
            return True
        else:
            return self._file.atEnd()

    def bytesAvailable(self):
        QgsMessageLog.logMessage('bytesAvailable')
        real_bytes_available = self._file.bytesAvailable()
        if real_bytes_available > self._bytes_left:
            return self._bytes_left
        else:
            return real_bytes_available

    def bytesToWrite(self):
        QgsMessageLog.logMessage('bytesToWrite')
        return self._file.bytesToWrite()

    def canReadLine(self):
        QgsMessageLog.logMessage('canReadLine')
        return self._file.canReadLine()

    def close(self):
        QgsMessageLog.logMessage('close')
        return self._file.close()

    def isSequential(self):
        QgsMessageLog.logMessage('isSequential')
        return self._file.isSequential()

    def open(self, mode):
        QgsMessageLog.logMessage('open')
        return self._file.open(mode)

    def pos(self):
        QgsMessageLog.logMessage('pos')
        return self._original_size - self._bytes_left

    def readData(self, max_size):
        if max_size > self._bytes_left:
            max_size = self._bytes_left
        self._bytes_left = self._bytes_left - max_size
        if self._bytes_left == 0:
            self.readChannelFinished.emit()
        QgsMessageLog.logMessage('readData {0}'.format(max_size))
        return self._file.readData(max_size)

    def reset(self):
        QgsMessageLog.logMessage('readData')
        return True

    def seek(self, pos):
        QgsMessageLog.logMessage('seek {0}'.format(pos))
        return True

    def size(self):
        file_size = self._file.size()
        if file_size < self._bytes_left:
            QgsMessageLog.logMessage('size(file_size) {0}'.format(file_size))
            return file_size
        else:
            QgsMessageLog.logMessage('size(bytes_left) {0}'.format(self._bytes_left))
            return self._bytes_left
    
    def waitForReadyRead(self, msecs):
        QgsMessageLog.logMessage('waitForReadyRead {0}'.format(msecs))
        return self._file.waitForReadyRead(msecs)

    def on_aboutToClose(self):
        QgsMessageLog.logMessage('on_aboutToClose')
        self.aboutToClose.emit()
    
    def on_bytesWritten(self, bytes_written):
        QgsMessageLog.logMessage('on_bytesWritten {0}'.format(bytes_written))
        self.bytesWritten.emit(bytes_written)

    def on_channelBytesWritten(self, channel, bytes_written):
        QgsMessageLog.logMessage('on_channelBytesWritten {0} {1}'.format(channel, bytes_written))
        self.channelBytesWritten.emit(channel, bytes_written)
    
    def on_channelReadyRead(self, channel):
        QgsMessageLog.logMessage('on_channelReadyRead {0}'.format(channel))
        if self._bytes_left > 0:
            self.channelReadyRead.emit(channel)

    def on_readChannelFinished(self):
        QgsMessageLog.logMessage('on_readChannelFinished')
        self.readChannelFinished.emit()

    def on_readyRead(self):
        QgsMessageLog.logMessage('on_readyRead')
        if self._bytes_left > 0:
            self.readyRead.emit()

    def flush(self):
        QgsMessageLog.logMessage('flush')
        return self._file.flush()

    def fileName(self):
        QgsMessageLog.logMessage('filename')
        return self._file.fileName()

    def exists(self):
        QgsMessageLog.logMessage('exists')
        return self._file.exists()

    def decodeName(self, localFileName):
        QgsMessageLog.logMessage('decodeName {0}'.format(localFileName))
        return self._file.decodeName(localFileName)
Beispiel #36
0
    def testStatistics(self):
        """Test zonal stats"""
        TEST_DATA_DIR = unitTestDataPath() + "/zonalstatistics/"
        myTempPath = QDir.tempPath() + "/"
        testDir = QDir(TEST_DATA_DIR)
        for f in testDir.entryList(QDir.Files):
            QFile.remove(myTempPath + f)
            QFile.copy(TEST_DATA_DIR + f, myTempPath + f)

        myVector = QgsVectorLayer(myTempPath + "polys.shp", "poly", "ogr")
        myRaster = QgsRasterLayer(myTempPath + "edge_problem.asc", "raster",
                                  "gdal")
        zs = QgsZonalStatistics(myVector, myRaster, "", 1,
                                QgsZonalStatistics.All)
        zs.calculateStatistics(None)

        feat = QgsFeature()
        # validate statistics for each feature
        request = QgsFeatureRequest().setFilterFid(0)
        feat = next(myVector.getFeatures(request))
        myMessage = ('Expected: %f\nGot: %f\n' % (12.0, feat[1]))
        assert feat[1] == 12.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (8.0, feat[2]))
        assert feat[2] == 8.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.666666666666667, feat[3]))
        assert abs(feat[3] - 0.666666666666667) < 0.00001, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[4]))
        assert feat[4] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' %
                     (0.47140452079103201, feat[5]))
        assert abs(feat[5] - 0.47140452079103201) < 0.00001, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[6]))
        assert feat[6] == 0.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[7]))
        assert feat[7] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[8]))
        assert feat[8] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[9]))
        assert feat[9] == 0.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[10]))
        assert feat[10] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (2.0, feat[11]))
        assert feat[11] == 2.0, myMessage

        request.setFilterFid(1)
        feat = next(myVector.getFeatures(request))
        myMessage = ('Expected: %f\nGot: %f\n' % (9.0, feat[1]))
        assert feat[1] == 9.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2]))
        assert feat[2] == 5.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.555555555555556, feat[3]))
        assert abs(feat[3] - 0.555555555555556) < 0.00001, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[4]))
        assert feat[4] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' %
                     (0.49690399499995302, feat[5]))
        assert abs(feat[5] - 0.49690399499995302) < 0.00001, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[6]))
        assert feat[6] == 0.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[7]))
        assert feat[7] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[8]))
        assert feat[8] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[9]))
        assert feat[9] == 0.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[10]))
        assert feat[10] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (2.0, feat[11]))
        assert feat[11] == 2.0, myMessage

        request.setFilterFid(2)
        feat = next(myVector.getFeatures(request))
        myMessage = ('Expected: %f\nGot: %f\n' % (6.0, feat[1]))
        assert feat[1] == 6.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2]))
        assert feat[2] == 5.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.833333333333333, feat[3]))
        assert abs(feat[3] - 0.833333333333333) < 0.00001, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[4]))
        assert feat[4] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.372677996249965, feat[5]))
        assert abs(feat[5] - 0.372677996249965) < 0.00001, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[6]))
        assert feat[6] == 0.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[7]))
        assert feat[7] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[8]))
        assert feat[8] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[9]))
        assert feat[9] == 0.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[10]))
        assert feat[10] == 1.0, myMessage
        myMessage = ('Expected: %f\nGot: %f\n' % (2.0, feat[11]))
        assert feat[11] == 2.0, myMessage
Beispiel #37
0
 def read_local_qlr(self):
     f = QFile(self.local_qlr_filename)
     f.open(QIODevice.ReadOnly)
     return f.readAll()