Пример #1
0
    def open(self):
        fileName = QtGui.QFileDialog.getOpenFileName(
            self, "Open Bookmark File", QtCore.QDir.currentPath(),
            "XBEL Files (*.xbel *.xml)")

        if not fileName:
            return

        self.treeWidget.clear()

        handler = XbelHandler(self.treeWidget)
        reader = QtXml.QXmlSimpleReader()
        reader.setContentHandler(handler)
        reader.setErrorHandler(handler)

        file = QtCore.QFile(fileName)
        if not file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(
                self, "SAX Bookmarks",
                "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return

        xmlInputSource = QtXml.QXmlInputSource(file)
        if reader.parse(xmlInputSource):
            self.statusBar().showMessage("File loaded", 2000)
Пример #2
0
 def loadSetup(self):
     indihostfile = QtCore.QFile(
         KStandardDirs.locate("data", "kstars/indihosts.xml"))
     #print(indihostfile.fileName())
     if ((indihostfile.size() == 0)
             or not (indihostfile.open(QtCore.QIODevice.ReadOnly))):
         return
     handler = XmlIndiHostHandler(self)
     xmlreader = QtXml.QXmlSimpleReader()
     xmlreader.setContentHandler(handler)
     xmlreader.setErrorHandler(handler)
     source = QtXml.QXmlInputSource(indihostfile)
     ok = xmlreader.parse(source, True)
     #while (source.data() != ""):
     #source.reset()
     #ok=xmlreader.parseContinue()
     #xmlreader=QtCore.QXmlStreamReader(indihostfile)
     #ok=True
     #while not(xmlreader.atEnd()):
     #  xmlreader.readNext()
     #  if xmlreader.isStartElement():
     #    print("xml token name " + xmlreader.name().toString())
     #if xmlreader.hasError():
     #  ok=False
     if not (ok):
         print("Failed to load indihosts setup")
Пример #3
0
 def createDomDocument(cls, rootElementName, mainNS = QtCore.QString(), encoding = None):
     domImplementation = QtXml.QDomImplementation()
     domDocType = QtXml.QDomDocumentType()
     doc = domImplementation.createDocument(mainNS, #namespace URI
                                            rootElementName, #root element name
                                            domDocType) # document type
     processingInstruction = doc.createProcessingInstruction(u'xml', u'version="%s" encoding="%s"' % (cls.version,
                                                                                                    cls.defaultEncoding if encoding is None else encoding))
     doc.insertBefore(processingInstruction, cls.getRootElement(doc))
     return doc
Пример #4
0
 def __init__(self):
     QtGui.QTreeWidget.__init__(self)
     self.header().setResizeMode(QtGui.QHeaderView.Stretch)
     self.setHeaderLabels(['Title', 'Type'])
     source = QtXml.QXmlInputSource()
     source.setData(xml)
     handler = XmlHandler(self)
     reader = QtXml.QXmlSimpleReader()
     reader.setContentHandler(handler)
     reader.setErrorHandler(handler)
     reader.parse(source)
Пример #5
0
    def _process_reply(self, reply):
        try:
            request, handler, xml = self._active_requests.pop(reply)
        except KeyError:
            self.log.error("Error: Request not found for %s" %
                           str(reply.request().url().toString()))
            return
        error = int(reply.error())
        redirect = reply.attribute(
            QtNetwork.QNetworkRequest.RedirectionTargetAttribute).toUrl()
        self.log.debug(
            "Received reply for %s: HTTP %d (%s)",
            reply.request().url().toString(),
            reply.attribute(
                QtNetwork.QNetworkRequest.HttpStatusCodeAttribute).toInt()[0],
            reply.attribute(QtNetwork.QNetworkRequest.HttpReasonPhraseAttribute
                            ).toString())
        if handler is not None:
            if error:
                self.log.error(
                    "Network request error for %s: %s (QT code %d, HTTP code %d)",
                    reply.request().url().toString(), reply.errorString(),
                    error,
                    reply.attribute(QtNetwork.QNetworkRequest.
                                    HttpStatusCodeAttribute).toInt()[0])

            # Redirect if found and not infinite
            if not redirect.isEmpty() and not XmlWebService.urls_equivalent(
                    redirect,
                    reply.request().url()):
                self.log.debug("Redirect to %s requested", redirect.toString())
                self.get(
                    str(redirect.host()),
                    redirect.port(80),
                    # retain path, query string and anchors from redirect URL
                    redirect.toString(
                        QUrl.FormattingOption(QUrl.RemoveAuthority
                                              | QUrl.RemoveScheme)),
                    handler,
                    xml,
                    priority=True,
                    important=True)
            elif xml:
                xml_handler = XmlHandler()
                xml_handler.init()
                xml_reader = QtXml.QXmlSimpleReader()
                xml_reader.setContentHandler(xml_handler)
                xml_input = QtXml.QXmlInputSource(reply)
                xml_reader.parse(xml_input)
                handler(xml_handler.document, reply, error)
            else:
                handler(str(reply.readAll()), reply, error)
        reply.close()
Пример #6
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'EasyImport_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dlg = EasyImportDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&EasyImport')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'EasyImport')
        self.toolbar.setObjectName(u'EasyImport')

        # Root folder where shape files are stored
        self.shapeDirectory = QDir()

        # XML Config file
        self.configXML = QtXml.QDomDocument()

        # XML current Config
        self.currentConfigXML = QtXml.QDomElement()

        # XML Config path
        self.configFileName = 'config.xml'

        # Shape file dictionnary
        # shapeFiles[shape filename] = shapefile absolute path
        self.shapeFiles = {}

        # Shape file dictionnary
        # pointsLayersConfig[shape filename] = Import rules XML nodes
        self.pointsLayersConfig = {}
