Exemplo n.º 1
0
    def getActivePlugins(self, filename=None):
        '''
        Function checks xml and returns if plugin was active on previous program execution
        xmlfile: specifies alternative path to xml file with plugin information
        '''

        if not filename:
            filename = self.xmlFile

        if os.path.exists(filename):
            fileObject = QFile(filename)
            Xml = QDomDocument("xmldoc")
            Xml.clear()
            if (fileObject.open(QIODevice.ReadOnly)):
                Xml.setContent(fileObject.readAll())
                fileObject.close()

            rootNode = Xml.documentElement()
            nodeList = rootNode.elementsByTagName("plugin")

            for i in range(nodeList.length()):
                bpNode = nodeList.at(i).toElement()
                path = str(bpNode.attribute("path"))
                if path in self.pluginActions:
                    self.pluginActions[path].setLoaded(
                        bpNode.attribute("active") == "y")
                else:
                    logging.warning(
                        "No plugin for %s found, maybe it was moved/deleted?",
                        path)
Exemplo n.º 2
0
    def savePluginInfo(self, filename=None):
        '''
        write plugin info to xml (plugin active/inactive ...)
        xmlfile: specifies alternative path to xml file with plugin information
        '''

        if not filename:
            filename = self.xmlFile

        # create xml
        Xml = QDomDocument("xmldoc")
        rootNode = Xml.createElement("SysCDbgActivePlugins")
        Xml.appendChild(rootNode)

        for i in iter(self.pluginActions.values()):
            pluginNode = Xml.createElement("plugin")
            pluginNode.setAttribute("path", i.path)
            if i.isChecked():
                pluginNode.setAttribute("active", "y")
            else:
                pluginNode.setAttribute("active", "n")
            rootNode.appendChild(pluginNode)

        # create and write xml file
        with open(filename, "w") as f:
            f.write(Xml.toString())
Exemplo n.º 3
0
    def get_template_element(self, path):
        """
        Gets the template element.
        :param path: The path of the template
        :type path: String
        :return: QDomDocument,
        QDomDocument.documentElement()
        :rtype: Tuple
        """
        config_file = os.path.join(path)
        config_file = QFile(config_file)
        if not config_file.open(QIODevice.ReadOnly):
            template = os.path.basename(path)
            self.prog.setLabelText(
                QApplication.translate('TemplateUpdater',
                                       'Failed to update {}'.format(template)))
            error_title = QApplication.translate('TemplateContentReader',
                                                 'File Reading Error')
            error_message = QApplication.translate(
                'TemplateContentReader', 'Failed to update {0}. '
                'Check the file permission of {0}'.format(template))

            QMessageBox.critical(iface.mainWindow(), error_title,
                                 error_message)
            return None

        doc = QDomDocument()

        status, msg, line, col = doc.setContent(config_file)
        if not status:
            return None

        doc_element = doc.documentElement()

        return doc_element
Exemplo n.º 4
0
def getAttachments(xml_doc):
    # Get text part and attachments
    doc = QDomDocument()
    doc.setContent(xml_doc)
    root = doc.firstChild().toElement()
    alt_part = root.elementsByTagName('alternative').item(0)
    parts = root.childNodes()
    attachments = []
    i = 0
    while i < parts.length():
        i += 1
        e = parts.item(i-1).toElement()
        if e.tagName() != 'part' : continue
        if 'text/' in e.attribute('type') and alt_part.isNull() :
            text_part_num, enc = e.attribute('PartNum'), e.attribute('encoding')
        else:
            attachments.append([e.attribute('PartNum'), e.attribute('encoding'),
                            e.attribute('filename'), formatFileSize(e.attribute('size'))])
    # preferably select text/html in multipart/alternative
    if not alt_part.isNull():
        part = alt_part.firstChild()
        while not part.isNull():
            e = part.toElement()
            text_part_num, enc = e.attribute('PartNum'), e.attribute('encoding')
            if e.attribute('type') == 'text/html':
                break
            part = part.nextSibling()
    return text_part_num, enc, attachments
    def copy(self):
        # Iterate
        selectedNodes = self.iface.layerTreeView().selectedNodes(True)
        if len(selectedNodes) == 0:
            self.iface.messageBar().pushMessage(
                "Copy layers and groups",
                "First select at least 1 layer or group in the Layers Panel.",
                0, 7)
            return

        doc = QDomDocument("QGIS-layers-and-groups")
        QgsLayerDefinition.exportLayerDefinition(doc, selectedNodes, "", "")

        tempDir = tempfile.gettempdir()
        xmlFilePath = os.path.join(tempDir,
                                   str(time.time()).replace(".", "") + ".qlr")
        f = codecs.open(xmlFilePath, 'w', encoding='utf-8')
        f.write(doc.toString())
        f.close()

        self.clipboard.setText(
            "@QGIS-layers-and-groups@{}".format(xmlFilePath))
        self.iface.messageBar().pushMessage(
            "Copy layers and groups",
            "Selected layers and/or groups were copied to clipboard.", 0, 5)
