def saveUseData(self): # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument("usedata") usedata = dom_document.createElement("usedata") dom_document.appendChild(usedata) root = dom_document.createElement("openedprojects") usedata.appendChild(root) for i in self.OPENED_PROJECTS: tag = dom_document.createElement("project") root.appendChild(tag) t = dom_document.createTextNode(i) tag.appendChild(t) root = dom_document.createElement("settings") usedata.appendChild(root) s = 0 for key, value in self.SETTINGS.items(): if key == "InstalledInterpreters": continue tag = dom_document.createElement("key") root.appendChild(tag) t = dom_document.createTextNode(key + '=' + value) tag.appendChild(t) s += 1 usedata = dom_document.createElement("usedata") dom_document.appendChild(usedata) try: file = open(self.appPathDict["usedata"], "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close() except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) return self.settings["running"] = 'False' self.saveSettings() self.saveModulesForCompletion()
def run(self): self.found = [] if self.reg: txt = self.text else: txt = re.escape(self.text) if self.wo: txt = "\\b{0}\\b".format(txt) flags = re.UNICODE | re.LOCALE if not self.cs: flags |= re.IGNORECASE try: search = re.compile(txt, flags) except re.error as why: print(why) files = os.listdir(self.libraryDir) # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument() for i in range(len(files)): if self.stop: break file = os.path.abspath(os.path.join(self.libraryDir, files[i])) try: text = open(file, 'r').read() except: continue dom_document.setContent(text) documentElement = dom_document.documentElement() childElement = documentElement.firstChild().toElement() while childElement.isNull() is False: if childElement.nodeName() == 'comments': if (self.searchLoc == 0) or (self.searchLoc == 2): comments = childElement.firstChild().nodeValue() contains = search.search(comments) if contains: self.found.append(files[i]) elif childElement.nodeName() == 'code': if (self.searchLoc == 0) or (self.searchLoc == 1): code = childElement.firstChild().nodeValue() contains = search.search(code) if contains: if files[i] not in self.found: self.found.append(files[i]) childElement = childElement.nextSibling() self.searchSoFar.emit(i)
def createDomDocument(self): """ Create the QDomDocument from where to parse information. """ QtWidgets.QApplication.processEvents() LOGGER.info('Loading diagram: %s', self.path) if not fexists(self.path): raise DiagramNotFoundError('diagram not found: {0}'.format( self.path)) self.document = QtXml.QDomDocument() if not self.document.setContent(fread(self.path)): raise DiagramNotValidError( 'could not parse diagram from {0}'.format(self.path))
def deserialize_sld_doc( raw_sld_doc: QtCore.QByteArray, ) -> typing.Tuple[typing.Optional[QtXml.QDomElement], str]: """Deserialize SLD document gotten from GeoNode into a usable named layer element""" sld_doc = QtXml.QDomDocument() # in the line below, `True` means use XML namespaces and it is crucial for # QGIS to be able to load the SLD sld_loaded = sld_doc.setContent(raw_sld_doc, True) error_message = "Could not parse SLD document" named_layer_element = None if sld_loaded: root = sld_doc.documentElement() if not root.isNull(): sld_named_layer = root.firstChildElement("NamedLayer") if not sld_named_layer.isNull(): named_layer_element = sld_named_layer error_message = "" return named_layer_element, error_message
def run(self, path): """ Perform graph references document generation. :type path: str """ # CREATE THE DOCUMENT self.document = QtXml.QDomDocument() instruction = self.document.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8" standalone="no"') self.document.appendChild(instruction) # CREATE ROOT ELEMENT root = self.document.createElement('graphReferences') # GENERATE NODES for diagram in self.project.diagrams(): for node in diagram.nodes(): QtCore.QCoreApplication.processEvents() if node.isMeta(): iri = self.project.get_full_IRI( self.project.get_iri_of_node(node), None, node.remaining_characters) diagramElement = self.document.createElement('diagramName') diagramElement.appendChild(self.document.createTextNode(diagram.name)) xElement = self.document.createElement('x') xElement.appendChild(self.document.createTextNode(str(int(node.x())))) yElement = self.document.createElement('y') yElement.appendChild(self.document.createTextNode(str(int(node.y())))) wElement = self.document.createElement('w') wElement.appendChild(self.document.createTextNode(str(int(node.width())))) hElement = self.document.createElement('h') hElement.appendChild(self.document.createTextNode(str(int(node.height())))) nodeElement = self.document.createElement(node.type().realName.replace(' node', '')) nodeElement.setAttribute('name', iri) nodeElement.appendChild(diagramElement) nodeElement.appendChild(xElement) nodeElement.appendChild(yElement) nodeElement.appendChild(wElement) nodeElement.appendChild(hElement) root.appendChild(nodeElement) # APPEND THE GRAPH TO THE DOCUMENT self.document.appendChild(root) # GENERATE THE FILE fwrite(self.document.toString(2), path)
def convertToNode(self, data: Element) -> QtXml.QDomElement: """ Convert XML line to Node XML. When it's a calculatedField sends data to QSA of Node type. @param data. xml with related line info. @return Node with original data contents. """ # node = Node() doc = QtXml.QDomDocument() ele = doc.createElement("element") for k in data.keys(): attr_node = doc.createAttribute(k) attr_node.setValue(data.get(k) or "") ele.setAttributeNode(attr_node) return ele
def loadStyle(self, styleName, groupName): if styleName == "Default": if groupName == "Python": return PythonLexer.defaultStyle() elif groupName == "Css": return CssLexer.defaultStyle() elif groupName == "Xml": return XmlLexer.defaultStyle() elif groupName == "Html": return HtmlLexer.defaultStyle() else: pass style = {} stylePath = os.path.join(self.useData.appPathDict["stylesdir"], groupName, styleName + ".xml") # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument() file = open(stylePath, "r") x = dom_document.setContent(file.read()) file.close() rootElement = dom_document.documentElement() lexerElement = rootElement.firstChild().toElement() node = lexerElement.firstChild() while node.isNull() is False: tag = node.toElement() name = tag.text() font = tag.attribute("font") color = tag.attribute("color") size = int(tag.attribute("size")) bold = (tag.attribute("bold") == "True") italic = (tag.attribute("italic") == "True") paper = tag.attribute("paper") style[name] = [font, color, size, bold, italic, paper] node = node.nextSibling() return style
def install_acl(self, idacl: str) -> None: """ Create a new file "acl.xml" and store it replacing the previous one, if it exists. @param idacl Record identifier of the "flacls" table to use to create "acl.xml". """ doc = QtXml.QDomDocument("ACL") root = doc.createElement("ACL") doc.appendChild(root) name = doc.createElement("name") root.appendChild(name) text_node = doc.createTextNode(idacl) name.appendChild(text_node) qry = pnsqlquery.PNSqlQuery() qry.setTablesList("flacs") qry.setSelect("idac,tipo,nombre,iduser,idgroup,degrupo,permiso") qry.setFrom("flacs") qry.setWhere("idacl='%s'" % idacl) qry.setOrderBy("prioridad DESC, tipo") qry.setForwardOnly(True) if qry.exec_(): # step = 0 # progress = util.ProgressDialog(util.tr("Instalando control de acceso..."), None, q.size(), None, None, True) # progress.setCaption(util.tr("Instalando ACL")) # progress.setMinimumDuration(0) # progress.setProgress(++step) while qry.next(): self.make_rule(qry, doc) # progress.setProgress(++step) from pineboolib import application if application.PROJECT.conn_manager is None: raise Exception("Project is not connected yet") application.PROJECT.conn_manager.managerModules().setContent( "acl.xml", "sys", doc.toString())
def loadUseData(self): # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument() try: file = open(self.appPathDict["usedata"], "r") dom_document.setContent(file.read()) file.close() except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) return elements = dom_document.documentElement() node = elements.firstChild() settingsList = [] while node.isNull() is False: property = node.toElement() sub_node = property.firstChild() while sub_node.isNull() is False: sub_prop = sub_node.toElement() if node.nodeName() == "openedprojects": path = sub_prop.text() if os.path.exists(path): self.OPENED_PROJECTS.append(path) elif node.nodeName() == "settings": settingsList.append((tuple(sub_prop.text().split('=', 1)))) sub_node = sub_node.nextSibling() node = node.nextSibling() self.SETTINGS.update(dict(settingsList)) # for compatibility with older versions of PyCoder settingsKeys = self.SETTINGS.keys() if "MarkOperationalLines" not in settingsKeys: self.SETTINGS["MarkOperationalLines"] = "False" if "UI" not in settingsKeys: self.SETTINGS["UI"] = "Custom" self.loadKeymap() self.loadModulesForCompletion()
def setReportData( self, q: Optional[Union[FLDomNodeInterface, PNSqlQuery]] = None ) -> Optional[bool]: """Set data source to report.""" if isinstance(q, FLDomNodeInterface): return self.setFLReportData(q) if q is None: return None self.rd = QtXml.QDomDocument("KugarData") self.d_.rows_ = (self.rd.createDocumentFragment() ) # FIXME: Don't set the private from the public. self.d_.setQuery(q) q.setForwardOnly(True) if q.exec_() and q.next(): g = self.d_.qGroupDict_ if not g: while True: self.d_.addRowToReportData(0) if not q.next(): break else: vA: List[None] = [] for i in range(10): vA.append(None) ok = True while ok: self.d_.groupBy(len(g), vA) if not q.next(): ok = False data = self.rd.createElement("KugarData") data.appendChild(self.d_.rows_) self.rd.appendChild(data) self.d_.rows_.clear() self.initData() return True
def createDomDocument(self): """ Create the QDomDocument where to store project information. """ self.document = QtXml.QDomDocument() instruction = self.document.createProcessingInstruction( 'xml', 'version="1.0" encoding="UTF-8"') self.document.appendChild(instruction) blackbird = self.document.createElement('blackbird') blackbird.setAttribute('version', '1') self.document.appendChild(blackbird) projectName = self.document.createElement('name') projectName.appendChild( self.document.createTextNode('PROJECT NAME')) # TODO Modifica projectVersion = self.document.createElement('version') projectVersion.appendChild(self.document.createTextNode(self.version)) blackbird.appendChild(projectName) blackbird.appendChild(projectVersion)
def execute(self, filename): doc = QtXml.QDomDocument("Geometric Constraints") file = QtCore.QFile(filename) if not file.open(QtCore.QIODevice.ReadOnly): raise StandardError("File could not be opened") """ Skip the first line, because we need the root of the objects not the document. """ file.readLine() if not doc.setContent(file, False): file.close() raise StandardError("Could not initialize the file") file.close() root = doc.documentElement() if root.tagName() != "Objects": raise StandardError("Invalid document") self.prototypeManager.load(root) self.mainWindow.viewportManager.updateViewports()
def loadProperties(self, style_name, groupName): if style_name == "Default": properties = self.loadDefaultProperties() return properties # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument() path = os.path.join(self.useData.appPathDict["stylesdir"], groupName, style_name + ".xml") file = open(path, "r") dom_document.setContent(file.read()) file.close() properties = {} rootElement = dom_document.documentElement() propertyElement = rootElement.firstChild() propertyElement = propertyElement.nextSiblingElement().toElement() node = propertyElement.firstChild() while node.isNull() is False: tag = node.toElement() name = tag.text() background = tag.attribute("background") foreground = tag.attribute("foreground") properties[name] = [background, foreground] if name == "Calltips": properties[name].append(tag.attribute("highLight")) if name == "Number Margin": properties[name].append(tag.attribute("font")) properties[name].append(int(tag.attribute("size"))) bold = (tag.attribute("bold") == "True") properties[name].append(bold) italic = (tag.attribute("italic") == "True") properties[name].append(italic) node = node.nextSibling() return properties
def showExtraData(self, path): # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument() file = open(path, "r") dom_document.setContent(file.read()) file.close() documentElement = dom_document.documentElement() childElement = documentElement.firstChild().toElement() source = '' # for compatibilty with older versions of library files while childElement.isNull() is False: if childElement.nodeName() == 'comments': comments = childElement.firstChild().nodeValue() elif childElement.nodeName() == 'code': code = childElement.firstChild().nodeValue() elif childElement.nodeName() == 'source': source = childElement.firstChild().nodeValue() childElement = childElement.nextSibling() self.commentViewer.setPlainText(comments) self.codeViewer.setText(code) self.sourceLine.setText(source)
def createDomDocument(self): """ Create the QDomDocument where to store project information. """ self.document = QtXml.QDomDocument() instruction = self.document.createProcessingInstruction( 'xml', 'version="1.0" encoding="UTF-8"') self.document.appendChild(instruction) graphol = self.getDomElement('graphol') graphol.setAttribute('version', '3') self.document.appendChild(graphol) project = self.getDomElement('project') project.setAttribute('name', self.project.name) project.setAttribute('version', self.project.version) graphol.appendChild(project) ontologyEl = self.getOntologyDomElement() project.appendChild(ontologyEl) diagramsEl = self.getDiagramsDomElement() project.appendChild(diagramsEl)
def loadKeymap(self): if self.settings["firstRun"] == "True": self.CUSTOM_SHORTCUTS = self.DEFAULT_SHORTCUTS return # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument() try: file = open(self.appPathDict["keymap"], "r") x = dom_document.setContent(file.read()) file.close() except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) return elements = dom_document.documentElement() node = elements.firstChild() while node.isNull() is False: property = node.toElement() sub_node = property.firstChild() group = node.nodeName() while sub_node.isNull() is False: sub_prop = sub_node.toElement() tag = sub_prop.toElement() name = tag.tagName() shortcut = tag.attribute("shortcut") if group == "Editor": keyValue = int(tag.attribute("value")) self.CUSTOM_SHORTCUTS[ group][name] = [shortcut, keyValue] else: self.CUSTOM_SHORTCUTS[ group][name] = shortcut sub_node = sub_node.nextSibling() node = node.nextSibling()
def __init__(self, document: (QtXml.QDomDocument, type(None)) = None, parent=None): ''' Constructor for GenericDomModel Arguments: document -- QtXml.QDomDocument; the actual DOM document that becomes the root item of this model -- can be empty (i.e. a default constructed QtXml.QDomDocument); optional, default is None, which means in effect the instance will contain an empty QtXml.QDomDocument parent -- QtCore.QObject parent object (optional, default is None) ''' super().__init__(parent) if document is None: document = QtXml.QDomDocument() self.domDocument = document # also set the root item as the DOM document (which, again, it might be empty) self.rootItem = DomItem(self.domDocument, 0) # row is 0 because root has no siblings
if len(sys.argv) == 1: print("Error: You have to specify the file to check") sys.exit(1) for fileIndex in range(1, len(sys.argv)): path = sys.argv[fileIndex] print("Processing " + path) xmlFile = QtCore.QFile(path) if not xmlFile.exists(): print("Error: File {} does not exist".format(path)) else: if not xmlFile.open(QtCore.QIODevice.ReadOnly): print("Error: Could not open {} for reading".format(path)) else: doc = QtXml.QDomDocument() doc.setContent(xmlFile.readAll()) root = doc.documentElement() if root.tagName() != "map": print( "Error: The map description file should begin with the map tag" ) else: imagePath = QtCore.QFileInfo(path).absolutePath( ) + "/" + root.firstChildElement("mapFile").text() if not QtCore.QFile.exists(imagePath): print( "Error: Map file {} does not exist".format(imagePath)) sys.exit(2)
import sys from PyQt5 import QtGui, QtSvg, QtXml, QtCore from PyQt5.QtWidgets import QApplication, QWidget, QLabel doc = QtXml.QDomDocument("animated_123") file = QtCore.QFile("animated_123.svg") #if (not file.open(QtCore.QIODevice.ReadOnly)): doc.setContent(file) ## file.close(); # return; file.close() docElem = doc.documentElement() N = docElem #.firstChild(); n = N #n.toElement().QIt = QtGui.QStandardItem("Godfather") depth = 0 model = QtGui.QStandardItemModel() curIt = QtGui.QStandardItem("My File") model.setItem(0, curIt) #self.svgTreeView.setModel(model) while (not n.isNull()): e = n.toElement() # try to convert the node to an element. if (not n.isNull()): print("." * depth + e.tagName()) nextIt = QtGui.QStandardItem(e.tagName()) curIt.appendRow(nextIt) print("Parent did %swork" % ("not " if nextIt.parent() == curIt else ""))
def reportData(self): return FLDomNodeInterface.nodeInterface( self.rd if self.rd else QtXml.QDomDocument() )
def reportTemplate(self): return FLDomNodeInterface.nodeInterface( self.rt if self.rt else QtXml.QDomDocument() )
def addToLibrary(self, editorTabWidget): if editorTabWidget.getSource().strip() == '': message = QtWidgets.QMessageBox.warning( self, "Library Add", "Source code must be present to add to library!") return add = LibraryAddDialog(editorTabWidget, self) if add.accepted: path = os.path.join(self.useData.appPathDict["librarydir"], add.name) if os.path.exists(path): mess = "File already exists in Library.\n\nReplace it?" reply = QtWidgets.QMessageBox.warning( self, "Library Add", mess, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: pass else: return try: # FIXME QtXml is no longer supported. dom_document = QtXml.QDomDocument("snippet") root = dom_document.createElement("snippet") dom_document.appendChild(root) tag = dom_document.createElement('comments') root.appendChild(tag) t = dom_document.createCDATASection( add.commentEntry.toPlainText()) tag.appendChild(t) tag = dom_document.createElement('source') root.appendChild(tag) if add.entireModuleButton.isChecked(): t = dom_document.createCDATASection("Main") tag.appendChild(t) else: t = dom_document.createCDATASection( editorTabWidget.getTabName()) tag.appendChild(t) tag = dom_document.createElement('code') root.appendChild(tag) if add.entireModuleButton.isChecked(): t = dom_document.createCDATASection( editorTabWidget.getSource()) else: t = dom_document.createCDATASection( editorTabWidget.focusedEditor().selectedText()) tag.appendChild(t) file = open(path, "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close() self.loadLibrary() self.close() except Exception as err: message = QtWidgets.QMessageBox.warning( self, "Library Add", "Adding to Library failed!\n\n{0}".format(str(err)))
def load_xml(self, fs_filename): """ load xml airspace file """ # check input # assert f_model # read coordinates ls_filename = ":/data/" + fs_filename + ".xml" l_data_file = QtCore.QFile(ls_filename) assert l_data_file is not None l_data_file.open(QtCore.QIODevice.ReadOnly) if not l_data_file.isOpen(): # logger l_log = logging.getLogger("airspace::load_xml") l_log.setLevel(logging.NOTSET) l_log.fatal("<E01: failed to open {}".format(ls_filename)) # abend sys.exit(1) # FIXME QtXml is no longer supported. l_xml_doc = QtXml.QDomDocument("airspace") assert l_xml_doc is not None if not l_xml_doc.setContent(l_data_file): l_data_file.close() # logger l_log = logging.getLogger("airspace::load_xml") l_log.setLevel(logging.NOTSET) l_log.fatal("<E02: failed to parse {}".format(ls_filename)) # abend sys.exit(1) l_data_file.close() l_doc_elem = l_xml_doc.documentElement() assert l_doc_elem is not None self._f_variation, lv_ok = l_doc_elem.attribute( QString("variation"), QString("0")).toDouble() self._f_elevation, lv_ok = l_doc_elem.attribute( QString("elevation"), QString("0")).toDouble() l_node = l_doc_elem.firstChild() assert l_node is not None while not l_node.isNull(): l_element = l_node.toElement() assert l_element is not None if not l_element.isNull(): self._parse_dom_element(l_element) l_node = l_node.nextSibling() assert l_node is not None
def printAction(self): #export tmp imgs of qwebviews for imgFile,webview in {"tmpSV.png":self.view.SV,"tmpBE.png":self.view.BE}.items(): painter = QtGui.QPainter() img = QtGui.QImage(webview.size().width(), webview.size().height(), QtGui.QImage.Format_ARGB32) painter.begin(img) webview.page().mainFrame().render(painter) painter.end() img.save(os.path.join(self.dirPath,"tmp",imgFile)) # portion of code from: http://gis.stackexchange.com/questions/77848/programmatically-load-composer-from-template-and-generate-atlas-using-pyqgis # Load template myLayout = core.QgsLayout(core.QgsProject.instance()) myFile = os.path.join(os.path.dirname(__file__), 'res','go2SV_A4.qpt') myTemplateFile = open(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QtXml.QDomDocument() myDocument.setContent(myTemplateContent) myLayout.loadFromTemplate(myDocument,core.QgsReadWriteContext()) #MAP mapFrame = sip.cast(myLayout.itemById('MAP'),core.QgsLayoutItemMap) mapFrameAspectRatio = mapFrame.extent().width()/mapFrame.extent().height() newMapFrameExtent = core.QgsRectangle() actualPosition = self.transformToCurrentSRS(core.QgsPointXY (float(self.actualPOV['lon']),float(self.actualPOV['lat']))) centerX = actualPosition.x() centerY = actualPosition.y() if float(self.actualPOV['heading']) > 360: head = float(self.actualPOV['heading'])-360 else: head = float(self.actualPOV['heading']) newMapFrameExtent.set(centerX - self.iface.mapCanvas().extent().height()*mapFrameAspectRatio/2,centerY - self.iface.mapCanvas().extent().height()/2,centerX + self.iface.mapCanvas().extent().height()*mapFrameAspectRatio/2,centerY + self.iface.mapCanvas().extent().height()/2) mapFrame.setExtent(newMapFrameExtent) mapFrame.setMapRotation(self.canvas.rotation()) mapFrame.redraw() #CURSOR mapFrameCursor = sip.cast(myLayout.itemById('CAMERA'),core.QgsLayoutItemPicture) mapFrameCursor.setPicturePath(os.path.join(os.path.dirname(__file__),'res', 'camera.svg')) mapFrameCursor.setItemRotation(head+self.canvas.rotation(), adjustPosition=True) #NORTH mapFrameNorth = sip.cast(myLayout.itemById('NORTH'),core.QgsLayoutItemPicture) mapFrameNorth.setPicturePath(os.path.join(os.path.dirname(__file__),'res', 'NorthArrow_01.svg')) mapFrameNorth.setPictureRotation(self.canvas.rotation()) #STREETVIEW AND GM PICS if self.view.SV.isHidden(): LargePic = os.path.join(os.path.dirname(__file__),'tmp', 'tmpBE.png') SmallPic = os.path.join(os.path.dirname(__file__),'tmp', 'tmpSV.png') else: LargePic = os.path.join(os.path.dirname(__file__),'tmp', 'tmpSV.png') SmallPic = os.path.join(os.path.dirname(__file__),'tmp', 'tmpBE.png') SVFrame = sip.cast(myLayout.itemById('LARGE'),core.QgsLayoutItemPicture) SVFrame.setPicturePath(LargePic) BEFrame = sip.cast(myLayout.itemById('SMALL'),core.QgsLayoutItemPicture) BEFrame.setPicturePath(SmallPic) #DESCRIPTION DescFrame = sip.cast(myLayout.itemById('DESC'),core.QgsLayoutItemLabel) info = self.snapshotOutput.getGeolocationInfo() DescFrame.setText("LAT: %s\nLON: %s\nHEAD: %s\nADDRESS:\n%s" % (info['lat'], info['lon'], head, info['address'])) workDir = core.QgsProject.instance().readPath("./") fileName, filter = QtWidgets.QFileDialog().getSaveFileName(None,"Save pdf", workDir, "*.pdf"); if fileName: if QtCore.QFileInfo(fileName).suffix() != "pdf": fileName += ".pdf" exporter = core.QgsLayoutExporter(myLayout) exporter.exportToPdf(fileName,core.QgsLayoutExporter.PdfExportSettings())
def run(self, path): """ Perform GraphML document generation. :type path: str """ LOGGER.info('Exporting diagram %s to %s', self.diagram.name, path) # 1) CREATE THE DOCUMENT self.document = QtXml.QDomDocument() instruction = self.document.createProcessingInstruction( 'xml', 'version="1.0" encoding="UTF-8"') self.document.appendChild(instruction) # 2) CREATE ROOT ELEMENT root = self.document.createElement('graphml') root.setAttribute('xmlns', 'http://graphml.graphdrawing.org/xmlns') root.setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance') root.setAttribute('xmlns:y', 'http://www.yworks.com/xml/graphml') root.setAttribute('xmlns:yed', 'http://www.yworks.com/xml/yed/3') root.setAttribute( 'xsi:schemaLocation', 'http://graphml.graphdrawing.org/xmlns ' 'http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd') # 3) CREATE ELEMENT KEYS key = self.document.createElement('key') key.setAttribute('for', 'node') key.setAttribute('id', GraphMLDiagramExporter.KeyNode) key.setAttribute('yfiles.type', 'nodegraphics') root.appendChild(key) key = self.document.createElement('key') key.setAttribute('for', 'edge') key.setAttribute('id', GraphMLDiagramExporter.KeyEdge) key.setAttribute('yfiles.type', 'edgegraphics') root.appendChild(key) key = self.document.createElement('key') key.setAttribute('attr.name', K_URL) key.setAttribute('attr.type', 'string') key.setAttribute('for', 'node') key.setAttribute('id', GraphMLDiagramExporter.KeyUrl) root.appendChild(key) key = self.document.createElement('key') key.setAttribute('attr.name', K_DESCRIPTION) key.setAttribute('attr.type', 'string') key.setAttribute('for', 'node') key.setAttribute('id', GraphMLDiagramExporter.KeyDescription) root.appendChild(key) # 4) CREATE THE GRAPH NODE graph = self.document.createElement('graph') graph.setAttribute('edgedefault', 'directed') graph.setAttribute('id', 'G') # 5) GENERATE NODES for node in self.diagram.nodes(): if node.type() not in self.missing: func = self.exportFuncForItem[node.type()] graph.appendChild(func(node)) # 6) GENERATE EDGES for edge in self.diagram.edges(): if edge.source.type() not in self.missing and edge.target.type( ) not in self.missing: func = self.exportFuncForItem[edge.type()] graph.appendChild(func(edge)) # 7) APPEND THE GRAPH TO THE DOCUMENT self.document.appendChild(root) root.appendChild(graph) # 8) GENERATE THE FILE fwrite(self.document.toString(2), path)
def save(self, file): filename, file_extention = file if file_extention == "SVG files (*.svg)": title = self.tr('Save in this format ?') text = self.tr( "If you save in this format, only certain properties will be retained (such as shapes and colors, not line and fill styles)" ) msgbox = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, title, text) msgbox.setWindowIcon(self.windowIcon()) no_button = msgbox.addButton(self.tr('No'), QtWidgets.QMessageBox.NoRole) yes_button = msgbox.addButton(self.tr('Yes'), QtWidgets.QMessageBox.YesRole) msgbox.setDefaultButton(no_button) msgbox.exec() if (msgbox.clickedButton() == yes_button): filesave = QtCore.QFile(filename) filesave.resize(0) if filesave.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.ReadOnly): generator = QtSvg.QSvgGenerator() generator.setFileName(filename) generator.setTitle("Simply Paint") generator.setDescription("Filed created by Simply Paint.") generator.setSize( QtCore.QSize(self.scene.width(), self.scene.height())) generator.setViewBox( QtCore.QRect(0, 0, self.scene.width(), self.scene.height())) painter = QtGui.QPainter() painter.begin(generator) self.scene.render(painter) painter.end() doc = QtXml.QDomDocument() doc.setContent(filesave) filesave.close() filesave = QtCore.QFile(filename) fileStream = QtCore.QTextStream(filesave) if filesave.open(QtCore.QIODevice.WriteOnly): SVGNode = doc.lastChild() boardNode = SVGNode.lastChild() groupFormNodeList = boardNode.childNodes() count = groupFormNodeList.length() for i in range(count): groupFormNode = groupFormNodeList.item(count - i - 1) if not groupFormNode.hasChildNodes(): boardNode.removeChild(groupFormNode) groupFormNodeList = boardNode.childNodes() doc.save(fileStream, 2) filesave.close() self.srcfile = file self.scene.setSceneChanged(False) if file_extention == "JSON files (*.json)": filesave = QtCore.QFile(filename) filesave.resize(0) if filesave.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.ReadOnly): s = SaveOpen() s.save(filesave, self.scene.items()) filesave.close() self.srcfile = file
def toXml( cls, obj_: QtCore.QObject, include_children: bool = True, include_complex_types: bool = False, ) -> QtXml.QDomDocument: """ Convert an object to xml. @param obj_. Object to be processed @param include_children. Include children of the given object @param include_complex_types. Include complex children @return xml of the given object """ xml_ = QtXml.QDomDocument() if not obj_: return xml_ e = xml_.createElement(type(obj_).__name__) e.setAttribute("class", type(obj_).__name__) xml_.appendChild(e) _meta = obj_.metaObject() i = 0 # _p_properties = [] for i in range(_meta.propertyCount()): mp = _meta.property(i) # if mp.name() in _p_properties: # i += 1 # continue # _p_properties.append(mp.name()) val = getattr(obj_, mp.name(), None) try: val = val() except Exception: pass if val is None: i += 1 continue val = str(val) if not val and not include_complex_types: i += 1 continue e.setAttribute(mp.name(), val) i += 1 if include_children: for child in obj_.children(): itd = cls.toXml(child, include_children, include_complex_types) xml_.firstChild().appendChild(itd.firstChild()) return xml_
def run(self,path): project = self.diagram.project # 1) CREATE THE DOCUMENT self.document = QtXml.QDomDocument() instruction = self.document.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8" standalone="no"') self.document.appendChild(instruction) # 2) CREATE ROOT ELEMENT root = self.document.createElement('graphReferences') node_diagrams_dict = dict() for diagram in project.diagrams(): for node in diagram.nodes(): if node.isMeta():#if node.type() not in self.missing: full_IRI = project.get_full_IRI(project.get_iri_of_node(node), None, node.remaining_characters) if full_IRI not in node_diagrams_dict.keys(): node_diagrams_dict[full_IRI] = [] node_diagrams_dict[full_IRI].append(node.type().realName.replace(' node','')) node_diagrams_dict[full_IRI].append(diagram.name) node_diagrams_dict[full_IRI].append(str(int(node.pos().x()))) node_diagrams_dict[full_IRI].append(str(int(node.pos().y()))) node_diagrams_dict[full_IRI].append(str(int(node.width()))) node_diagrams_dict[full_IRI].append(str(int(node.height()))) # 3) GENERATE NODES for node_full_text in node_diagrams_dict.keys(): value = node_diagrams_dict[node_full_text] for i in range(1,len(value)-4,5): diag = value[i] x = value[i+1] y = value[i+2] w = value[i+3] h = value[i+4] diag_to_append = self.document.createElement('diagramName') diag_to_append.appendChild(self.document.createTextNode(diag)) x_to_append = self.document.createElement('x') x_to_append.appendChild(self.document.createTextNode(x)) y_to_append = self.document.createElement('y') y_to_append.appendChild(self.document.createTextNode(y)) w_to_append = self.document.createElement('w') w_to_append.appendChild(self.document.createTextNode(w)) h_to_append = self.document.createElement('h') h_to_append.appendChild(self.document.createTextNode(h)) node_to_append = self.document.createElement(value[0]) node_to_append.setAttribute('name', node_full_text) node_to_append.appendChild(diag_to_append) node_to_append.appendChild(x_to_append) node_to_append.appendChild(y_to_append) node_to_append.appendChild(w_to_append) node_to_append.appendChild(h_to_append) root.appendChild(node_to_append) # 4) APPEND THE GRAPH TO THE DOCUMENT self.document.appendChild(root) # 5) GENERATE THE FILE fwrite(self.document.toString(2), path) self.success = True
def activateModule(self, idm=None) -> None: """Initialize module.""" if not idm: if self.sender(): idm = self.sender().objectName() if idm is None: return self.writeStateModule() w = None if idm in self.db().managerModules().listAllIdModules(): w = self._dict_main_widgets[ idm] if idm in self._dict_main_widgets.keys() else None if w is None: w = self.db().managerModules().createUI(file_name="%s.ui" % idm) if not w: return if w.findChild(pncore.PNCore): doc = QtXml.QDomDocument() ui_file = "%s.ui" % idm cc = self.db().managerModules().contentCached(ui_file) if not cc or not doc.setContent(cc): if cc: logger.warning("No se ha podido cargar %s" % (ui_file)) return None root = doc.documentElement().toElement() conns = root.namedItem("connections").toElement() connections = conns.elementsByTagName("connection") for i in range(connections.length()): itn = connections.at(i).toElement() sender = itn.namedItem("sender").toElement().text() signal = itn.namedItem("signal").toElement().text() if signal in ["activated()", "triggered()"]: signal = "triggered()" receiver = itn.namedItem("receiver").toElement().text() slot = itn.namedItem("slot").toElement().text() if receiver == "pncore" and signal == "triggered()": ac = cast(QtWidgets.QAction, w.findChild(QtWidgets.QAction, sender)) if ac is not None and sender in application.PROJECT.actions.keys( ): sl = getattr( application.PROJECT.actions[sender], slot[0:slot.find("(")], None, ) ac.triggered.connect(sl) else: logger.warning("Action %s not found", sender) w.setWindowModality(QtCore.Qt.WindowModal) self._dict_main_widgets[idm] = w w.setObjectName(idm) if flapplication.aqApp.acl_: flapplication.aqApp.acl_.process(w) self.setMainWidget(w) flapplication.aqApp.call("%s.init()" % idm, []) w.removeEventFilter(self) self.db().managerModules().setActiveIdModule(idm) self.setMainWidget(w) self.initMainWidget() self.showMainWidget(w) w.installEventFilter(self) return if not w: self.db().managerModules().setActiveIdModule("") else: self.db().managerModules().setActiveIdModule(idm) self.setMainWidget(w) self.showMainWidget(w)
def _set_data_(self, data: (xml.etree.ElementTree.Element, xml.dom.minidom.Document, QtXml.QDomNode, QtXml.QDomDocument, str, type(None)), *args, **kwargs): ''' Set the xml document 'data' as the DOM document of the underlying DOM _docModel_ associated with the tree view ''' try: if isinstance(data, str): document = QtXml.QDomDocument() # Create an empty DOM document # the populate it with the string data. # At this point, 'data' must be a string # representation of an XML document # otherwise setContent will return False. # NOTE: this does not check whether 'data' # contains a well-formed XML document -- I think... if document.setContent(data, self.processNS): self._set_doc_( document) # if the DOM document has been successfully # populated by the data str, then set it as # the document to be shown self._data_ = data elif isinstance(data, QtXml.QDomDocument) and not data.isNull(): self._set_doc_(data) self._data_ = data elif isinstance(data, QtXml.QDomNode) and not data.isNull(): if data.isDocument(): self._set_doc_(data.toDocument()) else: # deep import of a non-document QDomNode document = QtXml.QDomDocument() document.importNode(data, True) self._set_doc_(document) self._data_ = data elif isinstance(data, xml.dom.minidom.Document): document = QtXml.QDomDocument() if document.setContent(data.toprettyxml(), self.processNS): self._set_doc_(document) self._data_ = data elif isinstance(data, xml.etree.ElementTree.Element): document = QtXml.QDomDocument() docString = ET.tostring(data, encoding="unicode") if document.setContent(docString, self.processNS): self._set_doc_(document) self._data = data #print(docString) #self._set_data_(docString) except Exception as e: traceback.print_exc() if kwargs.get("show", True): self.activateWindow()