Пример #7
0
    def _textChangedSlot(self, text):
        """Event when TextBox changed

        Args:
        -----
        text: str
            new contents of text box
        """
        self._param = QtXml.QDomElement()
        if qt4:
            qs = str(self.sender().property("dom address").toPyObject())
        else:
            qs = str(self.sender().property("dom address"))

        ind = qs.rfind('/')
        ids = qs[ind:]

        self._param = self.qhash[qs].elem.firstChildElement("Activate")
        while (self._param.isNull() is False):
            qs = str(self._param.text()).strip() + ids
            widget_visible = self.qhash[qs].elem.attribute("Visible", "Uknown")
            if (text != ""):
                self.qhash[qs].widget.setEnabled(True)
                self.qhash[qs].widget.show()
                self.qhash[qs].label.show()
            else:
                self.qhash[qs].widget.setEnabled(False)
                if (widget_visible != "Unknown"):
                    self.qhash[qs].label.hide()
                    self.qhash[qs].widget.hide()
            self._param = self._param.nextSiblingElement("Activate")
Пример #8
0
    def _getExtent(self, layer):
        def getTargetWindow():
            nodes = doc.elementsByTagName('TargetWindow')
            node = nodes.item(0)
            targetWindow = {'ulX': None, 'ulY': None, 'lrX': None, 'lrY': None}
            labels = {
                'UpperLeftX': 'ulX',
                'UpperLeftY': 'ulY',
                'LowerRightX': 'lrX',
                'LowerRightY': 'lrY'
            }
            for key, value in labels.iteritems():
                text = node.firstChildElement(key).text()
                if len(text) == 0:
                    continue
                targetWindow[value] = float(text)
            return targetWindow

        doc = QtXml.QDomDocument()
        file = QtCore.QFile(layer.source())
        doc.setContent(file)
        file.close()

        tw = getTargetWindow()
        return QgsCore.QgsRectangle(tw['ulX'], tw['lrY'], tw['lrX'], tw['ulY'])