Exemplo n.º 6
0
    def on_pushButton_5_clicked(self):

        self.listWidget.clear()  # 先清空显示

        file = QFile("my.xml")
        if (not file.open(QIODevice.ReadOnly)):
            raise Exception("open my.xml Err")
        doc = QDomDocument()
        status, rrorMsg, errorLine, errorColumn = doc.setContent(file)
        if (not status):
            file.close()
            raise Exception(str(rrorMsg))
        file.close()

        docElem = doc.documentElement()  # 返回根元素

        n = docElem.firstChild()
        while (not n.isNull()):
            if (n.isElement()):
                e = n.toElement()
                self.listWidget.addItem(e.tagName() +
                                        e.attribute(QString("编号")))
                list = e.childNodes()
                for i in range(list.count()):
                    node = list.at(i)
                    if (node.isElement()):
                        self.listWidget.addItem("   " +
                                                node.toElement().tagName() +
                                                " : " +
                                                node.toElement().text())
            n = n.nextSibling()
Exemplo n.º 7
0
    def __init__(self, parent=None, xml='', highlighterClass=None):
        '''
        Constructor
        '''
        super(XmlViewerDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        self.setupUi(self)

        try:
            xml.seek(0)
        except:
            pass

        doc = QDomDocument()
        (ok, errorMsg, _, _) = doc.setContent(xml, True)
        self.lblError.setVisible(not ok)
        if ok:
            self.xmlTree.setModel(XmlModel(doc, self))
            if isinstance(xml, QFile):
                xml = doc.toString(indent=4)
        else:
            xml = ""
            self.lblError.setText(errorMsg)

        self.xmlText.setPlainText(xml)

        if highlighterClass:
            highlighterClass(self.xmlText)
Exemplo n.º 8
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
Exemplo n.º 9
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
Exemplo n.º 10
0
        def getTargetWindows():
            file = self._getFile(layer)
            if file is None:
                return None

            doc = QDomDocument()
            doc.setContent(file)
            file.close()

            nodes = doc.elementsByTagName('TargetWindow')
            if nodes.count == 0:
                return None

            node = nodes.item(0)
            targetWindow = {'ulX': None, 'ulY': None, 'lrX': None, 'lrY': None}
            labels = {
                'UpperLeftX': 'ulX',
                'UpperLeftY': 'ulY',
                'LowerRightX': 'lrX',
                'LowerRightY': 'lrY'
            }
            for key, value in labels.iteritems():
                text = node.firstChildElement(key).text()
                if len(text) == 0:
                    continue
                targetWindow[value] = float(text)

            if None in targetWindow.values():
                return None

            return targetWindow
Exemplo n.º 11
0
    def testSubstitutionMap(self):
        """Test that we can use degree symbols in substitutions.
        """
        # Create a point and convert it to text containing a degree symbol.
        myPoint = QgsPoint(12.3, -33.33)
        myCoordinates = myPoint.toDegreesMinutesSeconds(2)
        myTokens = myCoordinates.split(',')
        myLongitude = myTokens[0]
        myLatitude = myTokens[1]
        myText = 'Latitude: %s, Longitude: %s' % (myLatitude, myLongitude)

        # Load the composition with the substitutions
        myComposition = QgsComposition(CANVAS.mapRenderer())
        mySubstitutionMap = {'replace-me': myText}
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        myTemplateFile = file(myFile, 'rt')
        myTemplateContent = myTemplateFile.read()
        myTemplateFile.close()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument, mySubstitutionMap)

        # We should be able to get map0
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage
Exemplo n.º 12
0
    def template_document(self, path):
        """
        Reads the document template file and returns the corresponding
        QDomDocument.
        :param path: Absolute path to template file.
        :type path: str
        :return: A tuple containing the template document and error message
        where applicable
        :rtype: tuple
        """
        if not path:
            return None, QApplication.translate(
                "DocumentGenerator", "Empty path to document template")

        if not QFile.exists(path):
            return None, QApplication.translate(
                "DocumentGenerator", "Path to document template "
                "does not exist")

        template_file = QFile(path)

        if not template_file.open(QIODevice.ReadOnly):
            return None, QApplication.translate("DocumentGenerator",
                                                "Cannot read template file")

        template_doc = QDomDocument()

        if template_doc.setContent(template_file):
            return template_doc, ""

        return None, QApplication.translate(
            "DocumentGenerator", "Cannot read document template contents")
