def mkChapter(b): #print b.attributes() filter('zones', '"name" = '+str(b.attributes()[0])+'' ) filter('zones2', '"name" = '+str(b.attributes()[0])+'' ) filter('divisions', '"name" = "'+str(b.attributes()[0])+'"' ) filter('divisions2', '"name" = "'+str(b.attributes()[0])+'"' ) #cuidado que aqu´i se lia con valor integer o string zz = Lz.getFeatures(QgsFeatureRequest(QgsExpression('"name" = '+str(b.attributes()[0])+''))) zz = [x for x in zz] filter('districtes', '"c_distri" = "'+str(zz[0].attributes()[2])+'"' ) #coje la geometria del distriro distri = QgsMapLayerRegistry.instance().mapLayer(mapL['districtes']) gd= [d for d in distri.getFeatures()][0] canvas = QgsMapCanvas() template_path = root+qptChapter template_file = file(template_path) template_content = template_file.read() template_file.close() document = QDomDocument() document.setContent(template_content) #ms = canvas.mapSettings() ms=iface.mapCanvas().mapRenderer() #ms.setLayerSet(QgsMapLayerRegistry.instance().mapLayers().keys()) composition = QgsComposition(ms) composition.loadFromTemplate(document, {}) ## map_item = composition.getComposerItemById('mapa') map_item.setMapCanvas(canvas) #map_item.setRotation(-b.attributes()[1])######## bounds = (b.geometry()).boundingBox() map_item.zoomToExtent(bounds) ## map_item_distri = composition.getComposerItemById('mapDistrito') map_item_distri.setMapCanvas(canvas) map_item_distri.zoomToExtent(gd.geometry().boundingBox()) ##zona zo = composition.getComposerItemById('zona') zo.setText(str(b.attributes()[0])) ##barrio y distrito distrito = composition.getComposerItemById('distrito') distrito.setText(zz[0].attributes()[3]+' | '+zz[0].attributes()[2]) barrio = composition.getComposerItemById('barrio') barrio.setText(zz[0].attributes()[4]+' | '+zz[0].attributes()[5]) composition.refreshItems() composition.exportAsPDF(root+'output/'+str(b.attributes()[0]).zfill(4)+'.pdf') #filter('zones', '"name" = ""' ) filter('divisions', '' ) filter('divisions2', '' ) filter('districtes', '' ) return
def setDataSource( self, newSourceUri): ''' Method to apply a new datasource to a vector Layer ''' layer = self.layer newDS, newUri = self.splitSource(newSourceUri) newDatasourceType = newDS or layer.dataProvider().name() # read layer definition XMLDocument = QDomDocument("style") XMLMapLayers = QDomElement() XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = QDomElement() XMLMapLayer = XMLDocument.createElement("maplayer") layer.writeLayerXML(XMLMapLayer,XMLDocument) # apply layer definition XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(newUri) XMLMapLayer.firstChildElement("provider").firstChild().setNodeValue(newDatasourceType) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) layer.readLayerXML(XMLMapLayer) # Update layer extent layer.updateExtents() # Update graduated symbol renderer if layer.rendererV2().type() == u'graduatedSymbol': if len(layer.rendererV2().ranges()) == 1: layer.rendererV2().updateClasses( layer, layer.rendererV2().mode(), len(layer.rendererV2().ranges()) ) #Reload layer layer.reload()
def searchshow(self, name): ''' @type name: str @rtype: list ''' data = self._request('http://www.thetvdb.com/api/GetSeries.php?seriesname=%s' % name) xml = QDomDocument() xml.setContent(data) showsxml = xml.elementsByTagName('Series') shows = [] for i in range(len(showsxml)): newshow = show() newshow.id = unicode(QString(showsxml.at(i).toElement().elementsByTagName('seriesid').at(0).childNodes().at(0).toText().data())) newshow.name = unicode(QString(showsxml.at(i).toElement().elementsByTagName('SeriesName').at(0).childNodes().at(0).toText().data())) newshow.description = unicode(QString(showsxml.at(i).toElement().elementsByTagName('Overview').at(0).childNodes().at(0).toText().data())) newshow.image = unicode(QString(showsxml.at(i).toElement().elementsByTagName('banner').at(0).firstChild().toText().data())) newshow.data = showsxml.at(i).toElement() if len(newshow.image): self._download(urljoin(urljoin(choice(self.__mirrors[1]), '/banners/'), newshow.image), newshow.image) shows.append(newshow) return shows
def getlocalseasons(self, id): ''' @type id: str @rtype: list ''' seasons = {} if self._storage.exists('shows/%s/en.xml' % id): data = self._storage.getdata('shows/%s/en.xml' % id) xml = QDomDocument() xml.setContent(data) episodes = xml.elementsByTagName('Episode') for episode in range(episodes.count()): seasonid = unicode(QString(episodes.at(episode).toElement().elementsByTagName('seasonid').at(0).childNodes().at(0).toText().data())) seasonnum = QString(episodes.at(episode).toElement().elementsByTagName('SeasonNumber').at(0).childNodes().at(0).toText().data()).toInt() if seasonnum[1]: if seasonnum[0] > 0: if not seasonid in seasons: newseason = season() newseason.id = seasonid newseason.number = seasonnum[0] newseason.image = 'seasonbanners/%s-%d.jpg' % (id, newseason.number) newseason.showid = id seasons[seasonid] = newseason return sorted(seasons.values(), key = lambda item: item.number)
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)
def parse_knitting_symbol(symbolPath): """ Parse the knitting symbol located at path symbolPath. """ descriptionFile = QFile(symbolPath + "/description") if (not descriptionFile.exists()) or descriptionFile.error(): return None # parse XML dom = QDomDocument() (status, msg, line, col) = dom.setContent(descriptionFile) if not status: errorMessage = ("Failed reading pattern description in file %s -- " "%s at line %d column %d" % (descriptionFile.fileName(), msg, line, col)) logger.error(errorMessage) return None # make sure we're reading a sconcho pattern description root = dom.documentElement() if root.tagName() != "sconcho": return None # parse the actual content node = root.firstChild() if node.toElement().tagName() != "knittingSymbol": return None content = parse_symbol_description(node) # add the absolute path content["svgPath"] = symbolPath + "/" + content["svgName"] + ".svg" return content
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()
def make_pdf(): canvas = QgsMapCanvas() # Load our project QgsProject.instance().read(QFileInfo(project_path)) bridge = QgsLayerTreeMapCanvasBridge( QgsProject.instance().layerTreeRoot(), canvas) bridge.setCanvasLayers() if canvas.layerCount() < 1: print 'No layers loaded from this project, exiting.' return print canvas.mapSettings().extent().toString() 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': TIME_START, 'DATE_TIME_END': TIME_STOP} 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( '/home/web/reports/pdf/%s/%s.pdf' % (TIME_SLICE, LABEL)) QgsProject.instance().clear()
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")
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
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)
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
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
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())
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
def printWyrysPDF(self): alayer = self.iface.activeLayer() # Dodaje wszystkie warstwy do widoku mapy myMapRenderer = self.iface.mapCanvas().mapRenderer() # ładuje szablon druku myComposition = QgsComposition(myMapRenderer) username = getpass.getuser() username = str(username) templateDir = r"C:\Users" endDir = r"\Desktop\Knurow_mpzp\pliki\szablony_druku\jedno\wyrys\wyrys" template = self.szablon qpt = ".qpt" myFile = os.path.join(templateDir, username + endDir + template + qpt) myTemplateFile = file(myFile, "rt") myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # pobierz kompozycję mapy i zdefinuj skalę myAtlasMap = myComposition.getComposerMapById(0) # Konfiguracja Atlas myAtlas = myComposition.atlasComposition() # ustawia warstwÄ w atlasie myAtlas.setEnabled(True) myAtlas.setCoverageLayer(alayer) myAtlas.setHideCoverage(False) myAtlas.setSingleFile(True) myAtlas.setHideCoverage(False) myAtlasMap.setAtlasDriven(True) # mapa kontrolowana przez atlas myAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto) # jaka skala kontrolowana przez atlas (margin) myComposition.setAtlasMode(QgsComposition.ExportAtlas) # Ustawia Atlas na Eksport do PDF myComposition.refreshItems() # generuj atlas myAtlas.beginRender() myAtlas.prepareForFeature(self.idAtlas) saveDirEnd = "\Desktop\Knurow_mpzp\wydruki\wyrysy" outputDir = os.path.join(templateDir, username + saveDirEnd) output_pdf = outputDir + "\Wyrys_" + self.sygnatura + ".pdf" # saveDir = r'C:\Users\haku\Desktop\Opole\Knurow\druk\atlas\pdf' # output_pdf = saveDir + "wyrys_dz_" + str(self.idAtlas)+ "_MPZP_plan.pdf" try: myComposition.exportAsPDF(output_pdf) myAtlas.endRender() self.iface.messageBar().pushMessage( "Sukces", u"Wyrys został wygenerowany pomyślnie", level=QgsMessageBar.SUCCESS, duration=5 ) except: self.iface.messageBar().pushMessage( u"Błąd", u"Generowanie Wyrysu nie powiodło sie", level=QgsMessageBar.CRITICAL, duration=5 )
def xmlDownloaded(self,nr,state): """ populate the plugins object with the fetched data """ if not self.httpId.has_key(nr): return reposName = self.httpId[nr] if state: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = self.mRepositories[reposName]["QPHttp"].errorString() else: repoData = self.mRepositories[reposName]["xmlData"] reposXML = QDomDocument() reposXML.setContent(repoData.data()) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement("file_name").text().simplified() if not fileName: fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().trimmed().split("?")[0]).fileName() name = fileName.section(".", 0, 0) name = unicode(name) experimental = False if pluginNodes.item(i).firstChildElement("experimental").text().simplified().toUpper() in ["TRUE","YES"]: experimental = True plugin = { "name" : pluginNodes.item(i).toElement().attribute("name"), "version_avail" : pluginNodes.item(i).toElement().attribute("version"), "desc_repo" : pluginNodes.item(i).firstChildElement("description").text().simplified(), "desc_local" : "", "author" : pluginNodes.item(i).firstChildElement("author_name").text().simplified(), "homepage" : pluginNodes.item(i).firstChildElement("homepage").text().simplified(), "url" : pluginNodes.item(i).firstChildElement("download_url").text().simplified(), "experimental" : experimental, "filename" : fileName, "status" : "not installed", "error" : "", "error_details" : "", "version_inst" : "", "repository" : reposName, "localdir" : name, "read-only" : False} qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().simplified() if not qgisMinimumVersion: qgisMinimumVersion = "1" qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().simplified() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99" #if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement("disabled").text().simplified().toUpper() in ["TRUE","YES"]: if compareVersions(QGIS_VER, qgisMinimumVersion) < 2 and compareVersions(qgisMaximumVersion, QGIS_VER) < 2: #add the plugin to the cache plugins.addFromRepository(plugin) # set state=2, even if the repo is empty self.mRepositories[reposName]["state"] = 2 self.emit(SIGNAL("repositoryFetched(QString)"), reposName ) # is the checking done? if not self.fetchingInProgress(): plugins.rebuild() self.saveCheckingOnStartLastDate() self.emit(SIGNAL("checkingDone()"))
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)
def getSymbology(source): di = QDomImplementation() documentType = di.createDocumentType('qgis', 'http://mrcc.com/qgis.dtd', 'SYSTEM') doc = QDomDocument(documentType) rootNode = doc.createElement('qgis') rootNode.setAttribute('version', str(QGis.QGIS_VERSION)) doc.appendChild(rootNode) source.writeSymbology(rootNode, doc, '') return rootNode
def prepare_composition_from_template(c, template_path, time): document = QDomDocument() document.setContent(open(template_path).read()) c.loadFromTemplate(document) c.setPlotStyle(QgsComposition.Print) composition_set_time(c, time)
def xmlDownloaded(self,nr,state): """ populate the plugins object with the fetched data """ if not self.httpId.has_key(nr): return reposName = self.httpId[nr] if state: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = self.mRepositories[reposName]["QPHttp"].errorString() else: repoData = self.mRepositories[reposName]["xmlData"] reposXML = QDomDocument() reposXML.setContent(repoData.data()) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().trimmed()).fileName() name = fileName.section(".", 0, 0) name = str(name) plugin = {} plugin[name] = { "name" : pluginNodes.item(i).toElement().attribute("name"), "version_avail" : pluginNodes.item(i).toElement().attribute("version"), "desc_repo" : pluginNodes.item(i).firstChildElement("description").text().trimmed(), "desc_local" : "", "author" : pluginNodes.item(i).firstChildElement("author_name").text().trimmed(), "homepage" : pluginNodes.item(i).firstChildElement("homepage").text().trimmed(), "url" : pluginNodes.item(i).firstChildElement("download_url").text().trimmed(), "filename" : fileName, "status" : "not installed", "error" : "", "error_details" : "", "version_inst" : "", "repository" : reposName, "localdir" : name, "read-only" : False} qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().trimmed() if not qgisMinimumVersion: qgisMinimumVersion = "0" # please use the tag below only if really needed! (for example if plugin development is abandoned) qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().trimmed() if not qgisMaximumVersion: qgisMaximumVersion = "2" #if compatible, add the plugin to the list if compareVersions(QGIS_VER, qgisMinimumVersion) < 2 and compareVersions(qgisMaximumVersion, QGIS_VER) < 2: if QGIS_VER[0]=="0" or qgisMinimumVersion[0]=="1" or name=="plugin_installer": plugins.addPlugin(plugin) plugins.workarounds() self.mRepositories[reposName]["state"] = 2 else: #print "Repository parsing error" self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller","Couldn't parse output from the repository") self.emit(SIGNAL("repositoryFetched(QString)"), reposName ) # is the checking done? if not self.fetchingInProgress(): plugins.getAllInstalled() self.emit(SIGNAL("checkingDone()"))
def readXML(self,n): filename=glob.glob('*.qgs') xml = open(filename[0]).read() doc = QDomDocument() doc.setContent(xml) filelist = doc.elementsByTagName("legendlayerfile") layerfile = filelist.at(n).toElement() layerid = layerfile.attribute('layerid') visible = int(layerfile.attribute('visible')) return layerid, bool(visible)
def loadStyle(self, layer, fileName): errorMsg = '' domdoc = QDomDocument() qml = QFile( os.path.join(os.path.dirname(__file__), 'styles' , fileName) ) if not qml.exists(): QMessageBox.warning(self, 'I\'m sorry', 'Can\'t find style definition for layer %s:\n%s\nProbably plugin installation is broken, a random style will be used instead.' % (layer.name(), qml.fileName())) return domdoc.setContent(qml) n = domdoc.firstChildElement( "qgis" ); layer.readSymbology(n, errorMsg)
def __handleReply(self, reply) : self.activeQuery = "" if reply.error() != QNetworkReply.NoError : print(">>>>>>>> ERROR! : Network Error (" + reply.errorString() + ")") self.__notifications = -1 self.queryFailed.emit() return doc = QDomDocument() doc.setContent(reply) root = doc.documentElement() if root.tagName() == "error_response" : print(">>>>>>>> ERROR! : Facebook Server Returned Error ") err = root.firstChildElement("error_code").text() if int(err) == 190 : self.queryFailed.emit() self.__notifications = -1 self.authExpired.emit() print("\tError Code : " + err) print("\tError Message : " + root.firstChildElement("error_msg").text()) elif root.tagName() == "fql_query_response" : notificationList = root.elementsByTagName("notification") print("== Recived Query Result ==") print("\tTotal Notifications : " + str(notificationList.length())) for i in range(notificationList.length()) : notification = notificationList.at(i) print(unicode(notification.namedItem("title_html").toElement().text())) children = notification.namedItem("title_html").toElement().childNodes() print("title has " + str(children.length()) + " children") for j in range(children.length()) : print(notification.nodeType()) print(children.at(j).nodeName()) if (int(notification.namedItem("anon").toElement().text()) - int(notification.namedItem("created_time").toElement().text())) <= self.settings["pollinterval"] : print("\tNotification " + str(i) + " is New! Firing KNotification::event()") icon = QPixmap(self.settings["notification_icon"]) text = self.settings["notification_title"] text.replace("%title_html%", notification.namedItem("title_html").toElement().text()) KNotification.event(KNotification.Notification, "Facebook", text, icon) else : print(">>>>>>>> ERROR! : Facebook Server returned Unexpected Output : ") print(doc.toByteArray()) if notificationList.length() != self.__notifications : self.__notifications = notificationList.length() self.notificationsChanged.emit()
def mapaPlantillaPdf(self): import time registry = QgsMapLayerRegistry.instance() layers = registry.mapLayers().values() layerName = iface.activeLayer().name() # Add layer to map render myMapRenderer = QgsMapRenderer() myMapRenderer.setLayerSet(layerName) myMapRenderer.setProjectionsEnabled(False) # Load template layer = iface.activeLayer() canvas = iface.mapCanvas() extent = layer.extent() #canvas = QgsMapCanvas() ms = canvas.mapSettings() myComposition = QgsComposition(ms) # uso plantilla if (extent.width() > extent.height()): tipo = 'h' myFile = os.path.join(os.path.dirname(__file__), 'template_h2.qpt') else: # plantilla vertical tipo = 'v' myFile = os.path.join(os.path.dirname(__file__), 'template_v2.qpt') #myFile = '/home/jose/Documentos/pyqgis/template_h.qpt' myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # Sustituir textos substitution_map = {'TITULO': u'TEMÁTICO','EDIFICIO':self.dlg.comboBoxEdificio.currentText(),'FECHA': time.strftime("%d/%m/%Y") ,'AUTOR': u'José Manuel Mira','ORGANISMO': 'Universidad de Alicante'} myComposition.loadFromTemplate(myDocument, substitution_map) # Zoom a capa myMap = myComposition.getComposerMapById(0) myExtent = iface.activeLayer().extent() myMap.setNewExtent(myExtent) # Save image salidaPNG = "mapa_" + layer.name() + "_" + time.strftime("%Y%m%d%H%M%S") + ".png" myImage = myComposition.printPageAsRaster(0) myImage.save(salidaPNG) # export PDF import time salidaPDF = "mapa_" + layer.name() + "_" + time.strftime("%Y%m%d%H%M%S") + ".pdf" myComposition.exportAsPDF(salidaPDF) QMessageBox.information(self.iface.mainWindow(), "Resultado", "Los mapas, " + salidaPNG + " y "+ salidaPDF+ " han sido creados exitosamente.")
def testPrintMapFromTemplate(self): """Test that we can get a map to render in the template.""" myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif') myFileInfo = QFileInfo(myPath) myRasterLayer = QgsRasterLayer(myFileInfo.filePath(), myFileInfo.completeBaseName()) myRenderer = QgsMultiBandColorRenderer( myRasterLayer.dataProvider(), 2, 3, 4 ) #mRasterLayer.setRenderer( rasterRenderer ) myPipe = myRasterLayer.pipe() assert myPipe.set( myRenderer ), "Cannot set pipe renderer" QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer]) myMapRenderer = QgsMapRenderer() myLayerStringList = [] myLayerStringList.append(myRasterLayer.id()) myMapRenderer.setLayerSet(myLayerStringList) myMapRenderer.setProjectionsEnabled(False) myComposition = QgsComposition(myMapRenderer) myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt') myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # now render the map, first zooming to the raster extents myMap = myComposition.getComposerMapById(0) myMessage = ('Map 0 could not be found in template %s', myFile) assert myMap is not None, myMessage myExtent = myRasterLayer.extent() myMap.setNewExtent(myExtent) myImagePath = os.path.join(str(QDir.tempPath()), 'template_map_render_python.png') myPageNumber = 0 myImage = myComposition.printPageAsRaster(myPageNumber) myImage.save(myImagePath) assert os.path.exists(myImagePath), 'Map render was not created.' # Not sure if this is a predictable way to test but its quicker than # rendering. myFileSize = QFileInfo(myImagePath).size() myExpectedFileSize = 100000 myMessage = ('Expected file size to be greater than %s, got %s' ' for %s' % (myExpectedFileSize, myFileSize, myImagePath)) assert myFileSize > myExpectedFileSize, myMessage
class StrongParser(): """ This class is used to load a strong lexicon in XML, parse it, and query infos. """ def __init__(self, lexicon="../lexicons/Strongs_EN/strongsgreek.xml"): "Takes the path to the lexicon as argument, or uses the default one." self._doc = QDomDocument() if not self._doc.setContent(QFile(lexicon)): print("ERROR: couldn't load lexicon. Please, try harder.'") self._entries = self._doc.documentElement()\ .namedItem("entries").childNodes() def getGreekUnicode(self, number): "Returns the greek lexical form in unicode for the given strong number." return self.getStrong(number).namedItem("greek")\ .toElement().attribute("unicode") def getStrong(self, number): """Returns a QDomNode for the given strong number. Used mainly internally.""" return self._entries.at(number - 1) def getDefinition(self, number): """Returns the word definition from the strong lexicon. Uses first the strong definition, and if not the KJV definition. """ s = self.getStrongDefinition(number) if not s: s = self.getKJVDefinition(number) return self.clean(s) def clean(self, s): "Used to clean some text: removes line breaks, and multiple spaces." s = s.replace("\n", " ") os = "" while s != os: os = s s = s.replace(" ", " ") return s.strip() def getStrongDefinition(self, number): "Returns the strong definition for the given strong number." return self.getStrong(number).namedItem("strongs_def")\ .toElement().text() def getKJVDefinition(self, number): "Returns the KJV definition for the given strong number." d = self.getStrong(number).namedItem("kjv_def").toElement().text() if d[:3] == ":--": d = d[3:] return self.clean(d)
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
def getlocalshows(self): ''' @rtype: list ''' shows = [] if self._storage.exists('shows'): showdirs = self._storage.listdir('shows') for showdir in showdirs: data = self._storage.getdata('shows/%s/en.xml' % showdir) if data != None: xml = QDomDocument() xml.setContent(data) showxml = xml.elementsByTagName('Series').at(0) newshow = show() newshow.id = unicode(QString(showxml.toElement().elementsByTagName('id').at(0).childNodes().at(0).toText().data())) newshow.name = unicode(QString(showxml.toElement().elementsByTagName('SeriesName').at(0).childNodes().at(0).toText().data())) newshow.description = unicode(QString(showxml.toElement().elementsByTagName('Overview').at(0).childNodes().at(0).toText().data())) newshow.image = unicode(QString(showxml.toElement().elementsByTagName('banner').at(0).firstChild().toText().data())) newshow.data = showxml.toElement() newshow.actors = unicode(QString(showxml.toElement().elementsByTagName('Actors').at(0).childNodes().at(0).toText().data())).strip('|').split('|') newshow.contentrating = unicode(QString(showxml.toElement().elementsByTagName('ContentRating').at(0).childNodes().at(0).toText().data())) firstaired = unicode(QString(showxml.toElement().elementsByTagName('FirstAired').at(0).childNodes().at(0).toText().data())) if firstaired != '': newshow.firstaired = datetime.fromtimestamp(mktime(strptime(firstaired, '%Y-%m-%d'))) else: newshow.firstaired = datetime.now() newshow.genre = unicode(QString(showxml.toElement().elementsByTagName('Genre').at(0).childNodes().at(0).toText().data())).strip('|').split('|') newshow.imdb = unicode(QString(showxml.toElement().elementsByTagName('IMDB_ID').at(0).childNodes().at(0).toText().data())) newshow.network = unicode(QString(showxml.toElement().elementsByTagName('Network').at(0).childNodes().at(0).toText().data())) rating = unicode(QString( showxml.toElement().elementsByTagName('Rating').at(0).childNodes().at(0).toText().data())) if rating != '': newshow.rating = float(rating) else: newshow.rating = 0.0 newshow.runtime = int(unicode(QString(showxml.toElement().elementsByTagName('Runtime').at(0).childNodes().at(0).toText().data()))) newshow.status = unicode(QString(showxml.toElement().elementsByTagName('Status').at(0).childNodes().at(0).toText().data())) shows.append(newshow) return shows
def saveTemplate(self): """ Creates and saves a new document template. """ #Validate if the user has specified the data source if self.selectedDataSource() == "": QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \ QApplication.translate("ComposerWrapper","Please specify the " \ "data source name for the document composition.")) return #If it is a new unsaved document template then prompt for the document name. docFile = self.documentFile() if docFile == None: docName,ok = QInputDialog.getText(self.composerView(), \ QApplication.translate("ComposerWrapper","Template Name"), \ QApplication.translate("ComposerWrapper","Please enter the template name below"), \ ) if ok and docName != "": templateDir = self._composerTemplatesPath() if templateDir == None: QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \ QApplication.translate("ComposerWrapper","Directory for document templates could not be found.")) return absPath = templateDir + "/" + docName + ".sdt" docFile= QFile(absPath) else: return docFileInfo = QFileInfo(docFile) if not docFile.open(QIODevice.WriteOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Could not save template file."), \ docFile.errorString() )) return templateDoc = QDomDocument() self._writeXML(templateDoc,docFileInfo.completeBaseName()) if docFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Error"), \ QApplication.translate("ComposerWrapper","Could not save template file.")) return docFile.close() self.setDocumentFile(docFile)
def 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
def read_stc(self, config_file_name): """ Reads provided config file :returns QDomDocument, QDomDocument.documentElement() :rtype tuple """ config_file_path = os.path.join(self.file_handler.localPath(), config_file_name) config_file_path = QFile(config_file_path) config_file = os.path.basename(config_file_name) if self.check_config_file_exists(config_file): self.document = QDomDocument() status, msg, line, col = self.document.setContent(config_file_path) if not status: error_message = u'Configuration file cannot be loaded: {0}'. \ format(msg) self.append_log(str(error_message)) raise ConfigurationException(error_message) self.doc_element = self.document.documentElement()
def ordered_expected_layers(self): """Get an ordered list of layers according to users input. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :return: An ordered list of layers following a structure. :rtype: list """ registry = QgsMapLayerRegistry.instance() layers = [] count = self.list_layers_in_map_report.count() for i in range(count): layer = self.list_layers_in_map_report.item(i) origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE) layers.append((FROM_ANALYSIS['key'], key, parent, None)) else: layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) layer = registry.mapLayer(layer_id) style_document = QDomDocument() error = '' layer.exportNamedStyle(style_document, error) layers.append( (FROM_CANVAS['key'], layer.name(), full_layer_uri(layer), style_document.toString())) return layers
def testQgsCentroidFillSymbolLayerV2(self): ''' Create a new style from a .sld file and match test ''' mTestName = QString('QgsCentroidFillSymbolLayerV2') mFilePath = QDir.toNativeSeparators( QString('%1/symbol_layer/%2.sld').arg(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 = QString(u'regular_star') mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#55aaff') mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#00ff00') mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def importFromXml(self, fn): f = QFile(fn) if not f.exists() or not f.open(QIODevice.ReadOnly): QMessageBox.warning(None, "Importing", "File not found.") return False if f.size() <= 0 or f.atEnd(): return False from PyQt4.QtXml import QDomDocument doc = QDomDocument(self.XML_TRANSF_DOC) (ok, errMsg, errLine, errCol) = doc.setContent(f, False) f.close() if not ok: QMessageBox.warning( None, "Importing", "Failed to parse file: line %s col %s" % (errLine, errCol)) return False root = doc.documentElement() if root.tagName() == self.XML_TRANSF_LIST_TAG: node = root.firstChild() while not node.isNull(): if node.toElement().tagName() == self.XML_TRANSF_TAG: t = Transformation() if t._fromNode(node): if t.inGrid != None: finfo = QFileInfo(t.inGrid) if not finfo.exists(): t.inGrid = finfo.fileName() t.saveData() node = node.nextSibling() return True
def getDomDef(self, layer): XMLDocument = QDomDocument("undo-layer") XMLMapLayers = QDomElement() XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = QDomElement() XMLMapLayer = XMLDocument.createElement("maplayer") layer.writeLayerXML(XMLMapLayer, XMLDocument) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) return XMLMapLayer
def loadProject(filename): # clear the map layer registry QgsMapLayerRegistry.instance().removeAllMapLayers() assert os.path.exists(filename), "project file does not exist: " + filename # load the project QgsProject.instance().read(QFileInfo(filename)) assert QgsMapLayerRegistry.instance().mapLayers( ), "no layers in map layer registry" doc = QDomDocument() with open(filename) as f: doc.setContent(f.read()) # map settings mapSettings = QgsMapSettings() mapSettings.readXML(doc.elementsByTagName("mapcanvas").at(0)) # visible layers layerIds = [] nodes = doc.elementsByTagName("legendlayer") for i in range(nodes.count()): elem = nodes.at(i).toElement().elementsByTagName("legendlayerfile").at( 0).toElement() if elem.attribute("visible") == "1": layerIds.append(elem.attribute("layerid")) mapSettings.setLayers(layerIds) # canvas color red = int( doc.elementsByTagName("CanvasColorRedPart").at(0).toElement().text()) green = int( doc.elementsByTagName("CanvasColorGreenPart").at(0).toElement().text()) blue = int( doc.elementsByTagName("CanvasColorBluePart").at(0).toElement().text()) mapSettings.setBackgroundColor(QColor(red, green, blue)) return mapSettings
def exportToXml(self, fn): from PyQt4.QtXml import QDomDocument doc = QDomDocument(self.XML_TRANSF_DOC) instr = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\" ") doc.appendChild(instr) root = doc.createElement(self.XML_TRANSF_LIST_TAG) doc.appendChild(root) for t in Transformation.getAll(): root.appendChild(t._toNode(doc)) f = QFile(fn) if not f.open(QIODevice.WriteOnly): return False xmlStream = QTextStream(f) xmlStream.setCodec(QTextCodec.codecForName("UTF-8")) xmlStream << doc.toString() return True
def createNodes(self, external=False): if not self.__dialog: self.createDialog() if external: root = QDomDocument() else: if not self.__dialog.root or not self.__dialog.node: self.createHeader() root = self.__dialog.root elem = self.__createDOMNodes(root) if external and hasattr(self.__dialog.root, "importNode"): rootDs = self.__dialog.root.importNode(elem, True) else: rootDs = elem return rootDs
def createHeader(self): if not self.__dialog: self.createDialog() if hasattr(self.__dialog, "view") and self.__dialog.view: self.__dialog.view.setModel(None) self.__datasource.document = QDomDocument() ## defined in NodeDlg class self.__dialog.root = self.__datasource.document processing = self.__dialog.root.createProcessingInstruction( "xml", "version='1.0'") self.__dialog.root.appendChild(processing) definition = self.__dialog.root.createElement(QString("definition")) self.__dialog.root.appendChild(definition) self.__dialog.node = self.__dialog.root.createElement( QString("datasource")) definition.appendChild(self.__dialog.node) return self.__dialog.node
def layer_style_to_xml(self,qgis_layer): ''' saves qgis style to the setting sheet :param qgis_layer: :return: ''' XMLDocument = QDomDocument("qgis_style") XMLStyleNode = XMLDocument.createElement("style") XMLDocument.appendChild(XMLStyleNode) error = None qgis_layer.writeSymbology(XMLStyleNode, XMLDocument, error) xmldoc = XMLDocument.toString(1) return xmldoc
def copyFromClipboard(self): if not self.__dialog: self.createDialog() clipboard = QApplication.clipboard() text = unicode(clipboard.text()) self.__datasource.document = QDomDocument() self.__dialog.root = self.__datasource.document if not self.__datasource.document.setContent( self.__datasource.repair(text)): raise ValueError("could not parse XML") else: if self.__dialog and hasattr(self.__dialog, "root"): self.__dialog.root = self.__datasource.document self.__dialog.node = DomTools.getFirstElement( self.__datasource.document, "datasource") if not self.__dialog.node: return self.setFromNode(self.__dialog.node) return True
def saveMailInfo(self): if self.total_mails != self.mailsTable.rowCount(): return if self.total_mails == 0 : return # Cache mails in xml file doc = QDomDocument() root = doc.createElement('mails') doc.appendChild(root) for i in range(self.mailsTable.rowCount()): item = self.mailsTable.cellWidget(i,0) mail = doc.createElement('mail') mail.setAttribute('UID', item.uid) mail.setAttribute('Message-ID', item.msg_id) mail.setAttribute('Sender', item.sender) mail.setAttribute('Subject', unicode(item.subject).encode('utf8')) mail.setAttribute('Date', item.date) mail.setAttribute('Cached', item.cached) root.appendChild(mail) mailbox_file = ACNT_DIR + self.email_id + '/%s.xml'%self.mailbox[:].replace('/', '_') with open(mailbox_file, 'w') as doc_file: doc_file.write(doc.toString())
def __add_layer_definition_file(self, file_name, root_group): """ shamelessly copied from https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp """ qfile = QFile(file_name) if not qfile.open(QIODevice.ReadOnly): return None doc = QDomDocument() if not doc.setContent(qfile): return None file_info = QFileInfo(qfile) QDir.setCurrent(file_info.absoluteDir().path()) root = QgsLayerTreeGroup() ids = doc.elementsByTagName('id') for i in xrange(0, ids.size()): id_node = ids.at(i) id_elem = id_node.toElement() old_id = id_elem.text() layer_name = old_id[:-17] date_time = QDateTime.currentDateTime() new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz') id_elem.firstChild().setNodeValue(new_id) tree_layer_nodes = doc.elementsByTagName('layer-tree-layer') for j in xrange(0, tree_layer_nodes.count()): layer_node = tree_layer_nodes.at(j) layer_elem = layer_node.toElement() if old_id == layer_elem.attribute('id'): layer_node.toElement().setAttribute('id', new_id) layer_tree_elem = doc.documentElement().firstChildElement( 'layer-tree-group') load_in_legend = True if not layer_tree_elem.isNull(): root.readChildrenFromXML(layer_tree_elem) load_in_legend = False layers = QgsMapLayer.fromLayerDefinition(doc) QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend) nodes = root.children() for node in nodes: root.takeChild(node) del root root_group.insertChildNodes(-1, nodes) return None
def test_constructor(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]) allAttr = False cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) self.assertEqual(cd.parent, None) self.assertEqual(cd.childNumber(), 0) self.assertEqual(cd.node.nodeName(), "#document") ci = cd.child(0) self.assertEqual(ci.parent, cd) 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)
def test_data(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]) allAttr = False cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) self.assertEqual(cm.headerData(0, Qt.Vertical), None) dt = cm.data(QModelIndex()) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '') for role in range(1, 5): dt = cm.data(cm.rootIndex, role) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '') dt = cm.data(cm.rootIndex) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '#document') dt = cm.data(cm.rootIndex, Qt.DisplayRole) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '#document')
def composers(projectfile, mapsettings): with open(projectfile) as f: xml = f.read() doc = QDomDocument() doc.setContent(xml) nodes = doc.elementsByTagName("Composer") for nodeid in range(nodes.count()): node = nodes.at(0).toElement() name = node.attribute("title") compositionnodes = doc.elementsByTagName("Composition") if compositionnodes.count() == 0: continue compositionelm = compositionnodes.at(0).toElement() comp = QgsComposition(mapsettings) comp.readXML(compositionelm, doc) atlaselm = node.firstChildElement("Atlas") comp.atlasComposition().readXML(atlaselm, doc) comp.addItemsFromXML(node, doc) comp.refreshZList() yield name, comp
def updateSqlLayer(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: layer = self._getSqlLayer(self.filter) if layer == None: return #self.layer.dataProvider().setDataSourceUri(layer.dataProvider().dataSourceUri()) #self.layer.dataProvider().reloadData() XMLDocument = QDomDocument("style") XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = XMLDocument.createElement("maplayer") self.layer.writeLayerXML(XMLMapLayer, XMLDocument) XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(layer.source()) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) self.layer.readLayerXML(XMLMapLayer) self.layer.reload() self.iface.actionDraw().trigger() self.iface.mapCanvas().refresh() self.iface.legendInterface().refreshLayerSymbology(layer) finally: QApplication.restoreOverrideCursor()
def mapaPlantillaPdf(self): if QgsMapLayerRegistry.instance().count() == 0: # detiene el script si el registro está vacio return None # definir directorio para guardar pdf y png directory = self.dlg.lineEditDirectory.text() if not directory: QMessageBox.critical( QWidget(), "ERROR", u"Indica el directorio para guardar los archivos") else: registry = QgsMapLayerRegistry.instance() layers = QgsMapLayerRegistry.instance().mapLayers() for name, layer in layers.iteritems(): print name, layer.type() # Add layer to map render myMapRenderer = QgsMapRenderer() lst = [layer.id()] myMapRenderer.setLayerSet(lst) myMapRenderer.setProjectionsEnabled(False) iface.mapCanvas().refresh() extent = layer.extent() ms = iface.mapCanvas().mapSettings() myComposition = QgsComposition(ms) # uso plantilla # NOTA: La referencia a las imágenes SVG en las templates hacen referencia a URL, no a rutas locales relativas o absolutas import platform if (extent.width() > extent.height()): tipo = 'h' if platform.system() == 'Linux': myFile = os.path.join(os.path.dirname(__file__), 'templates/template_h.qpt') if platform.system() == 'Windows': myFile = os.path.join(os.path.dirname(__file__), 'templates/template_h.qpt') if platform.system() == 'Darwin': myFile = os.path.join(os.path.dirname(__file__), 'templates/template_h.qpt') else: # plantilla vertical tipo = 'v' if platform.system() == 'Linux': myFile = os.path.join(os.path.dirname(__file__), 'templates/template_v.qpt') if platform.system() == 'Windows': myFile = os.path.join(os.path.dirname(__file__), 'templates/template_v.qpt') if platform.system() == 'Darwin': myFile = os.path.join(os.path.dirname(__file__), 'templates/template_v.qpt') myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # Sustituir textos substitution_map = { 'TITULO': u'TEMÁTICO', 'EDIFICIO': self.dlg.comboBoxEdificio.currentText(), 'FECHA': time.strftime("%d/%m/%Y"), 'AUTOR': u'José Manuel Mira', 'ORGANISMO': 'Universidad de Alicante' } #self.setAttribute(Qt.WA_DeleteOnClose) #para evitar warnings en time myComposition.loadFromTemplate(myDocument, substitution_map) # Definir extensión mapa y ajustar composición myMap = myComposition.getComposerMapById(0) extent = layer.extent() print "oldExtent:" print extent.xMinimum() print extent.yMinimum() print extent.xMaximum() print extent.yMaximum() rW = extent.width() rH = extent.height() print "rW: " + str(rW) print "rH: " + str(rH) if (tipo == 'v'): # recalcular extent print "es vertical" pH = 255 #alto en mm del recuadro del mapa pW = (rW * pH) / rH print "pW es: " + str(pW) # caso para edificios verticales muy largos (ej: derecho) # 200 son los mm del ancho del recuadro del mapa if (pW < 200): # recalcular xMax print "caso 1" xMin = extent.xMinimum() print "xMin es " + str(xMin) yMin = extent.yMinimum() yMax = extent.yMaximum() dXp = 200 - pW print "dXp es " + str(dXp) newXmax = ((rH * (pW + dXp)) / pH) + extent.xMinimum() print "newXmax es " + str(newXmax) # centrar mapa deltaX = (newXmax - extent.xMaximum()) / 2 print "deltaX es: " + str(deltaX) newExtent = QgsRectangle(xMin - deltaX, yMin, newXmax - deltaX, yMax) #newExtent = QgsRectangle(xMin,yMin,newXmax,yMax) print "newExtent:" print str(newExtent.xMinimum()) print newExtent.yMinimum() print newExtent.xMaximum() print newExtent.yMaximum() myMap.setNewExtent(newExtent) # caso para edificios verticales muy anchos (ej: 0005PB, EPS III -0014) else: # recalcular Ymin print "caso 2" xMin = extent.xMinimum() xMax = extent.xMaximum() yMax = extent.yMaximum() dYp = 255 - pH newYmin = extent.yMinimum() - ((rW * (pH + dYp)) / pW) newExtent = QgsRectangle(xMin, newYmin, xMax, yMax) myMap.setNewExtent(newExtent) if (tipo == 'h'): print "mapa horizontal" myExtent = layer.extent() myMap.setNewExtent(myExtent) pW = 235 pH = (pW * rH) / rW # caso 1: Edificios muy alargados if (pH < 203): newRH = (203 * rW) / pW xMin = extent.xMinimum() xMax = extent.xMaximum() yMin = extent.yMinimum() yMax = extent.yMaximum() deltaY = (newRH - rH) / 2 #(yMax - newYmin)/2 print "deltaY: " + str(deltaY) newExtent = QgsRectangle(xMin, yMin - deltaY, xMax, yMax + deltaY) myMap.setNewExtent(newExtent) # caso 2: edificios alargados, pero casi cuadrados. else: pH = 203 xMin = extent.xMinimum() xMax = extent.xMaximum() yMin = extent.yMinimum() yMax = extent.yMaximum() newRW = (235 * rH) / pH newXmax = xMin + newRW print "newXmax: " + str(newXmax) deltaX = (newRW - rW) / 2 print "deltaX: " + str(deltaX) newExtent = QgsRectangle(xMin - deltaX, yMin, newXmax - deltaX, yMax) myMap.setNewExtent(newExtent) # Save image salidaPNG = os.path.join( directory, "mapa_" + layer.name() + "_" + time.strftime("%Y%m%d%H%M%S") + ".png") myImage = myComposition.printPageAsRaster(0) myImage.save(salidaPNG) # export PDF salidaPDF = os.path.join( directory, "mapa_" + layer.name() + "_" + time.strftime("%Y%m%d%H%M%S") + ".pdf") myComposition.exportAsPDF(salidaPDF) QMessageBox.information( QWidget(), "Resultado", "Los mapas, " + salidaPNG + " y " + salidaPDF + " han sido creados exitosamente.") # Elimina la capa del registro ( y del canvas) QgsMapLayerRegistry.instance().removeMapLayers([layer.id()]) # Desactivar botones self.dlg.temaButton.setEnabled(False) self.dlg.tema2Button.setEnabled(False) self.dlg.labelButton.setEnabled(False) self.dlg.denoButton.setEnabled(False) self.dlg.mapaPlantillaButton.setEnabled(False)
def run(self, *args, **kwargs): """ :param templatePath: The file path to the user-defined template. :param entityFieldName: The name of the column for the specified entity which must exist in the data source view or table. :param entityFieldValue: The value for filtering the records in the data source view or table. :param outputMode: Whether the output composition should be an image or PDF. :param filePath: The output file where the composition will be written to. Applies to single mode output generation. :param dataFields: List containing the field names whose values will be used to name the files. This is used in multiple mode configuration. :param fileExtension: The output file format. Used in multiple mode configuration. :param data_source: Name of the data source table or view whose row values will be used to name output files if the options has been specified by the user. """ templatePath = args[0] entityFieldName = args[1] entityFieldValue = args[2] outputMode = args[3] filePath = kwargs.get("filePath", None) dataFields = kwargs.get("dataFields", []) fileExtension = kwargs.get("fileExtension", "") data_source = kwargs.get("data_source", "") templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): return False, QApplication.translate("DocumentGenerator", "Cannot read template file.") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerDS = ComposerDataSource.create(templateDoc) spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) composerDS.setSpatialFieldsConfig(spatialFieldsConfig) #Check if data source exists and return if it doesn't if not self.data_source_exists(composerDS): msg = QApplication.translate( "DocumentGenerator", u"'{0}' data source does not exist in the database." u"\nPlease contact your database " u"administrator.".format(composerDS.name())) return False, msg #Set file name value formatter self._file_name_value_formatter = EntityValueFormatter( name=data_source) #Register field names to be used for file naming self._file_name_value_formatter.register_columns(dataFields) #TODO: Need to automatically register custom configuration collections #Photo config collection ph_config_collection = PhotoConfigurationCollection.create( templateDoc) #Table configuration collection table_config_collection = TableConfigurationCollection.create( templateDoc) #Create chart configuration collection object chart_config_collection = ChartConfigurationCollection.create( templateDoc) #Load the layers required by the table composer items self._table_mem_layers = load_table_layers(table_config_collection) #Execute query dsTable, records = self._exec_query(composerDS.name(), entityFieldName, entityFieldValue) if records is None or len(records) == 0: return False, QApplication.translate( "DocumentGenerator", "No matching records in the database") """ Iterate through records where a single file output will be generated for each matching record. """ for rec in records: composition = QgsComposition(self._map_renderer) composition.loadFromTemplate(templateDoc) ref_layer = None #Set value of composer items based on the corresponding db values for composerId in composerDS.dataFieldMappings().reverse: #Use composer item id since the uuid is stripped off composerItem = composition.getComposerItemById(composerId) if not composerItem is None: fieldName = composerDS.dataFieldName(composerId) fieldValue = getattr(rec, fieldName) self._composeritem_value_handler( composerItem, fieldValue) # Extract photo information self._extract_photo_info(composition, ph_config_collection, rec) # Set table item values based on configuration information self._set_table_data(composition, table_config_collection, rec) # Refresh non-custom map composer items self._refresh_composer_maps( composition, spatialFieldsConfig.spatialFieldsMapping().keys()) # Create memory layers for spatial features and add them to the map for mapId, spfmList in spatialFieldsConfig.spatialFieldsMapping( ).iteritems(): map_item = composition.getComposerItemById(mapId) if not map_item is None: # #Clear any previous map memory layer #self.clear_temporary_map_layers() for spfm in spfmList: #Use the value of the label field to name the layer lbl_field = spfm.labelField() spatial_field = spfm.spatialField() if not spatial_field: continue if lbl_field: if hasattr(rec, spfm.labelField()): layerName = getattr(rec, spfm.labelField()) else: layerName = self._random_feature_layer_name( spatial_field) else: layerName = self._random_feature_layer_name( spatial_field) #Extract the geometry using geoalchemy spatial capabilities geom_value = getattr(rec, spatial_field) if geom_value is None: continue geom_func = geom_value.ST_AsText() geomWKT = self._dbSession.scalar(geom_func) #Get geometry type geom_type, srid = geometryType( composerDS.name(), spatial_field) #Create reference layer with feature ref_layer = self._build_vector_layer( layerName, geom_type, srid) if ref_layer is None or not ref_layer.isValid(): continue #Add feature bbox = self._add_feature_to_layer( ref_layer, geomWKT) bbox.scale(spfm.zoomLevel()) #Workaround for zooming to single point extent if ref_layer.wkbType() == QGis.WKBPoint: canvas_extent = self._iface.mapCanvas( ).fullExtent() cnt_pnt = bbox.center() canvas_extent.scale(1.0 / 32, cnt_pnt) bbox = canvas_extent #Style layer based on the spatial field mapping symbol layer symbol_layer = spfm.symbolLayer() if not symbol_layer is None: ref_layer.rendererV2().symbols( )[0].changeSymbolLayer(0, spfm.symbolLayer()) ''' Add layer to map and ensure its always added at the top ''' self.map_registry.addMapLayer(ref_layer) self._iface.mapCanvas().setExtent(bbox) self._iface.mapCanvas().refresh() # Add layer to map memory layer list self._map_memory_layers.append(ref_layer.id()) self._hide_layer(ref_layer) ''' Use root layer tree to get the correct ordering of layers in the legend ''' self._refresh_map_item(map_item) #Extract chart information and generate chart self._generate_charts(composition, chart_config_collection, rec) #Build output path and generate composition if not filePath is None and len(dataFields) == 0: self._write_output(composition, outputMode, filePath) elif filePath is None and len(dataFields) > 0: docFileName = self._build_file_name( data_source, entityFieldName, entityFieldValue, dataFields, fileExtension) # Replace unsupported characters in Windows file naming docFileName = docFileName.replace('/', '_').replace \ ('\\', '_').replace(':', '_').strip('*?"<>|') if not docFileName: return ( False, QApplication.translate( "DocumentGenerator", "File name could not be generated from the data fields." )) outputDir = self._composer_output_path() if outputDir is None: return ( False, QApplication.translate( "DocumentGenerator", "System could not read the location of the output directory in the registry." )) qDir = QDir() if not qDir.exists(outputDir): return (False, QApplication.translate( "DocumentGenerator", "Output directory does not exist")) absDocPath = u"{0}/{1}".format(outputDir, docFileName) self._write_output(composition, outputMode, absDocPath) return True, "Success" return False, "Document composition could not be generated"
def xmlDownloaded(self): """ populate the plugins object with the fetched data """ reply = self.sender() reposName = reply.property('reposName') if reply.error() != QNetworkReply.NoError: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mRepositories[reposName][ "error"] += "\n\n" + QCoreApplication.translate( "QgsPluginInstaller", "If you haven't cancelled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window." ) else: reposXML = QDomDocument() content = reply.readAll() # Fix lonely ampersands in metadata reposXML.setContent(content.replace("& ", "& ")) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement( "file_name").text().strip() if not fileName: fileName = QFileInfo( pluginNodes.item(i).firstChildElement( "download_url").text().strip().split("?") [0]).fileName() name = fileName.partition(".")[0] experimental = False if pluginNodes.item(i).firstChildElement( "experimental").text().strip().upper() in [ "TRUE", "YES" ]: experimental = True deprecated = False if pluginNodes.item(i).firstChildElement( "deprecated").text().strip().upper() in [ "TRUE", "YES" ]: deprecated = True icon = pluginNodes.item(i).firstChildElement( "icon").text().strip() if icon and not icon.startswith("http"): icon = "http://%s/%s" % (QUrl( self.mRepositories[reposName]["url"]).host(), icon) if pluginNodes.item(i).toElement().hasAttribute( "plugin_id"): plugin_id = pluginNodes.item(i).toElement().attribute( "plugin_id") else: plugin_id = None plugin = { "id": name, "plugin_id": plugin_id, "name": pluginNodes.item(i).toElement().attribute("name"), "version_available": pluginNodes.item(i).toElement().attribute("version"), "description": pluginNodes.item(i).firstChildElement( "description").text().strip(), "about": pluginNodes.item(i).firstChildElement( "about").text().strip(), "author_name": pluginNodes.item(i).firstChildElement( "author_name").text().strip(), "homepage": pluginNodes.item(i).firstChildElement( "homepage").text().strip(), "download_url": pluginNodes.item(i).firstChildElement( "download_url").text().strip(), "category": pluginNodes.item(i).firstChildElement( "category").text().strip(), "tags": pluginNodes.item(i).firstChildElement( "tags").text().strip(), "changelog": pluginNodes.item(i).firstChildElement( "changelog").text().strip(), "author_email": pluginNodes.item(i).firstChildElement( "author_email").text().strip(), "tracker": pluginNodes.item(i).firstChildElement( "tracker").text().strip(), "code_repository": pluginNodes.item(i).firstChildElement( "repository").text().strip(), "downloads": pluginNodes.item(i).firstChildElement( "downloads").text().strip(), "average_vote": pluginNodes.item(i).firstChildElement( "average_vote").text().strip(), "rating_votes": pluginNodes.item(i).firstChildElement( "rating_votes").text().strip(), "icon": icon, "experimental": experimental, "deprecated": deprecated, "filename": fileName, "installed": False, "available": True, "status": "not installed", "error": "", "error_details": "", "version_installed": "", "zip_repository": reposName, "library": "", "readonly": False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement( "qgis_minimum_version").text().strip() if not qgisMinimumVersion: qgisMinimumVersion = "2" qgisMaximumVersion = pluginNodes.item(i).firstChildElement( "qgis_maximum_version").text().strip() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99" #if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement( "disabled").text().strip().upper() in [ "TRUE", "YES" ]: if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion): #add the plugin to the cache plugins.addFromRepository(plugin) self.mRepositories[reposName]["state"] = 2 else: # no plugin metadata found self.mRepositories[reposName]["state"] = 3 if reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) == 200: self.mRepositories[reposName][ "error"] = QCoreApplication.translate( "QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options." ) else: self.mRepositories[reposName][ "error"] = QCoreApplication.translate( "QgsPluginInstaller", "Status code:") + " %d %s" % ( reply.attribute( QNetworkRequest.HttpStatusCodeAttribute), reply.attribute( QNetworkRequest.HttpReasonPhraseAttribute)) self.repositoryFetched.emit(reposName) # is the checking done? if not self.fetchingInProgress(): self.checkingDone.emit() reply.deleteLater()
def WriteProjectInfoXml(self): doc = QDomDocument() rootElem = doc.createElement("ProjectListClass") xmlDeclaration = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"") doc.appendChild(xmlDeclaration) elem = doc.createElement("ProjectCount") elem.appendChild(doc.createTextNode(str(len(self.ProjectsList)))) rootElem.appendChild(elem) for i in range(len(self.ProjectsList)): elem = doc.createElement("ProjectInfo") objNameElem = doc.createElement("Name") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Name)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Path") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Path)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Created") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Created)) elem.appendChild(objNameElem) objNameElem = doc.createElement("ProcedureName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].ProcedureName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("ProjName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].ProjName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Pt") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Pt)) elem.appendChild(objNameElem) objNameElem = doc.createElement("SubProjName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].SubProjName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("UserName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].UserName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("WorkspaceName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].WorkspaceName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("FullName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].FullName)) elem.appendChild(objNameElem) rootElem.appendChild(elem) doc.appendChild(rootElem) qFile = QFile(self.m_strProjectInfoFullName) if qFile.open(QFile.WriteOnly): textStream = QTextStream(qFile) doc.save(textStream, 4) qFile.close() # ###CRC file is created. with open(self.m_strProjectInfoFullName, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.flush() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(self.m_strProjectInfoFullName) path = string_0.left(string_0.length() - 3) + "crc" fileStream = open(path, 'wb') fileStream.write(bytes) fileStream.close() else: raise UserWarning, "can not open file:" + self.m_strProjectInfoFullName
def save(self, filename): doc = QDomDocument() root = doc.createElement("graph") doc.appendChild(root) items = doc.createElement("items") root.appendChild(items) # Items for index, item in enumerate(self.graph.items()): elem = item.save(doc.createElement("item")) elem.setAttribute("id", index) items.appendChild(elem) # Connections connections = doc.createElement("connections") root.appendChild(connections) for edge in self.graph.edges: connection = doc.createElement("connection") # Source source = doc.createElement("source") source.setAttribute( "id", self.graph.items().index(edge[0].parentObject())) source.setAttribute( "port", edge[0].parentObject().providesPorts.index(edge[0])) connection.appendChild(source) # Target target = doc.createElement("target") target.setAttribute( "id", self.graph.items().index(edge[1].parentObject())) target.setAttribute( "port", edge[1].parentObject().requiresPorts.index(edge[1])) connection.appendChild(target) connections.appendChild(connection) # Write f = QFile(filename) f.open(QIODevice.WriteOnly | QIODevice.Text) stream = QTextStream(f) stream << doc.toString() f.close() self.setModified(False)
def testQgsGraduatedSymbolRendererV2_2(self): """Test QgsGraduatedSymbolRendererV2: Adding /removing/editing classes """ # Create a renderer renderer = QgsGraduatedSymbolRendererV2() symbol = createMarkerSymbol() renderer.setSourceSymbol(symbol.clone()) symbol.setColor(QColor(255, 0, 0)) # Add class without start and end ranges renderer.addClass(symbol.clone()) renderer.addClass(symbol.clone()) renderer.updateRangeLabel(1, 'Second range') renderer.updateRangeLowerValue(1, 10.0) renderer.updateRangeUpperValue(1, 25.0) renderer.updateRangeRenderState(1, False) symbol.setColor(QColor(0, 0, 255)) renderer.updateRangeSymbol(1, symbol.clone()) # Add as a rangeobject symbol.setColor(QColor(0, 255, 0)) range = QgsRendererRangeV2(20.0, 25.5, symbol.clone(), 'Third range', False) renderer.addClassRange(range) # Add class by lower and upper renderer.addClassLowerUpper(25.5, 30.5) # (Update label for sorting tests) renderer.updateRangeLabel(3, 'Another range') self.assertEqual( dumpRangeLabels(renderer.ranges()), '(0.0 - 0.0,Second range,Third range,Another range,)', 'Added ranges labels not correct') self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'Added ranges lower/upper values not correct') # Check that clone function works renderer2 = renderer.clone() self.assertEqual(dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "clone function doesn't replicate renderer properly") # Check save and reload from Dom works doc = QDomDocument() element = renderer.save(doc) renderer2 = QgsGraduatedSymbolRendererV2.create(element) self.assertEqual( dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "Save/create from DOM doesn't replicate renderer properly") # Check sorting renderer.sortByLabel() self.assertEqual( dumpRangeList(renderer.ranges(), labelsOnly=True), '(0.0 - 0.0,Another range,Second range,Third range,)', 'sortByLabel not correct') renderer.sortByValue() self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'sortByValue not correct') renderer.sortByValue(Qt.DescendingOrder) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,10.0000-25.0000,0.0000-0.0000,)', 'sortByValue descending not correct') # Check deleting renderer.deleteClass(2) self.assertEqual(dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,0.0000-0.0000,)', 'deleteClass not correct') renderer.deleteAllClasses() self.assertEqual(len(renderer.ranges()), 0, "deleteAllClasses didn't delete all")
def xmlDownloaded(self, nr, state): """ populate the plugins object with the fetched data """ if not self.httpId.has_key(nr): return reposName = self.httpId[nr] if state: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = self.mRepositories[ reposName]["QPHttp"].errorString() else: repoData = self.mRepositories[reposName]["xmlData"] reposXML = QDomDocument() reposXML.setContent(repoData.data()) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement( "file_name").text().simplified() if not fileName: fileName = QFileInfo( pluginNodes.item(i).firstChildElement( "download_url").text().trimmed().split("?") [0]).fileName() name = fileName.section(".", 0, 0) name = unicode(name) experimental = False if pluginNodes.item(i).firstChildElement( "experimental").text().simplified().toUpper() in [ "TRUE", "YES" ]: experimental = True plugin = { "name": pluginNodes.item(i).toElement().attribute("name"), "version_avail": pluginNodes.item(i).toElement().attribute("version"), "desc_repo": pluginNodes.item(i).firstChildElement( "description").text().simplified(), "desc_local": "", "author": pluginNodes.item(i).firstChildElement( "author_name").text().simplified(), "homepage": pluginNodes.item(i).firstChildElement( "homepage").text().simplified(), "url": pluginNodes.item(i).firstChildElement( "download_url").text().simplified(), "experimental": experimental, "filename": fileName, "status": "not installed", "error": "", "error_details": "", "version_inst": "", "repository": reposName, "localdir": name, "read-only": False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement( "qgis_minimum_version").text().simplified() if not qgisMinimumVersion: qgisMinimumVersion = "0" # please use the tag below only if really needed! (for example if plugin development is abandoned) qgisMaximumVersion = pluginNodes.item(i).firstChildElement( "qgis_maximum_version").text().simplified() if not qgisMaximumVersion: qgisMaximumVersion = "2" #if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement( "disabled").text().simplified().toUpper() in [ "TRUE", "YES" ]: if compareVersions( QGIS_VER, qgisMinimumVersion) < 2 and compareVersions( qgisMaximumVersion, QGIS_VER) < 2: if QGIS_VER[0] == qgisMinimumVersion[0] or ( qgisMinimumVersion != "0" and qgisMaximumVersion != "2" ): # to be deleted #add the plugin to the cache plugins.addFromRepository(plugin) # set state=2, even if the repo is empty self.mRepositories[reposName]["state"] = 2 self.emit(SIGNAL("repositoryFetched(QString)"), reposName) # is the checking done? if not self.fetchingInProgress(): plugins.rebuild() self.saveCheckingOnStartLastDate() self.emit(SIGNAL("checkingDone()"))
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment and blunder from GNU Gama """ # gama-local OK? if self.gama_path is None: logging.error("GNU gama path is None") return (None, None) # fix = 0 free network fix = sum([1 for p, s in self.points if s == 'FIX']) adj = sum([1 for p, s in self.points if s == 'ADJ']) if adj == 0 or len(self.observations) < 2: # no unknowns or observations logging.error("GNU gama no unknowns or not enough observations") return (None, None) doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Ulyxes')) 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('sigma-act', 'apriori') 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 / 3600.0 * 10000.0)) points_observations.setAttribute( 'angle-stdev', str(math.sqrt(2) * self.stdev_angle / 3600.0 * 10000)) points_observations.setAttribute( 'zenith-angle-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) 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['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) 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['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) 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['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if 'station' in o: # station record sta = doc.createElement('obs') sta.setAttribute('from', o['station']) # instrument height ih = 0 if 'ih' in o: ih = o['ih'] points_observations.appendChild(sta) else: # observation th = 0 if 'th' in o: th = o['th'] if self.dimension == 2: # horizontal network if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o and 'v' in o: # horizontal distance hd = math.sin(o['v'].GetAngle()) * o['distance'] tmp = doc.createElement('distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o: tmp = doc.createElement('s-distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['distance'])) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) if 'v' in o: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['v'].GetAngle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension logging.error("GNU gama unknown dimension") return (None, None) # generate temp file name f = tempfile.NamedTemporaryFile() tmp_name = f.name f.close() f = open(tmp_name + '.xml', 'w') f.write(doc.toByteArray()) f.close() # run gama-local status = os.system(self.gama_path + ' ' + tmp_name + '.xml --text ' + tmp_name + '.txt --xml ' + tmp_name + 'out.xml') if status != 0: logging.error("GNU gama failed") return (None, None) xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource, xmlParser) # get adjusted coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted coordinates") return (None, None) 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': p = {} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p['id'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p['east'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p['north'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p['elev'] = float(ppp.firstChild().nodeValue()) # TODO standard deviation of coords to p res.append(p) adj_nodes = doc.elementsByTagName('observations') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted observations") return (None, None) blunder = {'std-residual': 0} adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() in [ 'direction', 'slope-distance', 'zenith-angle' ]: o = {'std-residual': 0} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'from': o['from'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'to': o['to'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'f': o['f'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'std-residual': o['std-residual'] = float(ppp.firstChild().nodeValue()) if o['std-residual'] > self.krit and \ o['std-residual'] > blunder['std-residual'] and \ o['f'] > 10: # extra observations ratio blunder = dict(o) xmlFile.close() # remove input xml and output xml os.remove(tmp_name + '.xml') os.remove(tmp_name + '.txt') os.remove(tmp_name + 'out.xml') return (res, blunder)
def override_component_template(component, template_path): """Override a default component with a new component with given template. :param component: Component as dictionary. :type component: dict :param template_path: Custom template path that will be used. :type template_path: str :returns: New report component. :rtype: dict """ copy_component = deepcopy(component) template_directory, template_filename = split(template_path) file_name, file_format = splitext(template_filename) if file_format[1:] != (QgisComposerComponentsMetadata.OutputFormat.QPT ) or (not exists(template_path)): return copy_component # we do the import here to avoid circular import when starting # up the plugin from safe.definitions.reports.components import ( map_report_component_boilerplate) custom_template_component = deepcopy(map_report_component_boilerplate) # we need to update several items in this component pdf_output_file = '{file_name}.pdf'.format(file_name=file_name) qpt_output_file = '{file_name}.qpt'.format(file_name=file_name) custom_template_component['key'] = file_name custom_template_component['template'] = template_path custom_template_component['output_path']['template'] = qpt_output_file custom_template_component['output_path']['map'] = pdf_output_file # we need to update the orientation of the custom template with open(custom_template_component['template']) as (template_file): template_content = template_file.read() document = QDomDocument() document.setContent(template_content) root_element = document.namedItem('Composer') composition_element = root_element.namedItem('Composition') all_orientations = [ landscape_map_report_description, portrait_map_report_description ] orientation = None if isinstance(root_element, QDomNode): paper_width = composition_element.attributes().namedItem( 'paperWidth').nodeValue() paper_height = composition_element.attributes().namedItem( 'paperHeight').nodeValue() for _orientation in all_orientations: if _orientation['width'] == int(paper_width) and ( _orientation['height'] == int(paper_height)): orientation = _orientation['orientation'] break # By default, the component is landscape oriented, So if we found that # the custom template is portrait, we need to delete the information about # orientation in the component because in the report metadata, if there is # no specification about the orientation, then they will set it # to portrait. if orientation == portrait_map_report_description['orientation']: custom_template_component['orientation'] = orientation del custom_template_component['page_width'] del custom_template_component['page_height'] copy_component['components'] = [custom_template_component] return copy_component
app = QgsApplication(sys.argv, True) QgsApplication.setPrefixPath("/usr", True) QgsApplication.initQgis() project_path = 'report_maps.qgs' template_path = 'owner_occupancy.qpt' canvas = QgsMapCanvas() canvas.resize(QSize(1450, 850)) #start = time.time() QgsProject.instance().read(QFileInfo(project_path)) #end = time.time() root = QgsProject.instance().layerTreeRoot() bridge = QgsLayerTreeMapCanvasBridge(root, canvas) bridge.setCanvasLayers() registry = QgsMapLayerRegistry.instance() template_file = file(template_path) template_content = template_file.read() template_file.close() document = QDomDocument() document.setContent(template_content) map_settings = canvas.mapSettings() composition = QgsComposition(map_settings) #start = time.time() composition.loadFromTemplate(document) #end = time.time() #create list of all layers currently in the map map_layers = [lyr for lyr in registry.mapLayers() if root.findLayer(lyr)]
def _getFile(self, layer): doc = QDomDocument() file = QFile(layer.source()) return None if not file.open(QIODevice.ReadOnly) else file
def add_layers_to_canvas_with_custom_orders(order, impact_function, iface=None): """Helper to add layers to the map canvas following a specific order. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :param order: Special structure the list of layers to add. :type order: list :param impact_function: The multi exposure impact function used. :type impact_function: MultiExposureImpactFunction :param iface: QGIS QGisAppInterface instance. :type iface: QGisAppInterface """ root = QgsProject.instance().layerTreeRoot() root.setVisible(False) # Make all layers hidden. group_analysis = root.insertGroup(0, impact_function.name) group_analysis.setVisible(Qt.Checked) group_analysis.setCustomProperty(MULTI_EXPOSURE_ANALYSIS_FLAG, True) # Insert layers in the good order in the group. for layer_definition in order: if layer_definition[0] == FROM_CANVAS['key']: style = QDomDocument() style.setContent(get_string(layer_definition[3])) layer = load_layer(layer_definition[2], layer_definition[1])[0] layer.importNamedStyle(style) QgsMapLayerRegistry.instance().addMapLayer(layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setVisible(Qt.Checked) else: if layer_definition[2] == impact_function.name: for layer in impact_function.outputs: if layer.keywords['layer_purpose'] == layer_definition[1]: QgsMapLayerRegistry.instance().addMapLayer( layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setVisible(Qt.Checked) try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass break else: for sub_impact_function in impact_function.impact_functions: # Iterate over each sub impact function used in the # multi exposure analysis. if sub_impact_function.name == layer_definition[2]: for layer in sub_impact_function.outputs: purpose = layer_definition[1] if layer.keywords['layer_purpose'] == purpose: QgsMapLayerRegistry.instance().addMapLayer( layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setVisible(Qt.Checked) try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass break if iface: iface.setActiveLayer(impact_function.analysis_impacted)