Пример #9
0
    def load(self):
        file = QtCore.QFile(self.libMgr.getConfigFile())

        #Load data into config, if file doesn't exist, create one
        if (not file.open(QtCore.QIODevice.ReadWrite | QtCore.QIODevice.Text)):
            print 'config.ini could not be opened'
            return

        self.config = QtXml.QDomDocument("ConfigFile")

        #Validate file xml
        if (not self.config.setContent(file)):
            self.libMgr.printError('config.ini could not be parsed',
                                   "Config load failed", 10)
            return
        file.close()

        root = self.config.documentElement()

        #If there was wierdness as the root node, error
        if (root.tagName() != 'config' and root.tagName() != ''):
            self.libMgr.printError('config.ini invalid xml',
                                   "Config load failed", 10)
            return
        #If there was no root, empty file, start one
        elif (root.tagName() == ''):
            self.__initDefaults()
        #If its good, make sure all the base nodes have not been manually deleted
        else:
            self.__validateDefaults(root)

        self.save()
Пример #10
0
 def serialize(self, rootNode):
     doc = QtXml.QDomDocument()
     xmlNode = self.xmlFromNode(doc, rootNode)
     doc.appendChild(xmlNode)
     for child in rootNode._children:
         self._recurseXml(doc, xmlNode, child)
     return doc.toString(indent=4)
Пример #11
0
    def _capabilitiesRequestFinished(self):
        # Receive the server capabilities XML
        if self._theReply.error() == 1:
            QMessageBox.information(
                None, '',
                QApplication.translate(
                    "QgsWpsGui",
                    "Connection Refused. Please check your Proxy-Settings"))
            pass

        xmlString = self._theReply.readAll().data()
        self._theReply.deleteLater()
        self.doc = QtXml.QDomDocument()
        self.doc.setContent(xmlString, True)

        root = self.doc.documentElement()
        version = root.attribute("version")
        if version != "1.0.0":
            QMessageBox.information(
                None,
                QApplication.translate("QgsWps",
                                       "Only WPS Version 1.0.0 is supported"),
                xmlString)
            pass
        self.capabilitiesRequestFinished.emit()
Пример #12
0
    def saveModulesForCompletion(self):
        dom_document = QtXml.QDomDocument("modules")

        modules = dom_document.createElement("modules")
        dom_document.appendChild(modules)

        for i, v in self.libraryDict.items():
            tag = dom_document.createElement(i)
            modules.appendChild(tag)
            tag.setAttribute("use", str(v[1]))

            for subModule in v[0]:
                item = dom_document.createElement("item")
                tag.appendChild(item)

                t = dom_document.createTextNode(subModule)
                item.appendChild(t)

        try:
            file = open(self.appPathDict["modules"], "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)))
Пример #13
0
    def renderTemplate(self, theTemplateFilePath, theOutputFilePath):
        """Load a QgsComposer map from a template and render it

        .. note:: THIS METHOD IS EXPERIMENTAL AND CURRENTLY NON FUNCTIONAL

        Args:
            theTemplateFilePath - path to the template that should be loaded.
            theOutputFilePath - path for the output pdf
        Returns:
            None
        Raises:
            None
        """
        self.setupComposition()

        myResolution = self.composition.printResolution()
        self.printer = setupPrinter(theOutputFilePath,
                                    theResolution=myResolution)
        if self.composition:
            myFile = QtCore.QFile(theTemplateFilePath)
            myDocument = QtXml.QDomDocument()
            myDocument.setContent(myFile, False)  # .. todo:: fix magic param
            myNodeList = myDocument.elementsByTagName('Composer')
            if myNodeList.size() > 0:
                myElement = myNodeList.at(0).toElement()
                self.composition.readXML(myElement, myDocument)
        self.printToPdf(theOutputFilePath)
Пример #14
0
    def loadKeymap(self):
        if self.settings["firstRun"] == "True":
            self.CUSTOM_DEFAULT_SHORTCUTS = self.DEFAULT_SHORTCUTS
            return
        dom_document = QtXml.QDomDocument()
        file = open(self.appPathDict["keymap"], "r")
        x = dom_document.setContent(file.read())
        file.close()

        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")
                shortcut = QtGui.QKeySequence(shortcut).toString()
                function = tag.attribute("function")
                self.CUSTOM_DEFAULT_SHORTCUTS[group][name] = [
                    shortcut, function
                ]

                sub_node = sub_node.nextSibling()

            node = node.nextSibling()
Пример #15
0
    def loadUseData(self):
        dom_document = QtXml.QDomDocument()
        file = open(self.appPathDict["usedata"], "r")
        dom_document.setContent(file.read())
        file.close()

        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))
        self.loadKeymap()