Exemplo n.º 13
0
def bodystructureToXml(bodystructure):
    parts = parse_bodystructure(bodystructure)
    alt_partnum = '.'
    doc = QDomDocument()
    root = doc.createElement('body')
    doc.appendChild(root)
    for part_num, text in parts:
        if text.startswith('MULTIPART/'):
            if text == 'MULTIPART/ALTERNATIVE':
                alt_part = doc.createElement('alternative')
                root.appendChild(alt_part)
                alt_partnum = part_num
        else:
            part_type, encoding, size, filename = parse_nonmultipart(text)
            item = doc.createElement('part')
            item.setAttribute('PartNum', part_num)
            item.setAttribute('type', part_type)
            item.setAttribute('encoding', encoding)
            if part_num.startswith(alt_partnum) and part_type.startswith('text/'):
                alt_part.appendChild(item)
            else:
                item.setAttribute('filename', filename)
                item.setAttribute('size', size)
                root.appendChild(item)
    return doc
Exemplo n.º 14
0
    def test_constructor_with_dom(self):
        fun = sys._getframe().f_code.co_name
        print "Run: %s.%s() " % (self.__class__.__name__, fun)
        doc = QDomDocument()
        nname = "definition"
        qdn = doc.createElement(nname)
        doc.appendChild(qdn)
        nkids = self.__rnd.randint(1, 10)
        kds = []
        for n in range(nkids):
            kds.append(doc.createElement("kid%s" % n))
            qdn.appendChild(kds[-1])

        ci = ComponentItem(qdn)

        self.assertEqual(ci.parent, None)
        self.assertEqual(ci.node, qdn)
        self.assertEqual(ci.childNumber(), 0)
        self.assertEqual(ci.node.nodeName(), nname)
        for k in range(nkids):
            self.assertTrue(isinstance(ci.child(k), ComponentItem))
            self.assertTrue(isinstance(ci.child(k).parent, ComponentItem))
            self.assertEqual(ci.child(k).childNumber(), k)
            self.assertEqual(ci.child(k).node, kds[k])
            self.assertEqual(ci.child(k).parent.node, qdn)
            self.assertEqual(ci.child(k).node.nodeName(), "kid%s" % k)
            self.assertEqual(ci.child(k).parent, ci)
Exemplo n.º 15
0
 def colorRampToString( self, ramp ):
     if ramp is None:
         return '';
     d=QDomDocument()
     d.appendChild(QgsSymbolLayerV2Utils.saveColorRamp('ramp',ramp,d))
     rampdef=d.toString()
     return rampdef
Exemplo n.º 16
0
def composer_data_source(template_file):
    """
    Creates a ComposerDataSource object from the specified template file. If
    the file cannot be opened due to file permissions or if it does not exist
    then the function will return None.
    :param template_file: Absolute template file path.
    :type template_file: str
    :return: Composer data source object.
    :rtype: ComposerDataSource
    """
    t_file = QFile(template_file)

    #Check if the file exists
    if not t_file.exists():
        return None

    #Check if the file can be opened
    if not t_file.open(QIODevice.ReadOnly):
        return None

    template_doc = QDomDocument()

    #Populate dom document
    if template_doc.setContent(t_file):
        return ComposerDataSource.create(template_doc)

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

            texts = []

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

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

            return u' '.join(texts)
        finally:
            f.close()
