示例#1
0
def get_layer_symbology(layer):
    doc = QDomDocument(QDomImplementation().createDocumentType(
        "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM"))
    rootNode = doc.createElement("qgis")
    doc.appendChild(rootNode)
    errorMsg = ""
    ctx = QgsReadWriteContext()
    layer.writeSymbology(rootNode, doc, errorMsg, ctx)
    return doc.toByteArray()
示例#2
0
    def _editTemplate(self, templatePath, newName):
        """
        Updates the template document to use the new name.
        """
        templateFile = QFile(templatePath)

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

        templateDoc = QDomDocument()

        if templateDoc.setContent(templateFile):
            composerElement = templateDoc.documentElement()
            titleAttr = composerElement.attributeNode("_title")
            if not titleAttr.isNull():
                titleAttr.setValue(newName)

            # Try remove file
            status = templateFile.remove()

            if not status:
                return (False, "")

            # Create new file
            newTemplatePath = self._composerTemplatesPath(
            ) + "/" + newName + ".sdt"
            newTemplateFile = QFile(newTemplatePath)

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

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

            newTemplateFile.close()

            return (True, newTemplatePath)
示例#3
0
    def formatResponse(self) -> (QByteArray, str):
        doc = QDomDocument()
        root = doc.createElement('ServiceExceptionReport')
        root.setAttribute('version', self.version)
        root.setAttribute('xmlns', 'http://www.opengis.net/ogc')
        doc.appendChild(root)

        elem = doc.createElement('ServiceException')
        elem.setAttribute('code', self.code)
        elem.appendChild(doc.createTextNode(self.message))
        root.appendChild(elem)

        if self.locator:
            elem.setAttribute('locator', self.locator)

        return doc.toByteArray(), 'text/xml; charset=utf-8'
    def getCachedDocument(self, project, request, key):
        m = hashlib.md5()
        paramMap = request.parameters()
        urlParam = "&".join(["%s=%s" % (k, paramMap[k]) for k in paramMap.keys()])
        m.update(urlParam.encode('utf8'))

        if not os.path.exists(os.path.join(self._cache_dir, m.hexdigest() + ".xml")):
            return QByteArray()

        doc = QDomDocument(m.hexdigest() + ".xml")
        with open(os.path.join(self._cache_dir, m.hexdigest() + ".xml"), "r") as f:
            statusOK, errorStr, errorLine, errorColumn = doc.setContent(f.read(), True)
            if not statusOK:
                print("Could not read or find the contents document. Error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr))
                return QByteArray()

        return doc.toByteArray()
    def getCachedDocument(self, project, request, key):
        m = hashlib.md5()
        paramMap = request.parameters()
        urlParam = "&".join(["%s=%s" % (k, paramMap[k]) for k in paramMap.keys()])
        m.update(urlParam.encode('utf8'))

        if not os.path.exists(os.path.join(self._cache_dir, m.hexdigest() + ".xml")):
            return QByteArray()

        doc = QDomDocument(m.hexdigest() + ".xml")
        with open(os.path.join(self._cache_dir, m.hexdigest() + ".xml"), "r") as f:
            statusOK, errorStr, errorLine, errorColumn = doc.setContent(f.read(), True)
            if not statusOK:
                print("Could not read or find the contents document. Error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr))
                return QByteArray()

        return doc.toByteArray()
示例#6
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()
示例#7
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
示例#8
0
    def adjust(self):
        """ Export data to GNU Gama xml, adjust the network and read result

            :returns: result list of adjusment from GNU Gama
        """
        # fix = 0 free network
        fix = 0
        adj = 0
        for p, s in self.points:
            if s == 'FIX':
                fix += 1
            else:
                adj += 1
        if adj == 0 or len(self.observations) == 0:
            # no unknowns or observations
            return None

        doc = QDomDocument()
        doc.appendChild(
            doc.createComment(
                'Gama XML created by SurveyingCalculation plugin for QGIS'))
        gama_local = doc.createElement('gama-local')
        gama_local.setAttribute('version', '2.0')
        doc.appendChild(gama_local)
        network = doc.createElement('network')
        network.setAttribute('axes-xy', 'ne')
        network.setAttribute('angles', 'left-handed')
        gama_local.appendChild(network)
        description = doc.createElement('description')
        if self.dimension == 1:
            description.appendChild(doc.createTextNode('GNU Gama 1D network'))
        elif self.dimension == 2:
            description.appendChild(doc.createTextNode('GNU Gama 2D network'))
        elif self.dimension == 3:
            description.appendChild(doc.createTextNode('GNU Gama 3D network'))
        network.appendChild(description)
        parameters = doc.createElement('parameters')
        parameters.setAttribute('sigma-apr', '1')
        parameters.setAttribute('conf-pr', str(self.probability))
        parameters.setAttribute('tol-abs', '1000')
        parameters.setAttribute('sigma-act', 'aposteriori')
        parameters.setAttribute('update-constrained-coordinates', 'yes')
        network.appendChild(parameters)
        points_observations = doc.createElement('points-observations')
        points_observations.setAttribute(
            'distance-stdev',
            str(self.stdev_dist) + ' ' + str(self.stdev_dist1))
        points_observations.setAttribute('direction-stdev',
                                         str(self.stdev_angle))
        points_observations.setAttribute('angle-stdev',
                                         str(math.sqrt(self.stdev_angle * 2)))
        points_observations.setAttribute('zenith-angle-stdev',
                                         str(self.stdev_angle))
        network.appendChild(points_observations)
        for p, s in self.points:
            if self.dimension == 1:
                tmp = doc.createElement('point')
                tmp.setAttribute('id', p.id)
                if p.z is not None:
                    tmp.setAttribute('z', str(p.z))
                if s == 'FIX':
                    tmp.setAttribute('fix', 'z')
                else:
                    if fix == 0:
                        tmp.setAttribute('adj', 'Z')
                    else:
                        tmp.setAttribute('adj', 'z')
                points_observations.appendChild(tmp)
            elif self.dimension == 2:
                tmp = doc.createElement('point')
                tmp.setAttribute('id', p.id)
                if p.e is not None and p.n is not None:
                    tmp.setAttribute('y', str(p.e))
                    tmp.setAttribute('x', str(p.n))
                if s == 'FIX':
                    tmp.setAttribute('fix', 'xy')
                else:
                    if fix == 0:
                        # free network
                        tmp.setAttribute('adj', 'XY')
                    else:
                        tmp.setAttribute('adj', 'xy')
                points_observations.appendChild(tmp)
            elif self.dimension == 3:
                tmp = doc.createElement('point')
                tmp.setAttribute('id', p.id)
                if p.e is not None and p.n is not None:
                    tmp.setAttribute('y', str(p.e))
                    tmp.setAttribute('x', str(p.n))
                if p.z is not None:
                    tmp.setAttribute('z', str(p.z))
                if s == 'FIX':
                    tmp.setAttribute('fix', 'xyz')
                else:
                    if fix == 0:
                        tmp.setAttribute('adj', 'XYZ')
                    else:
                        tmp.setAttribute('adj', 'xyz')
                points_observations.appendChild(tmp)
        if self.dimension == 1:
            hd = doc.createElement('height-differences')
            points_observations.appendChild(hd)
        for o in self.observations:
            if o.station == 'station':
                # station record
                st_id = o.point_id
                if o.th is None:
                    ih = 0
                else:
                    ih = o.th
                if self.dimension in [2, 3]:
                    sta = doc.createElement('obs')
                    sta.setAttribute('from', o.point_id)
                    points_observations.appendChild(sta)
            else:
                # observation
                if self.dimension == 2:
                    # horizontal network
                    if o.hz is not None:
                        tmp = doc.createElement('direction')
                        tmp.setAttribute('to', o.point_id)
                        tmp.setAttribute('val', str(o.hz.get_angle('GON')))
                        sta.appendChild(tmp)
                    if o.d is not None:
                        # horizontal distance
                        hd = o.horiz_dist()
                        if hd is not None:
                            tmp = doc.createElement('distance')
                            tmp.setAttribute('to', o.point_id)
                            tmp.setAttribute('val', str(hd))
                            sta.appendChild(tmp)
                elif self.dimension == 1:
                    # elevations only 1d
                    if o.th is None:
                        th = 0
                    else:
                        th = o.th
                    if o.d is not None and o.v is not None:
                        tmp = doc.createElement('dh')
                        tmp.setAttribute('from', st_id)
                        tmp.setAttribute('to', o.point_id)
                        # TODO hibaterjedes
                        tmp.setAttribute('stdev', '1')
                        sz = math.sin(o.v.get_angle())
                        w = self.stdev_dist + self.stdev_dist1 * o.d.d / 1000
                        ro_cc = 200 * 100 * 100 / math.pi
                        if o.d.mode == 'SD':
                            cz = math.cos(o.v.get_angle())
                            tmp.setAttribute('val', str(o.d.d * cz + ih - th))
                            tmp.setAttribute(
                                'stdev',
                                str(
                                    math.sqrt(cz**2 * w**2 +
                                              (o.d.d * 1000)**2 * sz**2 *
                                              (self.stdev_angle / RO_CC)**2)))
                        else:
                            tz = math.tan(o.v.get_angle())
                            tmp.setAttribute(
                                'val',
                                str(o.d.d / math.tan(o.v.get_angle()) + ih -
                                    th))
                            tmp.setAttribute(
                                'stdev',
                                str(
                                    math.sqrt((1 / tz)**2 * w**2 +
                                              (o.d.d * 1000)**2 *
                                              (o.d.d * 1000)**2 *
                                              (1 / sz**2)**2 *
                                              (self.stdev_angle / RO_CC)**2)))
                        hd.appendChild(tmp)
                elif self.dimension == 3:
                    # 3d
                    if o.th is None:
                        th = 0
                    else:
                        th = o.th
                    if o.hz is not None:
                        tmp = doc.createElement('direction')
                        tmp.setAttribute('to', o.point_id)
                        tmp.setAttribute('val', str(o.hz.get_angle('GON')))
                        sta.appendChild(tmp)
                    if o.d is not None:
                        if o.d.mode == 'SD':
                            tmp = doc.createElement('s-distance')
                            tmp.setAttribute('val', str(o.d.d))
                            tmp.setAttribute('from_dh', str(ih))
                            tmp.setAttribute('to_dh', str(th))
                        else:
                            tmp = doc.createElement('distance')
                            tmp.setAttribute('val', str(o.d.d))
                        tmp.setAttribute('to', o.point_id)
                        sta.appendChild(tmp)
                    if o.v is not None:
                        tmp = doc.createElement('z-angle')
                        tmp.setAttribute('to', o.point_id)
                        tmp.setAttribute('val', str(o.v.get_angle('GON')))
                        tmp.setAttribute('from_dh', str(ih))
                        tmp.setAttribute('to_dh', str(th))
                        sta.appendChild(tmp)
                else:
                    # unknown dimension
                    return None
        # generate temp file name
        tmpf = QTemporaryFile(QDir.temp().absoluteFilePath('w'))
        tmpf.open(QIODevice.WriteOnly)
        tmpf.close()
        tmp_name = tmpf.fileName()
        f = QFile(tmp_name + '.xml')
        if f.open(QIODevice.WriteOnly):
            f.write(doc.toByteArray())
            f.close()

        # run gama-local
        if self.gama_prog is None:
            return None
        status = QProcess.execute(self.gama_prog, [
            tmp_name + '.xml', '--angles', '360', '--text', tmp_name + '.txt',
            '--xml', tmp_name + 'out.xml'
        ])
        if status != 0:
            return None

        xmlParser = QXmlSimpleReader()
        xmlFile = QFile(tmp_name + 'out.xml')
        xmlInputSource = QXmlInputSource(xmlFile)
        doc.setContent(xmlInputSource, xmlParser)

        f_txt = QFile(tmp_name + '.txt')
        f_txt.open(QIODevice.ReadOnly)
        res = f_txt.readAll().data()
        f_txt.close()

        # store coordinates
        adj_nodes = doc.elementsByTagName('adjusted')
        if adj_nodes.count() < 1:
            return res
        adj_node = adj_nodes.at(0)
        for i in range(len(adj_node.childNodes())):
            pp = adj_node.childNodes().at(i)
            if pp.nodeName() == 'point':
                for ii in range(len(pp.childNodes())):
                    ppp = pp.childNodes().at(ii)
                    if ppp.nodeName() == 'id':
                        p = Point(ppp.firstChild().nodeValue())
                    elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y':
                        p.e = float(ppp.firstChild().nodeValue())
                    elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x':
                        p.n = float(ppp.firstChild().nodeValue())
                    elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z':
                        p.z = float(ppp.firstChild().nodeValue())
                ScPoint(p).store_coord(self.dimension)
        # remove input xml and output xml
        tmpf.remove()
        f_txt.remove()
        f.remove()
        xmlFile.remove()

        return res