Пример #16
0
 def get_allowed_kf_services(self):
     allowed_kf_services = {}
     allowed_kf_services['any_type'] = {'services': []}
     url_to_get = self.replace_variables(KF_SERVICES_URL)
     response = urlopen(url_to_get)
     xml = response.read()
     doc = QtXml.QDomDocument()
     doc.setContent(xml)
     service_types = doc.documentElement().childNodes()
     i = 0
     while i < service_types.count():
         service_type = service_types.at(i)
         service_type_name = service_type.nodeName()
         allowed_kf_services[service_type_name] = {'services': []}
         services = service_type.childNodes()
         j = 0
         while j < services.count():
             service = services.at(j)
             service_name = service.nodeName()
             allowed_kf_services[service_type_name]['services'].append(
                 service_name)
             allowed_kf_services['any_type']['services'].append(
                 service_name)
             j = j + 1
         i = i + 1
     return allowed_kf_services
Пример #17
0
    def readHFile(self, device):
        """
            Обработка с услугами
        """
        doc = QtXml.QDomDocument()
        doc.setContent(device)
        root = doc.documentElement()
        if root.tagName() != u'ZL_LIST':
            self.err2log(u'Некорректная структура H-файла.')
            return False

        if not self.checkVersion(root):
            self.err2log(u'Некорректная версия обмена в H-файле.')
            return False

        zglv = root.firstChildElement('ZGLV')
        self.date = QtCore.QDate.fromString(
            zglv.firstChildElement('DATA').text(), QtCore.Qt.ISODate)
        if not self.date.isValid():
            self.date = QtCore.QDate.currentDate()

        self.accountIdSet = set()
        zap = root.firstChildElement('ZAP')
        while not zap.isNull():
            QtGui.qApp.processEvents()
            self.processZap(zap)
            zap = zap.nextSiblingElement('ZAP')

        updateAccounts(self.accountIdSet)

        return 0
    def _xmlMerge(self, path):
        """Merges all edf-xml files in the given directory into a temporary
        file

        Args:
        -----
        path: str
            path to the Elmer xml-files configuration files

        """
        # create a temporary file
        mybuf = tempfile.TemporaryFile()

        gen_file = path + "edf.xml"

        # general settings
        first = et.parse(gen_file).getroot()

        # solver settings
        xml_files = glob.glob(path + "*.xml")
        xml_files = [file for file in xml_files if not os.path.basename(file).startswith("edf")]
        xml_files = [file for file in xml_files if not os.path.basename(file).startswith("eg")]

        for xml_file in xml_files:
            data = et.parse(xml_file).getroot()
            first.extend(data)

        mybuf.write(et.tostring(first))
        mybuf.seek(0)
        temp = mybuf.read().decode()
        mybuf.close()

        self._elmerDefs = QtXml.QDomDocument()
        self._elmerDefs.setContent(temp)