Exemplo n.º 18
0
 def importDOM(self, fname):
     dom = QDomDocument()
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         if not dom.setContent(fh):
             raise ValueError("could not parse XML")
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
     try:
         self.populateFromDOM(dom)
     except ValueError as e:
         return False, "Failed to import: {0}".format(e)
     self.__fname = QString()
     self.__dirty = True
     return True, "Imported {0} movie records from {1}".format(
         len(self.__movies),
         QFileInfo(fname).fileName())
Exemplo n.º 19
0
 def loadCachedMails(self):
     """ fetch list of mails (with headers) in a mailbox """
     oldest_uid, latest_uid = None, None
     mailbox_file = ACNT_DIR + self.email_id + '/%s.xml'%self.mailbox[:].replace('/', '_')
     if os.path.exists(mailbox_file):
         # load cached mails
         doc = QDomDocument()
         doc_file = QtCore.QFile(mailbox_file)
         if doc_file.open(QtCore.QIODevice.ReadOnly):
             doc.setContent(doc_file)
             doc_file.close()
         mails = doc.firstChild().toElement()
         mail = mails.firstChild()
         latest_uid = mail.toElement().attribute('UID')
         i = 0
         while not mail.isNull():
             e = mail.toElement()
             self.mailsTable.insertRow(i)
             item = MailItem()
             item.setData(e.attribute('Sender'), e.attribute('Subject'), e.attribute('UID'),
                      e.attribute('Message-ID'), e.attribute('Date'), e.attribute('Cached'))
             self.mailsTable.setCellWidget(i, 0, item)
             self.mailsTable.resizeRowsToContents()
             wait(30)
             mail = mail.nextSibling()
             i += 1
         oldest_uid = mails.lastChild().toElement().attribute('UID')
     print 'uids', oldest_uid, latest_uid
     if latest_uid:
         self.uidListRequested.emit(oldest_uid, latest_uid)
     else:
         self.newMailsRequested.emit(0)
Exemplo n.º 20
0
    def __init__(self):
        try:
            self.__seed = long(binascii.hexlify(os.urandom(16)), 16)
        except NotImplementedError:
            self.__seed = long(time.time() * 256)
#        self.__seed = 71366247078680776091931824685320965500
        self.__rnd = random.Random(self.__seed)
        print "VIEW SEED", self.__seed

        self.sindex = None
        self.eindex = None

        self.doc = QDomDocument()
        self.nname = "definition"
        self.qdn = self.doc.createElement(self.nname)
        self.doc.appendChild(self.qdn)
        self.nkids = self.__rnd.randint(1, 10)
        #        print "NKID", self.nkids
        self.kds = []
        self.tkds = []
        for n in range(self.nkids):
            self.kds.append(self.doc.createElement("kid%s" % n))
            self.kds[-1].setAttribute("name", "myname%s" % n)
            self.kds[-1].setAttribute("type", "mytype%s" % n)
            self.kds[-1].setAttribute("units", "myunits%s" % n)
            self.qdn.appendChild(self.kds[-1])
            self.tkds.append(self.doc.createTextNode("\nText\n %s\n" % n))
            self.kds[-1].appendChild(self.tkds[-1])

#        print doc.toString()

        self.allAttr = False
        self.testModel = ComponentModel(self.doc, self.allAttr)
        #        self.myindex = self.setIndex(0, 0, self.testModel.rootIndex)
        self.myindex = QModelIndex()
Exemplo n.º 21
0
    def testQgsSvgMarkerSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = 'QgsSvgMarkerSymbolLayerV2'
        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 = QgsSvgMarkerSymbolLayerV2.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

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

        mExpectedValue = u'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
