def set_layer_symbology(layer, symbology): if symbology is not None: doc = QDomDocument("qgis") doc.setContent(symbology) errorMsg = '' ctx = QgsReadWriteContext() layer.readSymbology(doc.firstChildElement("qgis"), errorMsg, ctx)
def colorRampToString( self, ramp ): if ramp is None: return ''; d=QDomDocument() d.appendChild(QgsSymbolLayerUtils.saveColorRamp('ramp',ramp,d)) rampdef=d.toString() return rampdef
def contentStatic(self, n): str_ret = FLStaticLoader.content(n, self.staticBdInfo_) if str_ret: from pineboolib.fllegacy.FLUtil import FLUtil util = FLUtil() sha = util.sha1(str_ret) if n in self.dictKeyFiles.keys(): s = self.dictKeyFiles[n] if self.dictKeyFiles and s == sha: return None elif self.dictKeyFiles and n.find(".qs") > -1: self.dictKeyFiles[n] = sha if n.endswith(".mtd"): from PyQt5.QtXml import QDomDocument doc = QDomDocument(n) if util.domDocumentSetContent(doc, str_ret): mng = self.conn_.manager() docElem = doc.documentElement() mtd = mng.metadata(docElem, True) if not mtd or mtd.isQuery(): return str_ret if not mng.existTable(mtd.name()): mng.createTable(mng) elif (self.conn_.canRegenTables()): self.conn_.regenTable(mtd.name(), mtd) return str_ret
def prepare_composition_from_template(layout, template_path, time): document = QDomDocument() with open(template_path) as f: document.setContent(f.read()) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) context.setProjectTranslator(QgsProject.instance()) layout.readLayoutXml(document.documentElement(), document, context) composition_set_time(layout, time)
def qgis_style(self): """Returns the current style, as a QDomDocument""" from PyQt5.QtXml import QDomDocument from qgis.core import QgsReadWriteContext doc = QDomDocument() elt = self.__renderer.save(doc, QgsReadWriteContext()) doc.appendChild(elt) return (doc, self.__render_type)
def prepare_composition_from_template(layout, template_path, time): document = QDomDocument() with open(template_path) as f: document.setContent(f.read()) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) context.setProjectTranslator(QgsProject.instance()) layout.readLayoutXml(document.documentElement(), document, context) composition_set_time(layout, time)
def stringToColorRamp(self, rampdef): try: if '<' not in rampdef: return None d = QDomDocument() d.setContent(rampdef) return QgsSymbolLayerUtils.loadColorRamp(d.documentElement()) except: return None
def stringToColorRamp( self, rampdef ): try: if '<' not in rampdef: return None d=QDomDocument() d.setContent(rampdef) return QgsSymbolLayerUtils.loadColorRamp( d.documentElement() ) except: return None
def save_project(doc: QDomDocument, file_name="./test.xml"): file = QFile(file_name) if not file.open(QIODevice.ReadWrite): return False out = QTextStream(file) out.setCodec("UTF-8") doc.save(out, 4, QDomNode.EncodingFromTextStream) file.close() return True
def read_gpx_file(self): """ Reads the gpx file contents and creates QDomDocument version of it. """ gpx_file_path = QFile(self.gpx_path) self.document = QDomDocument() status, msg, line, col = self.document.setContent(gpx_file_path) if status: self.gpx_element = self.document.documentElement()
def get_layer_symbology(layer): doc = QDomDocument(QDomImplementation().createDocumentType("qgis", "http://mrcc.com/qgis.dtd", "SYSTEM")) rootNode = doc.createElement("qgis") doc.appendChild(rootNode) errorMsg = '' ctx = QgsReadWriteContext() layer.writeSymbology(rootNode, doc, errorMsg, ctx) return doc.toByteArray()
def createObjectsTree(self, filePath): if os.path.exists(filePath): f = QFile(filePath) if f.open(QIODevice.ReadOnly): document = QDomDocument() if document.setContent(f): newModel = RDFNavigatorObjectsDomModel(document, self) self.objectsStructureView.setModel(newModel) self.objectsStructureModel = newModel f.close()
def __init__(self, session, server): self.session = session self.server = server self._xml = QDomDocument() global instance instance = self self._locked_session_paths = set()
def save(self): name = QFileDialog.getSaveFileName(self, 'Save File')[0] if name: doc = QDomDocument() formatter = XmlFormat(doc) doc.appendChild(formatter.projectToXml(self)) saveFile = open(name,'w') saveFile.write(doc.toString()) saveFile.close() self.unsavedChanges = False self.setWindowTitle("playbook - {}".format(self.projectName))
def copyQptToCompositor(composition_dest, qptDict): project = QgsProject() layout = QgsLayout(project) with open(qptDict['caminho'], 'rt') as myTemplateFile: myTemplateContent = myTemplateFile.read() doc = QDomDocument() doc.setContent(myTemplateContent) items, sucess = layout.loadFromTemplate(doc, QgsReadWriteContext(), False) if sucess: for item in items: cloneItem(item, composition_dest, qptDict['x_0'], qptDict['y_0'])
def load(self): name = QFileDialog.getOpenFileName(self, 'Load File')[0] if name: doc = QDomDocument(name) openFile = QFile(name) doc.setContent(openFile) formatter = XmlFormat(doc) formatter.xmlToProject(self) openFile.close() self.centralWidget().update() self.setWindowTitle("playbook - {}".format(self.projectName)) self.overview.addFrameWidget()
def on_pushButton_item_clicked(self): text = self.lineEdit_item.text() # 如果这个项目已经存在就不再添加 items = self.listWidget_item.findItems(text, Qt.MatchContains) if len(items): return self.listWidget_item.addItem(text) n = QDomDocument().createElement("item") domtext = QDomDocument().createTextNode(text) n.appendChild(domtext) self.element.appendChild(n) self.itemlist.append(n)
def layoutLoader(self, template_source, layout_name, title_text): """ Generate the layout """ from qgis.core import (QgsProject, QgsPrintLayout, QgsReadWriteContext) from qgis.utils import iface from PyQt5.QtXml import QDomDocument #template_source = '/home/user/Document/Template.qpt' #layout_name = 'NewLayout' #title_text = 'New Title' # Create objects lm = layout manager, l = print layout lm = QgsProject.instance().layoutManager() l = QgsPrintLayout(QgsProject.instance()) l.initializeDefaults() # Load template file and load it into the layout (l) template_file = open(template_source, 'r+', encoding='utf-8') template_content = template_file.read() template_file.close() document = QDomDocument() document.setContent(template_content) context = QgsReadWriteContext() l.loadFromTemplate(document, context) # Give the layout a name (must be unique) l.setName(layout_name) # Get current canvas extent and apply that to all maps (items) in layout # Replace any text "{{title}}" in any layout label with the dialog Title text canvas = iface.mapCanvas() for item in l.items(): if item.type() == 65639: # Map item.zoomToExtent(canvas.extent()) if item.type() == 65641: # Label item.setText(item.text().replace('{{title}}', title_text)) # Add layout to layout manager l.refresh() lm.addLayout(l) # Open and show the layout in designer try: iface.openLayoutDesigner(l) except: oopsBox = QMessageBox() oopsBox.setIcon(QMessageBox.Warning) oopsBox.setText( self. tr('Ooops. Something went wrong. Trying to open the generated layout ({}) returned errors.' .format(l.name()))) oopsBox.setWindowTitle(self.tr('Layout Loader')) oopsBox.exec_()
def __init__(self, parent=None, xmlelement='QDomElement:None', index=0, edit=False): super().__init__(parent) self.element = xmlelement self.index = index self.edit = edit self.namelist = [] self.setStyleSheet("background-color: rgb(255, 0, 0);border:none;") width = int(self.element.attribute( "width")) * 7 if self.element.attribute("width") else 13 height = int(self.element.attribute( "height")) * 22 if self.element.attribute("height") else 22 self.resize(width, height) font = QFont() if self.element.hasAttribute("size"): try: font.setPointSize(float(self.element.attribute("size"))) except: pass self.setFont(font) self.clicked.connect(self.on_Clicked) self.qdom = QDomDocument() self.many = self.element.attribute("many") self.direction = self.element.attribute("direction") if self.many == '2': self.set_namelist() else: self.uid = self.element.firstChildElement("UserID") self.uname = self.element.firstChildElement("UserName") if self.uid.isNull(): self.uid = self.qdom.createElement('UserID') self.uid = self.element.appendChild(self.uid) if self.uname.isNull(): self.uname = self.qdom.createElement('UserName') self.uname = self.element.appendChild(self.uname) self.namelist.append( (self.uid.toElement(), self.uname.toElement())) # self.setText(self.uid.nodeValue() + ' ' + self.uname.nodeValue()) text = '' for item in self.namelist: text += item[0].text() + ' ' + item[1].text() if self.direction == '1' and self.many == '2': text += '\n' elif self.direction == '1' and self.many == '2': text += ' ' self.setText(text)
def init_(self, aclXml=None): """ Lee el fichero "acl.xml" y establece una nueva lista de control de acceso. Si el fichero "acl.xml" no se puede leer, la lista de control de acceso queda vacía y no se procesará ningún control de acceso sobre ningún objeto. @param aclXml Contenido XML con la definición de la lista de control de acceso. """ util = FLUtil() if aclXml is None: aclXml = self._prj.conn.managerModules().content("acl.xml") doc = QDomDocument("ACL") if self.accessControlList_: self.accessControlList_.clear() del self.accessControlList_ self.accessControlList_ = {} if aclXml and not util.domDocumentSetContent(doc, aclXml): logger.error("Lista de control de acceso errónea") return self.accessControlList_ = {} # self.accessControlList_.setAutoDelete(True) docElem = doc.documentElement() no = docElem.firstChild() while not no.isNull(): e = no.toElement() if e: if e.tagName() == "name": self.name_ = e.text() no = no.nextSibling() continue ac = FLAccessControlFactory().create(e.tagName()) if ac: ac.set(e) logger.debug("****************** %s %s %s", ac.type(), ac.name(), ac.user(), ac) self.accessControlList_["%s::%s::%s" % (ac.type(), ac.name(), ac.user())] = ac no = no.nextSibling() continue no = no.nextSibling()
def init_(self, aclXml=None): """ Lee el fichero "acl.xml" y establece una nueva lista de control de acceso. Si el fichero "acl.xml" no se puede leer, la lista de control de acceso queda vacía y no se procesará ningún control de acceso sobre ningún objeto. @param aclXml Contenido XML con la definición de la lista de control de acceso. """ util = FLUtil() if aclXml is None: from pineboolib.pncontrolsfactory import aqApp aclXml = aqApp.db().managerModules().content("acl.xml") doc = QDomDocument("ACL") if self.accessControlList_: self.accessControlList_.clear() del self.accessControlList_ self.accessControlList_ = [] if aclXml and not util.domDocumentSetContent(doc, aclXml): qWarning("FLAccessControlList : " + FLUtil().tr("Lista de control de acceso errónea")) return self.accessControlList_ = {} # self.accessControlList_.setAutoDelete(True) docElem = doc.documentElement() no = docElem.firstChild() while not no.isNull(): e = no.toElement() if e: if e.tagName() == "name": self.name_ = e.text() no = no.nextSibling() continue ac = FLAccessControlFactory().create(e.tagName()) if ac: ac.set(e) self.accessControlList_["%s::%s::%s" % (ac.type(), ac.name(), ac.user())] = ac no = no.nextSibling() continue no = no.nextSibling()
def parseTextChildren(document = QDomDocument(), elRead = QDomElement(), elWrite = QDomElement(), emphasisStyle = {}, strongStyle = {}): for n in range(0, elRead.childNodes().size()): childNode = elRead.childNodes().item(n) if childNode.isText(): if elWrite.hasChildNodes() and str(childNode.nodeValue()).startswith(" ") is False: elWrite.appendChild(document.createTextNode(" ")) elWrite.appendChild(document.createTextNode(str(childNode.nodeValue()))) elif childNode.hasChildNodes(): childNode = childNode.toElement() fontFamily = str(childNode.attribute("font-family")) fontWeight = str(childNode.attribute("font-weight", "400")) fontItalic = str(childNode.attribute("font-style")) fontStrikeThrough = str(childNode.attribute("text-decoration")) fontBaseLine = str(childNode.attribute("baseline-shift")) newElementMade = False emphasis = False strong = False if len(emphasisStyle.keys()) > 0: emphasis = compare_styles(emphasisStyle, fontFamily, fontWeight, fontItalic) else: if fontItalic == "italic": emphasis = True if len(strongStyle.keys()) > 0: strong = compare_styles(strongStyle, fontFamily, fontWeight, fontItalic) else: if fontWeight == "bold" or int(fontWeight) > 400: strong = True if strong: newElement = document.createElement("strong") newElementMade = True elif emphasis: newElement = document.createElement("emphasis") newElementMade = True elif fontStrikeThrough == "line-through": newElement = document.createElement("strikethrough") newElementMade = True elif fontBaseLine.isalnum(): if (fontBaseLine == "super"): newElement = document.createElement("sup") newElementMade = True elif (fontBaseLine == "sub"): newElement = document.createElement("sub") newElementMade = True if newElementMade is True: parseTextChildren(document, childNode, newElement, emphasisStyle, strongStyle) elWrite.appendChild(newElement) else: parseTextChildren(document, childNode, elWrite, emphasisStyle, strongStyle) # If it is not a text node, nor does it have children(which could be textnodes), # we should assume it's empty and ignore it. elWrite.normalize() for e in range(0, elWrite.childNodes().size()): el = elWrite.childNodes().item(e) if el.isText(): eb = el.nodeValue() el.setNodeValue(eb.replace(" ", " "))
def openFile(self): filePath, _ = QFileDialog.getOpenFileName(self, "Open File", self.xmlPath, "XML files (*.xml);;HTML files (*.html);;" "SVG files (*.svg);;User Interface files (*.ui)") if filePath: f = QFile(filePath) if f.open(QIODevice.ReadOnly): document = QDomDocument() if document.setContent(f): newModel = DomModel(document, self) self.view.setModel(newModel) self.model = newModel self.xmlPath = filePath f.close()
def get_symbology(self): """Returns the associated QGIS symbology Return ------ A tuple (QDomDocument, int) The QDomDocument can be loaded by QgsFeatureRenderer.load() The int gives the renderer type or None, None """ symbology = self.__config.get("symbology") if symbology is None: return None, None doc = QDomDocument() doc.setContent(symbology) return (doc, self.__config.get("symbology_type"))
def on_plainTextEdit_text_textChanged(self): p_str = self.plainTextEdit_text.toPlainText() if self.element.firstChild().isNull(): text = QDomDocument().createTextNode(p_str) self.element.appendChild(text) else: self.element.firstChild().setNodeValue(p_str) self.edited.emit()
def openFile(self): filePath, _ = QFileDialog.getOpenFileName( self, "Open File", self.xmlPath, "XML files (*.xml);;HTML files (*.html);;" "SVG files (*.svg);;User Interface files (*.ui)") if filePath: f = QFile(filePath) if f.open(QIODevice.ReadOnly): document = QDomDocument() if document.setContent(f): newModel = DomModel(document, self) self.view.setModel(newModel) self.model = newModel self.xmlPath = filePath f.close()
def contentStatic(self, file_name: str, only_path: bool = False) -> Optional[str]: """ Return the contents of a file by static loading from the local disk. @param file_name File name. @return String with the contents of the file or None in case of error. """ str_ret = pnmodulesstaticloader.PNStaticLoader.content( file_name, self.static_db_info_, only_path) if str_ret is not None: s = "" util = flutil.FLUtil() sha = util.sha1(str_ret) if file_name in self.dict_key_files_.keys(): s = self.dict_key_files_[file_name] if s == sha: return None elif self.dict_key_files_ and file_name.find(".qs") > -1: self.dict_key_files_[file_name] = sha if file_name.endswith(".mtd"): from PyQt5.QtXml import QDomDocument # type: ignore doc = QDomDocument(file_name) if util.domDocumentSetContent(doc, str_ret): mng = self.conn_.connManager().manager() docElem = doc.documentElement() mtd = mng.metadata(docElem, True) if not mtd or mtd.isQuery(): return str_ret if not mng.existsTable(mtd.name()): mng.createTable(mng) elif self.conn_.canRegenTables(): self.conn_.regenTable(mtd.name(), mtd) return str_ret
def openFile(project_path, session_name, full_client_id): saved_connections.clear() global file_path file_path = "%s.xml" % project_path if os.path.isfile(file_path): try: file = open(file_path, 'r') except: sys.stderr.write('unable to read file %s\n' % file_path) app.quit() return xml = QDomDocument() xml.setContent(file.read()) content = xml.documentElement() if content.tagName() != "RAY-JACKPATCH": file.close() NSMServer.openReply() return cte = content.toElement() node = cte.firstChild() while not node.isNull(): el = node.toElement() if el.tagName() != "connection": continue port_from = el.attribute('from') port_to = el.attribute('to') saved_connections.append((port_from, port_to)) node = node.nextSibling() makeMayConnections() NSMServer.openReply() setDirtyClean() dirty_checker.start()
def getPrintLayoutFromQptPath(self, path, newValue): ''' Returns a QgsPrintLayout from a template indicated by path. Also sets the composition variable 'variableNames' to newvalue ''' # Load template from file layout = QgsPrintLayout(QgsProject.instance()) # self.updateQptVariables(layout, newValue) # layout.initializeDefaults() with open(path) as template: templateContent = template.read() doc = QDomDocument() doc.setContent(templateContent) # adding to existing items #items, ok = layout.loadFromTemplate(doc, QgsReadWriteContext(), False) layout.loadFromTemplate(doc, QgsReadWriteContext()) self.updateQptVariables(layout, str(newValue)) return layout
def _get_history_xml_document_element(self): if not self._is_init(): return None file_path = self._get_history_full_path() xml = QDomDocument() try: history_file = open(file_path, 'r') xml.setContent(history_file.read()) history_file.close() except BaseException: return None SNS_xml = xml.documentElement() if SNS_xml.tagName() != 'SNAPSHOTS': return None return SNS_xml
def getHistoryXmlDocumentElement(self): if not self.isInit(): return None file_path = self.getHistoryFullPath() xml = QDomDocument() try: history_file = open(file_path, 'r') xml.setContent(history_file.read()) history_file.close() except BaseException: return None SNS_xml = xml.documentElement() if SNS_xml.tagName() != 'SNAPSHOTS': return None return SNS_xml
def createSystemTable(self, n): """ Crea una tabla del sistema. Este método lee directamente de disco el fichero con la descripción de una tabla del sistema y la crea en la base de datos. Su uso normal es para inicializar el sistema con tablas iniciales. @param n Nombre de la tabla. @return Un objeto FLTableMetaData con los metadatos de la tabla que se ha creado, o False si no se pudo crear la tabla o ya existía """ util = FLUtil() if not self.existsTable(n): doc = QDomDocument() _path = filedir("..", "share", "pineboo", "tables") dir = qsatype.Dir_Class(_path) _tables = dir.entryList("%s.mtd" % n) for f in _tables: path = "%s/%s" % (_path, f) _file = QtCore.QFile(path) _file.open(QtCore.QIODevice.ReadOnly) _in = QtCore.QTextStream(_file) _data = _in.readAll() if not util.domDocumentSetContent(doc, _data): logger.warn( "FLManager::createSystemTable: %s", util.tr( "Error al cargar los metadatos para la tabla %1"). arg(n)) return False else: docElem = doc.documentElement() mtd = self.createTable(self.metadata(docElem, True)) return mtd f.close() return False
def cloneItem(item, composition_dest, x_0, y_0): ref_point = item.referencePoint() item.setReferencePoint(QgsLayoutItem.UpperLeft) original_x = item.pagePos().x() original_y = item.pagePos().y() final_x = original_x + x_0 final_y = original_y + y_0 # Create doc xml doc = QDomDocument('Clipboard') element = doc.createElement('Copied items') context = QgsReadWriteContext() item.writeXml(element, doc, context) # Add doc xml composition_dest.addItemsFromXml(element, doc, context, QPointF(final_x, final_y)) composition_dest.itemById(item.id()).attemptMove( QgsLayoutPoint(final_x, final_y)) composition_dest.itemById(item.id()).refresh() item.setReferencePoint(ref_point)
def updateRasterToken(self, layer, uri): """ http://gis.stackexchange.com/questions/62610/changing-data-source-of-layer-in-qgis """ XMLDocument = QDomDocument("style") XMLMapLayers = QDomElement() XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = QDomElement() XMLMapLayer = XMLDocument.createElement("maplayer") layer.writeLayerXML(XMLMapLayer,XMLDocument) # modify DOM element with new layer reference XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue( uri ) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) # reload layer definition layer.readLayerXML(XMLMapLayer) layer.reload() # apply to canvas and legend self.iface.actionDraw().trigger() self.iface.legendInterface().refreshLayerSymbology(layer)
def __init__( self, parent=None, ): super(RDFNavigatorProjectStructure, self).__init__(parent) self.setupUi(self) self.basicStructureWidget.itemDoubleClicked.connect( self.createOpenFileRequest) self.childType = None self.objectsStructureModel = RDFNavigatorObjectsDomModel( QDomDocument(), self) self.objectsStructureView.setModel(self.objectsStructureModel)
def saveFile(self, executable, config_file, arguments_line, save_signal, no_save_level, stop_signal, wait_window): try: file = open(self.path, 'w') except BaseException: return if not save_signal: save_signal = 0 xml = QDomDocument() p = xml.createElement('RAY-PROXY') p.setAttribute('VERSION', ray.VERSION) p.setAttribute('executable', executable) p.setAttribute('arguments', arguments_line) p.setAttribute('config_file', config_file) p.setAttribute('save_signal', str(int(save_signal))) p.setAttribute('no_save_level', str(no_save_level)) p.setAttribute('stop_signal', str(int(stop_signal))) p.setAttribute('wait_window', wait_window) xml.appendChild(p) contents = "<?xml version='1.0' encoding='UTF-8'?>\n" contents += "<!DOCTYPE RAY-PROXY>\n" contents += xml.toString() file.write(contents) file.close() self.readFile()
def remove_bookmark(self, spath): if not self.written: return contents = self._get_contents() if not contents: self.written = False return url = pathlib.Path(spath).as_uri() xml = QDomDocument() xml.setContent(contents) content = xml.documentElement() if content.tagName() != 'xbel': self.written = False return node = content.firstChild() while not node.isNull(): el = node.toElement() if el.tagName() == 'bookmark': if el.attribute('href') == url: content.removeChild(node) break node = node.nextSibling() else: self.written = False return self._print_contents(xml.toString()) self.written = False
def __init__(self, parent, icon, size=None, padding=None, color=None): QWidget.__init__(self, parent) padding = padding or 0 self._theme_manager = ThemeManager.get(self) self._color = format_color( color or self._theme_manager.get_color('button_foreground'), ColorFormat.rgb_string_256) self._svgdoc = QDomDocument() self._icon_widget = QSvgWidget(self) self.loadIcon(icon) if size: self._icon_widget.setFixedSize( QSize(size.width() - 2 * padding, size.height() - 2 * padding)) self._layout = QHBoxLayout(self) self._layout.setContentsMargins(padding, padding, padding, padding) self._layout.addWidget(self._icon_widget, Qt.AlignCenter)
def __init__(self): super(MainWindow, self).__init__() self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction("&Open...", self.openFile, "Ctrl+O") self.fileMenu.addAction("E&xit", self.close, "Ctrl+Q") self.xmlPath = "" self.model = DomModel(QDomDocument(), self) self.view = QTreeView(self) self.view.setModel(self.model) self.setCentralWidget(self.view) self.setWindowTitle("Simple DOM Model")
def toXml(self, obj_, includeChildren=True, includeComplexTypes=False): xml_ = QDomDocument() if not obj_: return xml_ e = xml_.createElement(type(obj_).__name__) e.setAttribute("class", type(obj_).__name__) xml_.appendChild(e) _meta = obj_.metaObject() num = _meta.propertyCount() i = 0 _p_properties = [] while i < num: 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: pass if val is None: i += 1 continue val = str(val) if not val and not includeComplexTypes: i += 1 continue e.setAttribute(mp.name(), val) i += 1 if includeChildren == True: for child in obj_.children(): itd = self.toXml(child, includeChildren, includeComplexTypes) xml_.firstChild().appendChild(itd.firstChild()) return xml_
def installACL(self, idacl): """ Crea un nuevo fichero "acl.xml" y lo almacena sustituyendo el anterior, en el caso de que exista. @param idacl Identificador del registro de la tabla "flacls" a utilizar para crear "acl.xml". """ util = FLUtil() doc = QDomDocument("ACL") root = doc.createElement("ACL") doc.appendChild(root) name = doc.createElement("name") root.appendChild(name) n = doc.createTextNode(idacl) name.appendChild(n) q = FLSqlQuery() q.setTablesList("flacs") q.setSelect("idac,tipo,nombre,iduser,idgroup,degroup,permiso") q.setFrom("flacs") q.setWhere("idacl='%s'" % idacl) q.setOrderBy("prioridad DESC, tipo") q.setForwarOnly(True) if q.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 q.next(): self.makeRule(q, doc) progress.setProgress(++step) from pineboolib.pnconrolsfactory import aqApp aqApp.db().managerModules().setContent("acl.xml", "sys", doc.toString())
def run(self): """ Perform ontology import from .graphml file format. """ file = QFile(self.filepath) try: if not file.open(QIODevice.ReadOnly): raise IOError('File not found: {}'.format(self.filepath)) document = QDomDocument() if not document.setContent(file): raise ParseError('could not initialize DOM document') # 1) INITIALIZE XML ROOT ELEMENT root = document.documentElement() # 2) READ KEYS FROM THE DOCUMENT key = root.firstChildElement('key') while not key.isNull(): if key.attribute('yfiles.type', '') == 'nodegraphics': self.keys['node_key'] = key.attribute('id') if key.attribute('yfiles.type', '') == 'edgegraphics': self.keys['edge_key'] = key.attribute('id') key = key.nextSiblingElement('key') # 3) GENERATE ARBITRARY DIAGRAM SCENE self.scene = self.mainwindow.createScene(DiagramScene.MaxSize, DiagramScene.MaxSize) # 4) INITIALIZE GRAPH ELEMENT graph = root.firstChildElement('graph') # 5) GENERATE NODES element = graph.firstChildElement('node') while not element.isNull(): # noinspection PyArgumentList QApplication.processEvents() node = None item = self.itemFromGraphmlNode(element) try: if item is Item.AttributeNode: node = self.buildAttributeNode(element) elif item is Item.ComplementNode: node = self.buildComplementNode(element) elif item is Item.ConceptNode: node = self.buildConceptNode(element) elif item is Item.DatatypeRestrictionNode: node = self.buildDatatypeRestrictionNode(element) elif item is Item.DisjointUnionNode: node = self.buildDisjointUnionNode(element) elif item is Item.DomainRestrictionNode: node = self.buildDomainRestrictionNode(element) elif item is Item.EnumerationNode: node = self.buildEnumerationNode(element) elif item is Item.IndividualNode: node = self.buildIndividualNode(element) elif item is Item.IntersectionNode: node = self.buildIntersectionNode(element) elif item is Item.RangeRestrictionNode: node = self.buildRangeRestrictionNode(element) elif item is Item.RoleNode: node = self.buildRoleNode(element) elif item is Item.RoleChainNode: node = self.buildRoleChainNode(element) elif item is Item.RoleInverseNode: node = self.buildRoleInverseNode(element) elif item is Item.UnionNode: node = self.buildUnionNode(element) elif item is Item.ValueDomainNode: node = self.buildValueDomainNode(element) elif item is Item.ValueRestrictionNode: node = self.buildValueRestrictionNode(element) if not node: raise ValueError('unknown node with id {}'.format(element.attribute('id'))) except Exception as e: self.errors.append(e) else: self.scene.addItem(node) self.scene.sgnItemAdded.emit(node) self.scene.guid.update(node.id) finally: element = element.nextSiblingElement('node') # 6) GENERATE EDGES element = graph.firstChildElement('edge') while not element.isNull(): # noinspection PyArgumentList QApplication.processEvents() edge = None item = self.itemFromGraphmlNode(element) try: if item is Item.InclusionEdge: edge = self.buildInclusionEdge(element) elif item is Item.InputEdge: edge = self.buildInputEdge(element) elif item is Item.InstanceOfEdge: edge = self.buildInstanceOfEdge(element) if not edge: raise ValueError('unknown edge with id {}'.format(element.attribute('id'))) except Exception as e: self.errors.append(e) else: self.scene.addItem(edge) self.scene.sgnItemAdded.emit(edge) self.scene.guid.update(edge.id) edge.updateEdge() finally: element = element.nextSiblingElement('edge') # 7) CENTER DIAGRAM R1 = self.scene.sceneRect() R2 = self.scene.visibleRect(margin=0) moveX = snapF(((R1.right() - R2.right()) - (R2.left() - R1.left())) / 2, DiagramScene.GridSize) moveY = snapF(((R1.bottom() - R2.bottom()) - (R2.top() - R1.top())) / 2, DiagramScene.GridSize) if moveX or moveY: collection = [x for x in self.scene.items() if x.node or x.edge] for item in collection: # noinspection PyArgumentList QApplication.processEvents() item.moveBy(moveX, moveY) for item in collection: # noinspection PyArgumentList QApplication.processEvents() if item.edge: item.updateEdge() # 8) RESIZE DIAGRAM SCENE R3 = self.scene.visibleRect(margin=20) size = max(R3.width(), R3.height(), DiagramScene.MinSize) self.scene.setSceneRect(QRectF(-size / 2, -size / 2, size, size)) finally: file.close()
def qml2Sld(self): try: layer = self.allMapLayers[self.dlg.comboBox.currentIndex()] except: return qmlDocument = QDomDocument() root = qmlDocument.createElement('SLD4raster') qmlDocument.appendChild(root) qgisNode = qmlDocument.createElement('qgis') root.appendChild(qgisNode) errorMessage = None context = QgsReadWriteContext() layer.writeSymbology(qgisNode, qmlDocument, errorMessage, context) qmlString = minidom.parseString(qmlDocument.toString().encode('utf-8')) # for non ASCII labels. sldRoot = Element('sld:StyledLayerDescriptor') sldRoot.attrib['xmlns'] = 'http://www.opengis.net/sld' sldRoot.attrib['xmlns:sld'] = 'http://www.opengis.net/sld' sldRoot.attrib['xmlns:ogc'] = 'http://www.opengis.net/ogc' sldRoot.attrib['xmlns:gml'] = 'http://www.opengis.net/gml' sldRoot.attrib['version'] = '1.0.0' userLayer = SubElement(sldRoot, 'sld:UserLayer') layerFeatureConstraints = SubElement(userLayer, 'sld:LayerFeatureConstraints') featureTypeConstraint = SubElement(layerFeatureConstraints, 'sld:FeatureTypeConstraint') userStyle = SubElement(userLayer, 'sld:UserStyle') styleName = SubElement(userStyle, 'sld:Name') styleName.text = self.dlg.comboBox.currentText() styleDescription = SubElement(userStyle, 'sld:Description') styleDescription.text = 'Generated by SLD4raster - https://cbsuygulama.wordpress.com/sld4raster' styleTitle = SubElement(userStyle, 'sld:Title') featureTypeStyle = SubElement(userStyle, 'sld:FeatureTypeStyle') featureName = SubElement(featureTypeStyle, 'sld:Name') featureRule = SubElement(featureTypeStyle, 'sld:Rule') rasterSymbolizer = SubElement(featureRule, 'sld:RasterSymbolizer') geometry = SubElement(rasterSymbolizer, 'sld:Geometry') ogcPropertyName = SubElement(geometry, 'ogc:PropertyName') ogcPropertyName.text = 'grid' opacity = SubElement(rasterSymbolizer, 'sld:Opacity') ###Getting raster type parameters rasterType = str(qmlString.getElementsByTagName('rasterrenderer')[0].attributes['type'].value) isGradient = 'gradient' in qmlString.getElementsByTagName('rasterrenderer')[0].attributes.keys() ###SLD for multiband raster if rasterType == 'multibandcolor': ###Getting RGB band order. redBand = str(qmlString.getElementsByTagName('rasterrenderer')[0].attributes['redBand'].value) greenBand = str(qmlString.getElementsByTagName('rasterrenderer')[0].attributes['greenBand'].value) blueBand = str(qmlString.getElementsByTagName('rasterrenderer')[0].attributes['blueBand'].value) channelSelection = SubElement(rasterSymbolizer, 'sld:ChannelSelection') redChannel = SubElement(channelSelection, 'sld:RedChannel') redSourceChannel = SubElement(redChannel, 'sld:SourceChannelName') redSourceChannel.text = redBand greenChannel = SubElement(channelSelection, 'sld:GreenChannel') greenSourceChannel = SubElement(greenChannel, 'sld:SourceChannelName') greenSourceChannel.text = greenBand blueChannel = SubElement(channelSelection, 'sld:BlueChannel') blueSourceChannel = SubElement(blueChannel, 'sld:SourceChannelName') blueSourceChannel.text = blueBand ###SLD for gradiented (black to white) raster elif isGradient: blackWhiteColor = ['#000000', '#FFFFFF'] colorMap = SubElement(rasterSymbolizer, 'sld:ColorMap') gradientType = qmlString.getElementsByTagName('rasterrenderer')[0].attributes['gradient'].value blackWhiteValue = [qmlString.getElementsByTagName('minValue')[0].firstChild.nodeValue, qmlString.getElementsByTagName('maxValue')[0].firstChild.nodeValue] ###Getting gradient color type if gradientType == 'WhiteToBlack': blackWhiteColor.reverse() for i in range(len(blackWhiteColor)): colorMapEntry = SubElement(colorMap, 'sld:ColorMapEntry') colorMapEntry.attrib['color'] = blackWhiteColor[i] colorMapEntry.attrib['opacity'] = '1.0' colorMapEntry.attrib['quantity'] = blackWhiteValue[i] ###SLD for singleband raster else: colorMap = SubElement(rasterSymbolizer, 'sld:ColorMap') ###Getting color ramp type colorType = str(qmlString.getElementsByTagName('colorrampshader')[0].attributes['colorRampType'].value) if colorType == 'DISCRETE': colorMap.attrib['type'] = "intervals" ###Getting color values colorValue = list() itemlist = qmlString.getElementsByTagName('item') for n in itemlist: colorValue.append( [n.attributes['color'].value, n.attributes['value'].value, n.attributes['label'].value]) ###Color values posting to SLD document for i in range(len(colorValue)): colorMapEntry = SubElement(colorMap, 'sld:ColorMapEntry') colorMapEntry.attrib['color'] = colorValue[i][0] colorMapEntry.attrib['quantity'] = colorValue[i][1] colorMapEntry.attrib['label'] = colorValue[i][2] colorMapEntry.attrib['opacity'] = '1.0' rasterOpacity = str(qmlString.getElementsByTagName('rasterrenderer')[0].attributes['opacity'].value) opacity.text = rasterOpacity textSLD = minidom.parseString(tostring(sldRoot)) self.dlg.sldText1.setText(textSLD.toprettyxml(indent=" "))
def run(self): """ Perform ontology import from .graphol file format. """ file = QFile(self.filepath) try: if not file.open(QIODevice.ReadOnly): raise IOError('File not found: {}'.format(self.filepath)) document = QDomDocument() if not document.setContent(file): raise ParseError('could not initialize DOM document') # 1) INITIALIZE XML ROOT ELEMENT root = document.documentElement() # 2) READ GRAPH INITIALIZATION DATA graph = root.firstChildElement('graph') w = int(graph.attribute('width', str(self.mainwindow.diagramSize))) h = int(graph.attribute('height', str(self.mainwindow.diagramSize))) # 3) GENERATE DIAGRAM SCENE self.scene = self.mainwindow.createScene(width=w, height=h) self.scene.document.path = self.filepath # 4) GENERATE NODES element = graph.firstChildElement('node') while not element.isNull(): # noinspection PyArgumentList QApplication.processEvents() node = None item = self.itemFromGrapholNode(element) try: if item is Item.AttributeNode: node = self.buildAttributeNode(element) elif item is Item.ComplementNode: node = self.buildComplementNode(element) elif item is Item.ConceptNode: node = self.buildConceptNode(element) elif item is Item.DatatypeRestrictionNode: node = self.buildDatatypeRestrictionNode(element) elif item is Item.DisjointUnionNode: node = self.buildDisjointUnionNode(element) elif item is Item.DomainRestrictionNode: node = self.buildDomainRestrictionNode(element) elif item is Item.EnumerationNode: node = self.buildEnumerationNode(element) elif item is Item.IndividualNode: node = self.buildIndividualNode(element) elif item is Item.IntersectionNode: node = self.buildIntersectionNode(element) elif item is Item.PropertyAssertionNode: node = self.buildPropertyAssertionNode(element) elif item is Item.RangeRestrictionNode: node = self.buildRangeRestrictionNode(element) elif item is Item.RoleNode: node = self.buildRoleNode(element) elif item is Item.RoleChainNode: node = self.buildRoleChainNode(element) elif item is Item.RoleInverseNode: node = self.buildRoleInverseNode(element) elif item is Item.UnionNode: node = self.buildUnionNode(element) elif item is Item.ValueDomainNode: node = self.buildValueDomainNode(element) elif item is Item.ValueRestrictionNode: node = self.buildValueRestrictionNode(element) if not node: raise ValueError('unknown node: {}'.format(element.attribute('type'))) self.scene.addItem(node) self.scene.sgnItemAdded.emit(node) self.scene.guid.update(node.id) finally: element = element.nextSiblingElement('node') # 5) GENERATE EDGES element = graph.firstChildElement('edge') while not element.isNull(): # noinspection PyArgumentList QApplication.processEvents() edge = None item = self.itemFromGrapholNode(element) try: if item is Item.InclusionEdge: edge = self.buildInclusionEdge(element) elif item is Item.InputEdge: edge = self.buildInputEdge(element) elif item is Item.InstanceOfEdge: edge = self.buildInstanceOfEdge(element) if not edge: raise ValueError('unknown edge: {}'.format(element.attribute('type'))) self.scene.addItem(edge) self.scene.sgnItemAdded.emit(edge) self.scene.guid.update(edge.id) edge.updateEdge() finally: element = element.nextSiblingElement('edge') # 6) GENERATE PREDICATE METADATA metadata = root.firstChildElement('metadata') if not metadata.isNull(): element = metadata.firstChildElement('meta') while not element.isNull(): # noinspection PyArgumentList QApplication.processEvents() item = self.itemFromGrapholNode(element) try: if item is Item.AttributeNode: meta = self.buildAttributeMetadata(element) elif item is Item.RoleNode: meta = self.buildRoleMetadata(element) else: meta = self.buildPredicateMetadata(element) if meta: self.scene.meta.add(meta.item, meta.predicate, meta) finally: element = element.nextSiblingElement('meta') finally: file.close()
class GrapholExporter(AbstractExporter): """ This class can be used to export Graphol diagrams to file. """ def __init__(self, scene): """ Initialize the Graphol exporter. :type scene: DiagramScene """ super().__init__(scene) self.document = None self.itemToXml = { Item.AttributeNode: 'attribute', Item.ComplementNode: 'complement', Item.ConceptNode: 'concept', Item.DatatypeRestrictionNode: 'datatype-restriction', Item.DisjointUnionNode: 'disjoint-union', Item.DomainRestrictionNode: 'domain-restriction', Item.EnumerationNode: 'enumeration', Item.IndividualNode: 'individual', Item.IntersectionNode: 'intersection', Item.PropertyAssertionNode: 'property-assertion', Item.RangeRestrictionNode: 'range-restriction', Item.RoleNode: 'role', Item.RoleChainNode: 'role-chain', Item.RoleInverseNode: 'role-inverse', Item.UnionNode: 'union', Item.ValueDomainNode: 'value-domain', Item.ValueRestrictionNode: 'value-restriction', Item.InclusionEdge: 'inclusion', Item.InputEdge: 'input', Item.InstanceOfEdge: 'instance-of', } #################################################################################################################### # # # NODES # # # #################################################################################################################### def exportAttributeNode(self, node): """ Export the given node into a QDomElement. :type node: AttributeNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportComplementNode(self, node): """ Export the given node into a QDomElement. :type node: ComplementNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportConceptNode(self, node): """ Export the given node into a QDomElement. :type node: ConceptNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportDatatypeRestrictionNode(self, node): """ Export the given node into a QDomElement. :type node: DatatypeRestrictionNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportDisjointUnionNode(self, node): """ Export the given node into a QDomElement. :type node: DisjointUnionNode :rtype: QDomElement """ return self.exportGenericNode(node) def exportDomainRestrictionNode(self, node): """ Export the given node into a QDomElement. :type node: DomainRestrictionNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportEnumerationNode(self, node): """ Export the given node into a QDomElement. :type node: EnumerationNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportIndividualNode(self, node): """ Export the given node into a QDomElement. :type node: IndividualNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportIntersectionNode(self, node): """ Export the given node into a QDomElement. :type node: IntersectionNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportPropertyAssertionNode(self, node): """ Export the given node into a QDomElement. :type node: PropertyAssertionNode :rtype: QDomElement """ element = self.exportGenericNode(node) element.setAttribute('inputs', ','.join(node.inputs)) return element def exportRangeRestrictionNode(self, node): """ Export the given node into a QDomElement. :type node: RangeRestrictionNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportRoleNode(self, node): """ Export the given node into a QDomElement. :type node: RoleNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportRoleChainNode(self, node): """ Export the given node into a QDomElement. :type node: RoleChainNode :rtype: QDomElement """ element = self.exportLabelNode(node) element.setAttribute('inputs', ','.join(node.inputs)) return element def exportRoleInverseNode(self, node): """ Export the given node into a QDomElement. :type node: RoleInverseNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportValueDomainNode(self, node): """ Export the given node into a QDomElement. :type node: ValueDomainNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportUnionNode(self, node): """ Export the given node into a QDomElement. :type node: UnionNode :rtype: QDomElement """ return self.exportLabelNode(node) def exportValueRestrictionNode(self, node): """ Export the given node into a QDomElement. :type node: ValueRestrictionNode :rtype: QDomElement """ return self.exportLabelNode(node) #################################################################################################################### # # # EDGES # # # #################################################################################################################### def exportInclusionEdge(self, edge): """ Export the given edge into a QDomElement. :type edge: InclusionEdge :rtype: QDomElement """ element = self.exportGenericEdge(edge) element.setAttribute('complete', int(edge.complete)) return element def exportInputEdge(self, edge): """ Export the given edge into a QDomElement. :type edge: InputEdge :rtype: QDomElement """ return self.exportGenericEdge(edge) def exportInstanceOfEdge(self, edge): """ Export the given edge into a QDomElement. :type edge: InstanceOf :rtype: QDomElement """ return self.exportGenericEdge(edge) #################################################################################################################### # # # METADATA # # # #################################################################################################################### def exportPredicateMetadata(self, item, predicate): """ Export given predicate metadata. :type item: Item :type predicate: str :rtype: QDomElement """ meta = self.scene.meta.metaFor(item, predicate) if meta: element = self.document.createElement('meta') element.setAttribute('type', self.itemToXml[item]) element.setAttribute('predicate', predicate) url = self.document.createElement('data:url') url.appendChild(self.document.createTextNode(meta.url)) description = self.document.createElement('data:description') description.appendChild(self.document.createTextNode(meta.description)) element.appendChild(url) element.appendChild(description) return element return None def exportAttributeMetadata(self, item, predicate): """ Export given attribute metadata. :type item: Item :type predicate: str :rtype: QDomElement """ element = self.exportPredicateMetadata(item, predicate) if element: meta = self.scene.meta.metaFor(item, predicate) if meta: functionality = self.document.createElement('data:functionality') functionality.appendChild(self.document.createTextNode(str(int(meta.functionality)))) element.appendChild(functionality) return element return None def exportRoleMetadata(self, item, predicate): """ Export given role metadata :type item: Item :type predicate: str :rtype: QDomElement """ element = self.exportPredicateMetadata(item, predicate) if element: meta = self.scene.meta.metaFor(item, predicate) if meta: functionality = self.document.createElement('data:functionality') functionality.appendChild(self.document.createTextNode(str(int(meta.functionality)))) inverseFunctionality = self.document.createElement('data:inverseFunctionality') inverseFunctionality.appendChild(self.document.createTextNode(str(int(meta.inverseFunctionality)))) asymmetry = self.document.createElement('data:asymmetry') asymmetry.appendChild(self.document.createTextNode(str(int(meta.asymmetry)))) irreflexivity = self.document.createElement('data:irreflexivity') irreflexivity.appendChild(self.document.createTextNode(str(int(meta.irreflexivity)))) reflexivity = self.document.createElement('data:reflexivity') reflexivity.appendChild(self.document.createTextNode(str(int(meta.reflexivity)))) symmetry = self.document.createElement('data:symmetry') symmetry.appendChild(self.document.createTextNode(str(int(meta.symmetry)))) transitivity = self.document.createElement('data:transitivity') transitivity.appendChild(self.document.createTextNode(str(int(meta.transitivity)))) element.appendChild(functionality) element.appendChild(inverseFunctionality) element.appendChild(asymmetry) element.appendChild(irreflexivity) element.appendChild(reflexivity) element.appendChild(symmetry) element.appendChild(transitivity) return element return None #################################################################################################################### # # # AUXILIARY METHODS # # # #################################################################################################################### def exportLabelNode(self, node): """ Export the given node into a QDomElement. :type node: AbstractNode :rtype: QDomElement """ position = node.mapToScene(node.textPos()) label = self.document.createElement('shape:label') label.setAttribute('height', node.label.height()) label.setAttribute('width', node.label.width()) label.setAttribute('x', position.x()) label.setAttribute('y', position.y()) label.appendChild(self.document.createTextNode(node.text())) element = self.exportGenericNode(node) element.appendChild(label) return element def exportGenericEdge(self, edge): """ Export the given node into a QDomElement. :type edge: AbstractEdge :rtype: QDomElement """ element = self.document.createElement('edge') element.setAttribute('source', edge.source.id) element.setAttribute('target', edge.target.id) element.setAttribute('id', edge.id) element.setAttribute('type', self.itemToXml[edge.item]) for p in [edge.source.anchor(edge)] + edge.breakpoints + [edge.target.anchor(edge)]: point = self.document.createElement('line:point') point.setAttribute('x', p.x()) point.setAttribute('y', p.y()) element.appendChild(point) return element def exportGenericNode(self, node): """ Export the given node into a QDomElement. :type node: AbstractNode :rtype: QDomElement """ element = self.document.createElement('node') element.setAttribute('id', node.id) element.setAttribute('type', self.itemToXml[node.item]) element.setAttribute('color', node.brush.color().name()) geometry = self.document.createElement('shape:geometry') geometry.setAttribute('height', node.height()) geometry.setAttribute('width', node.width()) geometry.setAttribute('x', node.pos().x()) geometry.setAttribute('y', node.pos().y()) element.appendChild(geometry) return element #################################################################################################################### # # # DOCUMENT EXPORT # # # #################################################################################################################### def export(self, indent=4): """ Export the coverted ontology. :type indent: int :rtype: str """ return self.document.toString(indent) #################################################################################################################### # # # DOCUMENT GENERATION # # # #################################################################################################################### def run(self): """ Perform Graphol ontology generation. """ # 1) CREATE THE DOCUMENT self.document = QDomDocument() self.document.appendChild(self.document.createProcessingInstruction('xml', 'version="1.0" ' 'encoding="UTF-8" ' 'standalone="no"')) # 2) CREATE ROOT ELEMENT root = self.document.createElement('graphol') root.setAttribute('xmlns', 'http://www.dis.uniroma1.it/~graphol/schema') root.setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance') root.setAttribute('xmlns:data', 'http://www.dis.uniroma1.it/~graphol/schema/data') root.setAttribute('xmlns:line', 'http://www.dis.uniroma1.it/~graphol/schema/line') root.setAttribute('xmlns:shape', 'http://www.dis.uniroma1.it/~graphol/schema/shape') root.setAttribute('xsi:schemaLocation', 'http://www.dis.uniroma1.it/~graphol/schema ' 'http://www.dis.uniroma1.it/~graphol/schema/graphol.xsd') self.document.appendChild(root) # 3) CREATE THE GRAPH NODE graph = self.document.createElement('graph') graph.setAttribute('width', self.scene.sceneRect().width()) graph.setAttribute('height', self.scene.sceneRect().height()) # 4) GENERATE NODES for node in self.scene.nodes(): element = None if node.item is Item.AttributeNode: element = self.exportAttributeNode(node) elif node.item is Item.ComplementNode: element = self.exportComplementNode(node) elif node.item is Item.ConceptNode: element = self.exportConceptNode(node) elif node.item is Item.DatatypeRestrictionNode: element = self.exportDatatypeRestrictionNode(node) elif node.item is Item.DisjointUnionNode: element = self.exportDisjointUnionNode(node) elif node.item is Item.DomainRestrictionNode: element = self.exportDomainRestrictionNode(node) elif node.item is Item.EnumerationNode: element = self.exportEnumerationNode(node) elif node.item is Item.IndividualNode: element = self.exportIndividualNode(node) elif node.item is Item.IntersectionNode: element = self.exportIntersectionNode(node) elif node.item is Item.PropertyAssertionNode: element = self.exportPropertyAssertionNode(node) elif node.item is Item.RangeRestrictionNode: element = self.exportRangeRestrictionNode(node) elif node.item is Item.RoleNode: element = self.exportRoleNode(node) elif node.item is Item.RoleChainNode: element = self.exportRoleChainNode(node) elif node.item is Item.RoleInverseNode: element = self.exportRoleInverseNode(node) elif node.item is Item.UnionNode: element = self.exportUnionNode(node) elif node.item is Item.ValueDomainNode: element = self.exportValueDomainNode(node) elif node.item is Item.ValueRestrictionNode: element = self.exportValueRestrictionNode(node) if not element: raise ValueError('unknown node: {}'.format(node)) graph.appendChild(element) # 5) GENERATE EDGES for edge in self.scene.edges(): element = None if edge.item is Item.InclusionEdge: element = self.exportInclusionEdge(edge) elif edge.item is Item.InputEdge: element = self.exportInputEdge(edge) elif edge.item is Item.InstanceOfEdge: element = self.exportInstanceOfEdge(edge) if not element: raise ValueError('unknown edge: {}'.format(edge)) graph.appendChild(element) # 6) APPEND THE GRAPH TO THE DOCUMENT root.appendChild(graph) # 7) GENERATE NODES META DATA collection = [] for item, predicate in self.scene.meta.entries(): if item is Item.RoleNode: element = self.exportRoleMetadata(item, predicate) elif item is Item.AttributeNode: element = self.exportAttributeMetadata(item, predicate) else: element = self.exportPredicateMetadata(item, predicate) if element: collection.append(element) if collection: metadata = self.document.createElement('metadata') for element in collection: metadata.appendChild(element) root.appendChild(metadata)
def run(self): """ Perform Graphol ontology generation. """ # 1) CREATE THE DOCUMENT self.document = QDomDocument() self.document.appendChild(self.document.createProcessingInstruction('xml', 'version="1.0" ' 'encoding="UTF-8" ' 'standalone="no"')) # 2) CREATE ROOT ELEMENT root = self.document.createElement('graphol') root.setAttribute('xmlns', 'http://www.dis.uniroma1.it/~graphol/schema') root.setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance') root.setAttribute('xmlns:data', 'http://www.dis.uniroma1.it/~graphol/schema/data') root.setAttribute('xmlns:line', 'http://www.dis.uniroma1.it/~graphol/schema/line') root.setAttribute('xmlns:shape', 'http://www.dis.uniroma1.it/~graphol/schema/shape') root.setAttribute('xsi:schemaLocation', 'http://www.dis.uniroma1.it/~graphol/schema ' 'http://www.dis.uniroma1.it/~graphol/schema/graphol.xsd') self.document.appendChild(root) # 3) CREATE THE GRAPH NODE graph = self.document.createElement('graph') graph.setAttribute('width', self.scene.sceneRect().width()) graph.setAttribute('height', self.scene.sceneRect().height()) # 4) GENERATE NODES for node in self.scene.nodes(): element = None if node.item is Item.AttributeNode: element = self.exportAttributeNode(node) elif node.item is Item.ComplementNode: element = self.exportComplementNode(node) elif node.item is Item.ConceptNode: element = self.exportConceptNode(node) elif node.item is Item.DatatypeRestrictionNode: element = self.exportDatatypeRestrictionNode(node) elif node.item is Item.DisjointUnionNode: element = self.exportDisjointUnionNode(node) elif node.item is Item.DomainRestrictionNode: element = self.exportDomainRestrictionNode(node) elif node.item is Item.EnumerationNode: element = self.exportEnumerationNode(node) elif node.item is Item.IndividualNode: element = self.exportIndividualNode(node) elif node.item is Item.IntersectionNode: element = self.exportIntersectionNode(node) elif node.item is Item.PropertyAssertionNode: element = self.exportPropertyAssertionNode(node) elif node.item is Item.RangeRestrictionNode: element = self.exportRangeRestrictionNode(node) elif node.item is Item.RoleNode: element = self.exportRoleNode(node) elif node.item is Item.RoleChainNode: element = self.exportRoleChainNode(node) elif node.item is Item.RoleInverseNode: element = self.exportRoleInverseNode(node) elif node.item is Item.UnionNode: element = self.exportUnionNode(node) elif node.item is Item.ValueDomainNode: element = self.exportValueDomainNode(node) elif node.item is Item.ValueRestrictionNode: element = self.exportValueRestrictionNode(node) if not element: raise ValueError('unknown node: {}'.format(node)) graph.appendChild(element) # 5) GENERATE EDGES for edge in self.scene.edges(): element = None if edge.item is Item.InclusionEdge: element = self.exportInclusionEdge(edge) elif edge.item is Item.InputEdge: element = self.exportInputEdge(edge) elif edge.item is Item.InstanceOfEdge: element = self.exportInstanceOfEdge(edge) if not element: raise ValueError('unknown edge: {}'.format(edge)) graph.appendChild(element) # 6) APPEND THE GRAPH TO THE DOCUMENT root.appendChild(graph) # 7) GENERATE NODES META DATA collection = [] for item, predicate in self.scene.meta.entries(): if item is Item.RoleNode: element = self.exportRoleMetadata(item, predicate) elif item is Item.AttributeNode: element = self.exportAttributeMetadata(item, predicate) else: element = self.exportPredicateMetadata(item, predicate) if element: collection.append(element) if collection: metadata = self.document.createElement('metadata') for element in collection: metadata.appendChild(element) root.appendChild(metadata)