Пример #19
0
    def __init__(self, parent=None):
        super(TreeWidget, self).__init__(parent)
        self.setAcceptDrops(True)
        #self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.InternalMove)

        self.setObjectName("treeWidget")
        self.setMinimumSize(QtCore.QSize(170, 425))
        self.setMaximumSize(QtCore.QSize(170, 65525))
        self.setGeometry(QtCore.QRect(10, 135, 170, 425))

        self.header().setResizeMode(QtGui.QHeaderView.Stretch)
        self.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.header().setResizeMode(QHeaderView.ResizeToContents)
        self.header().setStretchLastSection(False)
        self.header().hide()
        self.setHeaderLabels([""])
        self.setExpandsOnDoubleClick(True)
        self.domDocument = QtXml.QDomDocument()
        self.domElementForItem = {}
        self.folderIcon = QtGui.QIcon()
        self.bookmarkIcon = QtGui.QIcon()
        self.folderIcon.addPixmap(
            self.style().standardPixmap(QtGui.QStyle.SP_DirClosedIcon),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.folderIcon.addPixmap(
            self.style().standardPixmap(QtGui.QStyle.SP_DirOpenIcon),
            QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.bookmarkIcon.addPixmap(self.style().standardPixmap(
            QtGui.QStyle.SP_FileIcon))
Пример #20
0
 def _lSlot(self, state):
     """Event when CheckBox changed"""
     self._param = QtXml.QDomElement()
     q = QtGui.QObject.sender().property("dom address").toString()
 
     ind = int(q.lastIndexOf( '/', -1))
     ids = str(q.mid(ind,-1))
 
     self._param = self.qhash[q].elem.firstChildElement("Activate")
     while(self._param.isNull() != False):
         q = str(self._param.text()).strip() + ids
         self.qhash[q].widget.setEnabled(state)
         widget_visible = self.qhash[q].elem.attribute("Visible","Unknown")
         if(state == False & widget_visible != "Unknown"):
             self.qhash[q].label.hide()
             self.qhash[q].widget.hide()
         else:
           self.qhash[q].label.show()
           self.qhash[q].widget.show()
         self._param = self._param.nextSiblingElement("Activate")
 
     self._param = self.qhash[q].elem.firstChildElement("Deactivate")
     while(self._param.isNull() != False):
          q = str(self._param.text()).strip() + ids
          self.qhash[q].widget.setEnabled(-state)
          widget_visible = self.qhash[q].elem.attribute("Visible","Unknown")
          if(state == True & widget_visible != "Unknown" ):
              self.qhash[q].label.hide()
              self.qhash[q].widget.hide()
          else:
              self.qhash[q].label.show()
              self.qhash[q].widget.show()
     self._param = self._param.nextSiblingElement("Deactivate")
Пример #21
0
    def load(self):
        dom_document = QtXml.QDomDocument()
        file = open(self.projectPathDict["buildprofile"], "r")
        dom_document.setContent(file.read())
        file.close()

        dataDict = {}

        elements = dom_document.documentElement()
        node = elements.firstChild()
        while node.isNull() is False:
            name = node.nodeName()
            expandedName = name.replace('-', ' ')
            if expandedName in self.lists:
                sub_node = node.firstChild()
                while sub_node.isNull() is False:
                    sub_prop = sub_node.toElement()
                    self.lists[expandedName].append(sub_prop.text())
                    sub_node = sub_node.nextSibling()
                dataDict[expandedName] = self.lists[expandedName]
            else:
                sub_prop = node.toElement()
                dataDict[name] = sub_prop.text()
            node = node.nextSibling()
        return dataDict
Пример #22
0
    def getHtml(self):
        """ HTML output, used to print the list """
        while (self.canFetchMore()):
            self.fetchMore()
        htmlDocument = QtXml.QDomDocument("list")
        html = htmlDocument.createElement("html")
        htmlDocument.appendChild(html)
        body = htmlDocument.createElement("body")
        html.appendChild(body)
        table = htmlDocument.createElement("table")
        table.setAttribute("style", "border: 1px solid black")
        table.setAttribute("border", "none")
        body.appendChild(table)
        for i in range(0, self.rowCount()):
            row = htmlDocument.createElement("tr")
            data = htmlDocument.createElement("td")
            piggeonId = self.index(i, 1).data().toString()
            piggeonId += "-"
            piggeonId += self.index(i, 2).data().toString()
            piggeonId += "-"
            piggeonId += self.index(i, 3).data().toString()
            text = htmlDocument.createTextNode(piggeonId)
            data.appendChild(text)
            row.appendChild(data)
            for j in range(4, 10):
                data = htmlDocument.createElement("td")
                text = htmlDocument.createTextNode(
                    self.index(i, j).data().toString())
                data.appendChild(text)
                row.appendChild(data)
            table.appendChild(row)
#		fichero = file ("/tmp/fichero.html", "w")
#		fichero.write (htmlDocument.toString ())
#		fichero.close ()
        return htmlDocument.toString()
Пример #23
0
    def loadModulesForCompletion(self):
        dom_document = QtXml.QDomDocument()
        try:
            file = open(self.appPathDict["modules"], "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

        element = dom_document.documentElement()
        node = element.firstChild()

        self.libraryDict = {}
        while node.isNull() is False:
            property = node.toElement()
            sub_node = property.firstChild()

            moduleName = node.nodeName()
            use = property.attribute('use')

            itemList = []
            while sub_node.isNull() is False:
                sub_prop = sub_node.toElement()
                itemList.append(sub_prop.text())

                sub_node = sub_node.nextSibling()
            self.libraryDict[moduleName] = [itemList, use]
            node = node.nextSibling()
Пример #24
0
    def load(self, filename):
        try:
            fileXml = open(unicode(filename), 'r')
            textXml = fileXml.read()
            fileXml.close()
        except IOError:
            raise RuntimeError('Cannot open book file %s' % filename)

        document = QtXml.QDomDocument()

        if not document.setContent(QtCore.QString.fromUtf8(textXml)):
            raise RuntimeError('Error parsing book file %s' % filename)

        root = document.documentElement()
        if root.tagName() != 'book':
            raise RuntimeError('Unexpected book format in file %s' % filename)

        self.title = root.attribute('title', 'Untitled')
        self.overwrite = root.attribute('overwrite', 'true' if Book.DefaultOverwrite else 'false') == 'true'
        self.device = root.attribute('device', Book.DefaultDevice)
        self.outputFormat = root.attribute('outputFormat', Book.DefaultOutputFormat)
        self.imageFlags = int(root.attribute('imageFlags', str(Book.DefaultImageFlags)))
        self.filename = filename
        self.modified = False
        self.images = []

        items = root.elementsByTagName('image')
        if items is None:
            return

        for i in xrange(0, len(items)):
            item = items.at(i).toElement()
            if item.hasAttribute('filename'):
                self.images.append(item.attribute('filename'))
Пример #25
0
def create_qgis_template_output(output_path, composition):
    """Produce QGIS Template output.

    :param output_path: The output path.
    :type output_path: str

    :param composition: QGIS Composition object to get template.
        values
    :type composition: qgis.core.QgsComposition

    :return: Generated output path.
    :rtype: str
    """
    # make sure directory is created
    dirname = os.path.dirname(output_path)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    template_document = QtXml.QDomDocument()
    element = template_document.createElement('Composer')
    composition.writeXML(element, template_document)
    template_document.appendChild(element)

    with open(output_path, 'w') as f:
        f.write(template_document.toByteArray())

    return output_path
Пример #26
0
    def readProject(self, path):
        # validate project
        project_file = os.path.join(path, "project.xml")
        if os.path.exists(project_file) is False:
            return False
        dom_document = QtXml.QDomDocument()
        file = open(os.path.join(path, "project.xml"), "r")
        dom_document.setContent(file.read())
        file.close()

        data = {}

        elements = dom_document.documentElement()
        node = elements.firstChild()
        while node.isNull() is False:
            tag = node.toElement()
            name = tag.tagName()
            data["Version"] = tag.attribute("Version")
            data["Type"] = tag.attribute("Type")
            data["Name"] = tag.attribute("Name")
            data["MainScript"] = tag.attribute("MainScript")
            node = node.nextSibling()

        if name != "pcode_project":
            return False
        else:
            return name, data
Пример #27
0
    def save(self, filename):
        document = QtXml.QDomDocument()

        root = document.createElement('book')
        document.appendChild(root)

        root.setAttribute('title', self.title)
        root.setAttribute('overwrite', 'true' if self.overwrite else 'false')
        root.setAttribute('device', self.device)
        root.setAttribute('imageFlags', self.imageFlags)
        root.setAttribute('outputFormat', self.outputFormat)

        for filenameImg in self.images:
            itemImg = document.createElement('image')
            root.appendChild(itemImg)
            itemImg.setAttribute('filename', filenameImg)

        textXml = document.toString(4).toUtf8()

        try:
            fileXml = open(unicode(filename), 'w')
            fileXml.write(textXml)
            fileXml.close()
        except IOError:
            raise RuntimeError('Cannot create book file %s' % filename)

        self.filename = filename
        self.modified = False
Пример #28
0
    def saveKeymap(self, path=None):
        dom_document = QtXml.QDomDocument("keymap")

        keymap = dom_document.createElement("keymap")
        dom_document.appendChild(keymap)

        for key, value in self.useData.CUSTOM_SHORTCUTS.items():
            root = dom_document.createElement(key)
            keymap.appendChild(root)

            for short, func in value.items():
                tag = dom_document.createElement(short)
                if key == "Editor":
                    shortName = func[0]
                    keyValue = str(func[1])
                    tag.setAttribute("shortcut", shortName)
                    tag.setAttribute("value", keyValue)
                else:
                    tag.setAttribute("shortcut", func)
                root.appendChild(tag)

        if path is None:
            path = self.useData.appPathDict["keymap"]
        file = open(path, "w")
        file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        file.write(dom_document.toString())
        file.close()
 def got_allowed_kf_services_handler(self, reply):
     if reply.error() == QNetworkReply.NoError:
         allowed_kf_services = {}
         allowed_kf_services['any_type'] = {'services': []}
         xml = str(reply.readAll())
         doc = QtXml.QDomDocument()
         doc.setContent(xml)
         service_types = doc.documentElement().childNodes()
         i = 0
         while i<service_types.count():
             service_type = service_types.at(i)
             service_type_name= service_type.nodeName()
             allowed_kf_services[service_type_name] = {'services': []}
             services = service_type.childNodes()
             j = 0
             while j<services.count():
                 service = services.at(j)
                 service_name = service.nodeName()
                 allowed_kf_services[service_type_name]['services'].append(service_name)
                 allowed_kf_services['any_type']['services'].append(service_name)
                 j = j + 1
             i = i + 1
         self.allowed_kf_services = allowed_kf_services
         self.debug_write_allowed_services()
         self.get_kf_qlr_file()
     else:
         self.report_network_error("allowed services" + reply.errorString())
Пример #30
0
    def populateTable(self,filePath):
        self.filePath = filePath
        ui = self
        table = ui.tableWidget
#        table.clear()
        table.setRowCount(0)
        xml = file(filePath).read()
        d = QtXml.QDomDocument()
        d.setContent(xml)
        maps = d.elementsByTagName("maplayer")
        self.maps=maps

        for i in range(maps.length()):
            table.setRowCount(table.rowCount()+1)
            info = getMapInfo(maps.item(i))
            nameItem = QTableWidgetItem(info['name'])
            nameItem.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
            nameItem.setCheckState(QtCore.Qt.Unchecked)
            nameItem.setData(QtCore.Qt.UserRole,str(i))
            table.setItem(i,0,nameItem)
            table.setItem(i,1,FixedWidgetItem(info['mtype']))
            table.setItem(i,2,FixedWidgetItem(info['geom']))
            table.setItem(i,3,FixedWidgetItem(info['provider']))
            ds = FixedWidgetItem(info['ds'])
            ds.setData(QtCore.Qt.ToolTipRole,info['ds'])
            table.setItem(i,4,ds)