Exemplo n.º 22
0
    def loadTemplate(self, filePath):
        """
        Loads a document template into the view and updates the necessary STDM-related controls.
        """
        if not QFile.exists(filePath):
            QMessageBox.critical(self.composerView(), QApplication.translate("OpenTemplateConfig","Open Template Error"), \
                                        QApplication.translate("OpenTemplateConfig","The specified template does not exist."))
            return

        templateFile = QFile(filePath)

        if not templateFile.open(QIODevice.ReadOnly):
            QMessageBox.critical(self.composerView(), 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):
            #Load items into the composition and configure STDM data controls
            self.composition().loadFromTemplate(templateDoc)
            self.clearWidgetMappings()

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

            #Load symbol editors
            spatialFieldsConfig = SpatialFieldsConfiguration.create(
                templateDoc)
            self._configureSpatialSymbolEditor(spatialFieldsConfig)
Exemplo n.º 23
0
def make_pdf():
    canvas = QgsMapCanvas()
    # Load our project
    QgsProject.instance().read(QFileInfo(project_path))
    bridge = QgsLayerTreeMapCanvasBridge(QgsProject.instance().layerTreeRoot(),
                                         canvas)
    bridge.setCanvasLayers()

    template_file = file(template_path)
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)
    composition = QgsComposition(canvas.mapSettings())
    # You can use this to replace any string like this [key]
    # in the template with a new value. e.g. to replace
    # [date] pass a map like this {'date': '1 Jan 2012'}
    substitution_map = {'DATE_TIME_START': 'foo', 'DATE_TIME_END': 'bar'}
    composition.loadFromTemplate(document, substitution_map)
    # You must set the id in the template
    map_item = composition.getComposerItemById('map')
    map_item.setMapCanvas(canvas)
    map_item.zoomToExtent(canvas.extent())
    # You must set the id in the template
    legend_item = composition.getComposerItemById('legend')
    legend_item.updateLegend()
    composition.refreshItems()
    composition.exportAsPDF('report.pdf')
    QgsProject.instance().clear()
Exemplo n.º 24
0
    def setFromNode(self, datasource):
        res = self.main.node.firstChildElement(QString("result"))
        text = DomTools.getText(res)
        while len(text) > 0 and text[0] == '\n':
            text = text[1:]
        datasource.var['PYEVAL'].script = unicode(text) if text else ""
        attributeMap = res.attributes()
        datasource.var['PYEVAL'].result = unicode(
            "ds." + attributeMap.namedItem("name").nodeValue() if attributeMap.
            contains("name") else "")

        ds = DomTools.getText(self.main.node)
        dslist = unicode(ds).strip().split() \
            if unicode(ds).strip() else []
        datasource.var['PYEVAL'].dataSources = {}
        child = self.main.node.firstChildElement(QString("datasource"))
        while not child.isNull():
            if child.nodeName() == 'datasource':
                attributeMap = child.attributes()
                name = unicode(
                    attributeMap.namedItem("name").nodeValue() if attributeMap.
                    contains("name") else "")
                if name.strip():
                    dslist.append(name.strip())
                    doc = QDomDocument()
                    doc.appendChild(doc.importNode(child, True))
                    datasource.var['PYEVAL'].dataSources[name] = unicode(
                        doc.toString(0))
                    child = child.nextSiblingElement("datasource")

        datasource.var['PYEVAL'].input = " ".join(
            "ds." +
            (d[13:] if (len(d) > 13 and d[:13] == "$datasources.") else d)
            for d in dslist)
Exemplo n.º 25
0
    def load(self, filename):
        f = QFile(filename)
        f.open(QIODevice.ReadOnly)

        doc = QDomDocument()
        doc.setContent(f)

        root = doc.documentElement()
        items = root.childNodes().at(0).toElement()
        connections = root.childNodes().at(1).toElement()

        itemmap = dict()

        # Iterate through all children
        for n in [
                items.childNodes().at(i).toElement()
                for i in range(items.childNodes().length())
        ]:
            # type and pos
            _type = str(n.attributeNode("type").value())
            poselem = n.elementsByTagName("pos").at(0).toElement()
            _pos = QPointF(float(str(poselem.attributeNode("x").value())),
                           float(str(poselem.attributeNode("y").value())))

            exec("from items.%s import *" % _type)
            item = eval(_type)()
            item.setPos(_pos)
            self.addItem(item)

            item.load(n.elementsByTagName("properties").at(0).toElement())

            itemmap[int(str(n.attributeNode("id").value()))] = item

        # Connections
        for n in [
                connections.childNodes().at(i).toElement()
                for i in range(connections.childNodes().length())
        ]:
            sourceelem = n.childNodes().at(0).toElement()
            targetelem = n.childNodes().at(1).toElement()

            sourceid = int(str(sourceelem.attributeNode("id").value()))
            sourceport = int(str(sourceelem.attributeNode("port").value()))

            targetid = int(str(targetelem.attributeNode("id").value()))
            targetport = int(str(targetelem.attributeNode("port").value()))

            self.graph.addEdge(itemmap[sourceid].providesPorts[sourceport],
                               itemmap[targetid].requiresPorts[targetport])

        QApplication.processEvents()
        self.update()
        QApplication.processEvents()

        for item in self.graph.items():
            self.graph.updateEdges(item)

        f.close()
        self.setModified(False)
Exemplo n.º 26
0
 def copyToClipboard(self):
     dsNode = self.createNodes(True)
     doc = QDomDocument()
     child = doc.importNode(dsNode, True)
     doc.appendChild(child)
     text = unicode(doc.toString(0))
     clipboard = QApplication.clipboard()
     clipboard.setText(text)
Exemplo n.º 27
0
 def __init__(self, xml, parent=None):
     QWidget.__init__(self, None)
     self.doc = QDomDocument()
     if self.doc.setContent(xml) == False:
         print "Something is wrong"
         return
     self.model = DomModel(self.doc, self)
     parent.view.setModel(self.model)
Exemplo n.º 28
0
 def __init__(self, instance):
     """
     Initialize variables
     """
     self.instance = instance
     self.instance_doc = QDomDocument()
     self.set_instance_document(self.instance)
     self.key_watch = 0
Exemplo n.º 29
0
 def fromFile(cls, filename):
     QDir.setCurrent(os.path.dirname(filename))
     fileinfo = QFileInfo(filename)
     QgsProject.instance().read(fileinfo)
     xml = open(filename).read()
     doc = QDomDocument()
     doc.setContent(xml)
     return cls(doc)
Exemplo n.º 30
0
    def ReadProjectInfoXml(self):
        try:
            result = DlgCrcCheck.smethod_0(None, self.m_strProjectInfoFullName)
        except:
            return False
        if not result:
            return False

        doc = QDomDocument()
        qFile = QFile(self.m_strProjectInfoFullName)
        if qFile.open(QFile.ReadOnly):
            doc.setContent(qFile)
            qFile.close()
        else:
            raise UserWarning, "can not open file:" + self.m_strProjectInfoFullName
        dialogNodeList = doc.elementsByTagName("ProjectListClass")
        if dialogNodeList.isEmpty():
            raise UserWarning, "This file is not correct."
        dialogElem = dialogNodeList.at(0).toElement()

        ctrlNodesList = dialogElem.elementsByTagName("ProjectInfo")
        for i in range(ctrlNodesList.count()):
            pj = ProjectInfo()
            lineEditElem = ctrlNodesList.at(i).toElement()
            objectNameNode = lineEditElem.elementsByTagName("Name").at(0)
            objectNameElem = objectNameNode.toElement()
            pj.Name = objectNameElem.text()

            pathElem = objectNameElem.nextSiblingElement()
            pj.Path = pathElem.text()

            createdElem = pathElem.nextSiblingElement()
            pj.Created = createdElem.text()

            procedureNameElem = createdElem.nextSiblingElement()
            pj.ProcedureName = procedureNameElem.text()

            projNameElem = procedureNameElem.nextSiblingElement()
            pj.ProjName = projNameElem.text()

            ptElem = projNameElem.nextSiblingElement()
            pj.Pt = ptElem.text()

            subProjNameElem = ptElem.nextSiblingElement()
            pj.SubProjName = subProjNameElem.text()

            userNameElem = subProjNameElem.nextSiblingElement()
            pj.UserName = userNameElem.text()

            workspaceNameElem = userNameElem.nextSiblingElement()
            pj.WorkspaceName = workspaceNameElem.text()

            fullNameElem = workspaceNameElem.nextSiblingElement()
            pj.FullName = fullNameElem.text()

            self.ProjectsList.append(pj)
        return True