示例#1
0
 def _deleteDocument(self,templatePath):
     """
     Delete the document template from the file system.
     """
     docFile = QFile(templatePath)
     
     return docFile.remove()
示例#2
0
    def _grep_file(self, file_path, file_name):
        if not self.by_phrase:
            with open(file_path, 'r') as f:
                content = f.read()
            words = [word for word in
                self.search_pattern.pattern().split('|')]
            words.insert(0, True)

            def check_whole_words(result, word):
                return result and content.find(word) != -1
            if not reduce(check_whole_words, words):
                return
        file_object = QFile(file_path)
        if not file_object.open(QFile.ReadOnly):
            return

        stream = QTextStream(file_object)
        lines = []
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not (stream.atEnd() and not line):
            column = self.search_pattern.indexIn(line)
            if column != -1:
                lines.append((line_index, line))
            #take the next line!
            line = stream.readLine()
            line_index += 1
        #emit a signal!
        relative_file_name = file_manager.convert_to_relative(
            self.root_dir, file_path)
        self.emit(SIGNAL("found_pattern(PyQt_PyObject)"),
            (relative_file_name, lines))
示例#3
0
    def accept(self):
        if self.inputFiles is None:
            workDir = QDir(self.leInputDir.text())
            workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot)
            nameFilter = ["*.shp", "*.SHP"]
            workDir.setNameFilters(nameFilter)
            self.inputFiles = workDir.entryList()
            if len(self.inputFiles) == 0:
                QMessageBox.warning(
                    self, self.tr("No shapefiles found"),
                    self.tr("There are no shapefiles in this directory. Please select another one."))
                self.inputFiles = None
                return

        if self.outFileName is None:
            QMessageBox.warning(
                self, self.tr("No output file"),
                self.tr("Please specify output file."))
            return

        if self.chkListMode.isChecked():
            files = self.leInputDir.text().split(";")
            baseDir = QFileInfo(files[0]).absolutePath()
        else:
            baseDir = self.leInputDir.text()
            # look for shapes with specified geometry type
            self.inputFiles = ftools_utils.getShapesByGeometryType(baseDir, self.inputFiles, self.cmbGeometry.currentIndex())
            if self.inputFiles is None:
                QMessageBox.warning(
                    self, self.tr("No shapefiles found"),
                    self.tr("There are no shapefiles with the given geometry type. Please select an available geometry type."))
                return
            self.progressFiles.setRange(0, len(self.inputFiles))

        outFile = QFile(self.outFileName)
        if outFile.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.outFileName):
                QMessageBox.warning(self, self.tr("Delete error"), self.tr("Can't delete file %s") % (self.outFileName))
                return

        if self.inEncoding is None:
            self.inEncoding = "System"

        self.btnOk.setEnabled(False)

        self.mergeThread = ShapeMergeThread(baseDir, self.inputFiles, self.inEncoding, self.outFileName, self.encoding)
        QObject.connect(self.mergeThread, SIGNAL("rangeChanged( PyQt_PyObject )"), self.setFeatureProgressRange)
        QObject.connect(self.mergeThread, SIGNAL("checkStarted()"), self.setFeatureProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("checkFinished()"), self.resetFeatureProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("fileNameChanged( PyQt_PyObject )"), self.setShapeProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("featureProcessed()"), self.featureProcessed)
        QObject.connect(self.mergeThread, SIGNAL("shapeProcessed()"), self.shapeProcessed)
        QObject.connect(self.mergeThread, SIGNAL("processingFinished()"), self.processingFinished)
        QObject.connect(self.mergeThread, SIGNAL("processingInterrupted()"), self.processingInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.mergeThread.start()
示例#4
0
def createMap(filename):
    """
    Creates a Python dictionary from a CSV file. The CSV file must be semicolon
    separated (";") and must not contain quotes.
    """

    # Open the CSV file
    file = QFile( "%s/%s" % (basedir,filename))
    file.open(QIODevice.OpenMode(QIODevice.ReadOnly))

    map = {}

    # Read all lines
    while True:
        qByteArray = file.readLine()
        # Break the while loop when the end is reached
        if qByteArray.size() == 0:
            break
        # Remove the trailing end line
        line = QString(qByteArray).remove(QRegExp("\n"))
        # Split the line
        list = line.split(";")
        # Set the key and value to the map
        map[str(list[0].toUpper().toUtf8())] = str(list[1].toUtf8())

    return map
示例#5
0
def write_file(filename, content):
    _file = QFile(filename)
    if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate):
        raise EdisIOError
    outfile = QTextStream(_file)
    outfile << content
    return filename
示例#6
0
 def save_file(self):
     """
     Saving file to the path where getting from QFileDialog
     """
     fileobject = None
     if self.path is "":
         self.path = QFileDialog.getSaveFileName(self,
                                             "TextEditor", 
                                             self.tr("unnamed"))
     try:
         fileobject = QFile(self.path)
         if not fileobject.open(QIODevice.WriteOnly):
             raise IOError, unicode(fileobject.errorString())
         textstream = QTextStream(fileobject)
         textstream.setCodec("UTF-8")
         textstream << self.textEdit.toPlainText()
         self.textEdit.document().setModified(False)
         self.setWindowTitle("%s - TextEditor" % 
                             QFileInfo(self.path).fileName())
     except (IOError, OSError), error:
         QMessageBox.warning(self, 
                             self.tr("TextEditor - Save Error"), 
                             self.tr("Unable to save {0}:{1}".format( 
                             self.path, error)))
         self.path = ""
示例#7
0
	def exportTextFile(self, fh=None, header=None, data=None):
		"""Writes data to the given file. Accepts column names and the data as
		arguments

		"""
		if not fh:
			self.mkError("Could not open file for writing")
			return

		if not data:
			data = []

		if not len(data):
			self.mkWarn("No data to write")
			return

		fname = QFile(fh)
		if fname.open(QFile.WriteOnly | QFile.Text):
			txt = QTextStream(fname)
			if header:
				txt << ", ".join(col for col in header)
			txt << "\n"
			txt << "\n".join(", ".join(item) for item in data)

			msg = "File export complete: {0}".format(str(fname.fileName()))
			self.mkSuccess(msg)
示例#8
0
文件: downloads.py 项目: Jerk31/pyrex
class DownloadFtp(Download):
    def __init__(self, file_share, local_path, date):
        Download.__init__(self, file_share, local_path, date)
        self.ftp = QFtp(self)
        self.ftp.dataTransferProgress.connect(self.update_progress)
        self.ftp.done.connect(self.download_finished)
        self.ftp.stateChanged.connect(self.state_changed)
        self.url = QUrl(self._file_share.url)
        self.out_file = QFile(self.local_path)

        self.read_bytes = self.out_file.size() 
 
    def start_download(self):
        self.ftp.connectToHost(self.url.host(), self.url.port(21))
        self.ftp.login()
        
        if self.out_file.open(QIODevice.WriteOnly):
            self.ftp.get(self.url.path(), self.out_file)

    def stop(self):
        self.ftp

    def state_changed(self, state):
        if state == 1 or state == 2:
            self._state = 1

    def download_finished(self, _):
        print "finished !"

    def update_progress(self, read_bytes, total_bytes):
        self.read_bytes = read_bytes
    def testQgsSvgMarkerSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsSvgMarkerSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators (QString ('%1/symbol_layer/%2.sld').arg (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsSvgMarkerSymbolLayerV2.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

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

        mExpectedValue = QString(u'skull.svg')
        mValue = os.path.basename (str(mSymbolLayer.path()))
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 12
        mValue = mSymbolLayer.size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 45
        mValue = mSymbolLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
示例#10
0
 def save(self, new):
     fh = QFile("tools/" + self.name + ".tool")
     if new and fh.exists():
         return False
     if fh.open(QIODevice.WriteOnly):
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='%s'?>\n<!DOCTYPE TOOL>\n<TOOL\n" % CODEC)
         stream << (
             "TIPDIAM='%s'\nSYRDIAM='%s'\nPATHWIDTH='%s'\nPATHHEIGHT='%s'\nJOGSPEED='%s'\nSUCKBACK='%s'\nPUSHOUT='%s'\n"
             "PATHSPEED='%s'\nPAUSEPATHS='%s'\nCLEARANCE='%s'\nDEPOSITIONRATE='%s'\n>"
             % (
                 self.tipDiam,
                 self.syrDiam,
                 self.pathWidth,
                 self.pathHeight,
                 self.jogSpeed,
                 self.suckback,
                 self.pushout,
                 self.pathSpeed,
                 self.pausePaths,
                 self.clearance,
                 self.depRate,
             )
         )
         stream << ("\n</TOOL>")
         fh.close()
     return True
示例#11
0
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        print("Unable to set stylesheet, file not found\n")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        return ts.readAll()
示例#12
0
文件: cdrom.py 项目: JonnyJD/picard
 def get_cdrom_drives():
     drives = list(DEFAULT_DRIVES)
     cdinfo = QFile(LINUX_CDROM_INFO)
     if cdinfo.open(QIODevice.ReadOnly | QIODevice.Text):
         drive_names = []
         drive_audio_caps = []
         line = cdinfo.readLine()
         while not line.isEmpty():
             if line.indexOf(':') != -1:
                 key, values = line.split(':')
                 if key == 'drive name':
                     drive_names = QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)
                 elif key == 'Can play audio':
                     drive_audio_caps = [v == '1' for v in
                                         QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)]
                     break  # no need to continue passed this line
             line = cdinfo.readLine()
         # Show only drives that are capable of playing audio
         for index, drive in enumerate(drive_names):
             if drive_audio_caps[index]:
                 device = u'/dev/%s' % drive
                 symlink_target = QFile.symLinkTarget(device)
                 if symlink_target != '':
                     device = symlink_target
                 drives.append(device)
     return sorted(uniqify(drives))
示例#13
0
    def downloadFile(self, url_to_download, fout):
        " get the file from remote url to local folder "
        url = QUrl(url_to_download)
        fileInfo = QFileInfo(url.path())
        fileName = path.join(fout, str(fileInfo.fileName()))

        if QFile.exists(fileName):
            QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(
                self, "ERROR", "Cant save the file %s: %s." % (fileName, self.outFile.errorString())
            )
            self.outFile = None
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.httpRequestAborted = False

        tpath = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if tpath:
            tpath = str(tpath)
        else:
            tpath = sep
        # Download the file.
        print(" INFO: Blender Download Started ! ")
        self.httpGetId = self.http.get(tpath, self.outFile)
示例#14
0
 def importDOM(self, fname):
     dom = QDomDocument()
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         if not dom.setContent(fh):
             raise ValueError("could not parse XML")
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
     try:
         self.populateFromDOM(dom)
     except ValueError as e:
         return False, "Failed to import: {0}".format(e)
     self.__fname = QString()
     self.__dirty = True
     return True, "Imported {0} movie records from {1}".format(
                 len(self.__movies), QFileInfo(fname).fileName())
示例#15
0
文件: cdrom.py 项目: hartzell/picard
 def get_cdrom_drives():
     drives = []
     cdinfo = QFile(LINUX_CDROM_INFO)
     if cdinfo.open(QIODevice.ReadOnly | QIODevice.Text):
         drive_names = []
         drive_audio_caps = []
         line = cdinfo.readLine()
         while not line.isEmpty():
             if line.indexOf(':') != -1:
                 key, values = line.split(':')
                 if key == 'drive name':
                     drive_names = QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)
                 elif key == 'Can play audio':
                     drive_audio_caps = [v == '1' for v in
                                         QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)]
             line = cdinfo.readLine()
         # Show only drives that are capable of playing audio
         for drive in drive_names:
             if drive_audio_caps[drive_names.indexOf(drive)]:
                 device = u'/dev/%s' % drive
                 symlink_target = QFile.symLinkTarget(device)
                 if symlink_target != '':
                     device = symlink_target
                 drives.append(device)
     return sorted(drives)
示例#16
0
    def testQgsCentroidFillSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = 'QgsCentroidFillSymbolLayerV2'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

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

        mExpectedValue = u'regular_star'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'#55aaff'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'#00ff00'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
示例#17
0
    def go_to_definition(self):
        self.dirty = True
        self.results = []
        locations = self.get_locations()
        if self._isVariable:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if (x.type == FILTERS['attribs']) and (x.name == self._search)]
        else:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if ((x.type == FILTERS['functions']) or
                    (x.type == FILTERS['classes'])) and
                   (x.name.startswith(self._search))]
        for data in preResults:
            file_object = QFile(data[1])
            if not file_object.open(QFile.ReadOnly):
                return

            stream = QTextStream(file_object)
            line_index = 0
            line = stream.readLine()
            while not self._cancel and not stream.atEnd():
                if line_index == data[2]:
                    data[3] = line
                    self.results.append(data)
                    break
                #take the next line!
                line = stream.readLine()
                line_index += 1
示例#18
0
    def downloadFile(self, url, archivo_destino):
        url = QUrl(url)
        fileName = archivo_destino
        directorio_usuario_para_pilas = os.path.dirname(archivo_destino)

        if not os.path.exists(directorio_usuario_para_pilas):
            os.mkdir(directorio_usuario_para_pilas)

        if QFile.exists(fileName):
            QFile.remove(fileName)

        self.outFile = QFile(fileName)

        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(self, 'Error', 'Lo siento, no se puede descargar el archivo desde %s: %s.' % (self.url, self.outFile.errorString()))
            self.outFile = None
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.httpRequestAborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        self.httpGetId = self.http.get(path, self.outFile)
def main():

    GlobalVariables.init()
     
    app = QApplication([])

    File = QFile("darkorange.stylesheet")
    File.open(QFile.ReadOnly)
    StyleSheet = QLatin1String(File.readAll())    
 
    app.setStyleSheet(StyleSheet)

    tdviz = TDViz.TDVizCustom()
    tdviz.show()
    
    if GlobalVariables.isprojector: # @UndefinedVariable
        tdviz.setGeometry(1920, 0, 1280, 1024)
    else:
        tdviz.showFullScreen()    

    yscreenf = 1.0*tdviz._renWin.GetSize()[1]/1080.0

    cam = tdviz._ren.GetActiveCamera()
    cam.SetScreenBottomLeft(-262.5,148.5-148.5*2.0*yscreenf,-410)
    cam.SetScreenBottomRight(262.5,148.5-148.5*2.0*yscreenf,-410)
    cam.SetScreenTopRight(262.5,148.5,-410) 

    sys.exit(app.exec_())   
示例#20
0
    def downloadFile(self, url_to_download, download_location):
        url = QUrl(url_to_download)
        fileInfo = QFileInfo(url.path())
        #fileName = fileInfo.fileName()
        fileName = download_location + fileInfo.fileName()
        self.file_name = fileName
        print("Filename = " + fileName)

        if QFile.exists(fileName):
            QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(self, 'Error',
                    'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.httpRequestAborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        # Download the file.
        self.httpGetId = self.http.get(path, self.outFile)
        return fileName
示例#21
0
    def template_document(self, path):
        """
        Reads the document template file and returns the corresponding
        QDomDocument.
        :param path: Absolute path to template file.
        :type path: str
        :return: A tuple containing the template document and error message
        where applicable
        :rtype: tuple
        """
        if not path:
            return None, QApplication.translate("DocumentGenerator",
                                                "Empty path to document template")

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

        template_file = QFile(path)

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

        template_doc = QDomDocument()

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

        return None, QApplication.translate("DocumentGenerator",
                                            "Cannot read document template contents")
示例#22
0
def parse_knitting_symbol(symbolPath):
    """
    Parse the knitting symbol located at path symbolPath.
    """

    descriptionFile = QFile(symbolPath + "/description")
    if (not descriptionFile.exists()) or descriptionFile.error():
        return None

    # parse XML
    dom = QDomDocument()
    (status, msg, line, col) = dom.setContent(descriptionFile)
    if not status:
        errorMessage = ("Failed reading pattern description in file %s -- "
                        "%s at line %d column %d" % 
                        (descriptionFile.fileName(), msg, line, col))
        logger.error(errorMessage)
        return None

    # make sure we're reading a sconcho pattern description 
    root = dom.documentElement()
    if root.tagName() != "sconcho":
        return None

    # parse the actual content
    node = root.firstChild()
    if node.toElement().tagName() != "knittingSymbol":
        return None
  
    content = parse_symbol_description(node)

    # add the absolute path
    content["svgPath"] = symbolPath + "/" + content["svgName"] + ".svg"

    return content
示例#23
0
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #353434;
                text-align: center;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
示例#24
0
 def load(self):
     exception = None
     fh = None
     try:
         if self.filename.isEmpty():
             raise IOError, "no filename specified for loading"
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError, unicode(fh.errorString())
         stream = QDataStream(fh)
         magic = stream.readInt32()
         if magic != MAGIC_NUMBER:
             raise IOError, "unrecognized file type"
         fileVersion = stream.readInt16()
         if fileVersion != FILE_VERSION:
             raise IOError, "unrecognized file type version"
         self.ships = []
         while not stream.atEnd():
             name = QString()
             owner = QString()
             country = QString()
             description = QString()
             stream >> name >> owner >> country >> description
             teu = stream.readInt32()
             self.ships.append(Ship(name, owner, country, teu,
                                    description))
             self.owners.add(unicode(owner))
             self.countries.add(unicode(country))
         self.dirty = False
     except IOError, e:
         exception = e
示例#25
0
 def open(self):
     self.offerSave()
     path = (QFileInfo(self.filename).path()
             if not self.filename.isEmpty() else ".")
     fname = QFileDialog.getOpenFileName(self,
             "Page Designer - Open", path,
             "Page Designer Files (*.pgd)")
     if fname.isEmpty():
         return
     self.filename = fname
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError, unicode(fh.errorString())
         items = self.scene.items()
         while items:
             item = items.pop()
             self.scene.removeItem(item)
             del item
         self.addBorders()
         stream = QDataStream(fh)
         stream.setVersion(QDataStream.Qt_4_2)
         magic = stream.readInt32()
         if magic != MagicNumber:
             raise IOError, "not a valid .pgd file"
         fileVersion = stream.readInt16()
         if fileVersion != FileVersion:
             raise IOError, "unrecognised .pgd file version"
         while not fh.atEnd():
             self.readItemFromStream(stream)
     except IOError, e:
         QMessageBox.warning(self, "Page Designer -- Open Error",
                 "Failed to open {0}: {1}".format(self.filename, e))
示例#26
0
    def getActivePlugins(self, filename=None):
        '''
        Function checks xml and returns if plugin was active on previous program execution
        xmlfile: specifies alternative path to xml file with plugin information
        '''

        if not filename:
            filename = self.xmlFile

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

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

            for i in range(nodeList.length()):
                bpNode = nodeList.at(i).toElement()
                path = str(bpNode.attribute("path"))
                if path in self.pluginActions:
                    self.pluginActions[path].setLoaded(bpNode.attribute("active") == "y")
                else:
                    logging.warning("No plugin for %s found, maybe it was moved/deleted?", path)
示例#27
0
文件: about.py 项目: Guillon88/stdm
    def __init__(self,parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        #Connect signals
        self.btnContactUs.clicked.connect(self.onContactUs)
        self.btnSTDMHome.clicked.connect(self.onSTDMHome)

        #Load about HTML file
        aboutLocation = PLUGIN_DIR + "/html/about.htm"
        if QFile.exists(aboutLocation):
            aboutFile = QFile(aboutLocation)
            if not aboutFile.open(QIODevice.ReadOnly):
                QMessageBox.critical(self,
                                     QApplication.translate("AboutSTDMDialog","Open Operation Error"),
                                     QApplication.translate("AboutSTDMDialog","Cannot read 'About STDM' source file."))
                self.reject()

            reader = QTextStream(aboutFile)
            aboutSTDM = reader.readAll()
            self.txtAbout.setHtml(aboutSTDM)

        else:
            QMessageBox.critical(self,
                                 QApplication.translate("AboutSTDMDialog","File Does Not Exist"),
                                 QApplication.translate("AboutSTDMDialog","'About STDM' source file does not exist."))
            self.reject()
示例#28
0
    def save(self):
        """Hum ... just save ..."""
        if self.filename.startswith("Unnamed"):
            filename = self.parent().parent().parent().saveAsFile()
            if not (filename == ''):
                return
            self.filename = filename
        self.setWindowTitle( QFileInfo(self.filename).fileName())
        exception = None
        filehandle = None
        try:
            #Before FileSave plugin hook
            for plugin in filter_plugins_by_capability('beforeFileSave',self.enabled_plugins):
                plugin.do_beforeFileSave(self)

            filehandle =  QFile(self.filename)
            if not filehandle.open( QIODevice.WriteOnly):
                raise IOError, unicode(filehandle.errorString())
            stream =  QTextStream(filehandle)
            stream.setCodec("UTF-8")
            stream << self.toPlainText()
            self.document().setModified(False)
            RecentFiles().append(self.filename)
        except (IOError, OSError), ioError:
            exception = ioError
示例#29
0
 def _replace_results(self):
     result = QMessageBox.question(self, self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in xrange(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = unicode(parent.dir_name_root)
             file_name = unicode(parent.text(0))
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
    def testQgsSVGFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsSVGFillSymbolLayer')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

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

        mExpectedValue = 'accommodation_camping.svg'
        mValue = os.path.basename (str (mSymbolLayer.svgFilePath()))
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 6
        mValue = mSymbolLayer.patternWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
示例#31
0
    def apply(self, photo_item, composerWrapper, fromTemplate=False):
        if not isinstance(photo_item, QgsComposerPicture):
            return

        #Get the main picture editor widget and configure widgets
        picture_editor = composerWrapper.itemDock().widget()
        if not picture_editor is None:
            self._configure_picture_editor_properties(picture_editor)

        if not fromTemplate:
            if self.has_frame:
                # Enable outline in map composer item
                frame_width = 0.15
                photo_item.setFrameEnabled(True)
                photo_item.setFrameOutlineWidth(frame_width)

            photo_item.setResizeMode(QgsComposerPicture.ZoomResizeFrame)

            #Create data properties editor and it to the dock widget
            photo_data_source_editor = self._item_editor_cls(composerWrapper)
            stdmDock = composerWrapper.stdmItemDock()
            stdmDock.setWidget(photo_data_source_editor)

            #Add widget to the composer wrapper widget mapping collection
            composerWrapper.addWidgetMapping(photo_item.uuid(), photo_data_source_editor)

        # Set default photo properties
        if QFile.exists(self.default_photo):
            photo_item.setPictureFile(self.default_photo)

        #Set ID to match UUID
        photo_item.setId(photo_item.uuid())
示例#32
0
    def loadProject(self):
        if Settings.isProjectConfigured():
            self.projectGroupIndex = layers.createLayerGroup(self._plugin.iface, Config.projectGroupName)

            # Load the layer collections
            self._addCollection('grid')
            self._addCollection('plan')
            self._addCollection('section')
            self._addCollection('site')
            self.drawingsGroupName = Config.drawings['context']['layersGroupName']
            if (self.collection('grid').loadCollection()
                    and self.collection('plan').loadCollection()
                    and self.collection('section').loadCollection()
                    and self.collection('site').loadCollection()):

                self._dock.loadProject(self._plugin)

                if self.collection('plan').isLogged():
                    self._itemLogPath = os.path.join(self.collection('plan').projectPath,
                                                     self.collection('plan').settings.collectionPath,
                                                     'log/itemLog.csv')
                    if not QFile.exists(self._itemLogPath):
                        fd = open(self._itemLogPath, 'a')
                        fd.write('timestamp,action,siteCode,classCode,itemId\n')
                        fd.close()

                    # TODO Think of a better way...
                    # self.metadata = Metadata(self._dock.widget.sourceWidget)
                    # self.metadata.metadataChanged.connect(self.updateMapToolAttributes)
            self._initialised = True
            return True
        return False
示例#33
0
 def __pre_execution(self):
     """Execute a script before executing the project."""
     filePreExec = QFile(self.preExec)
     if filePreExec.exists() and \
             bool(QFile.ExeUser & filePreExec.permissions()):
         ext = file_manager.get_file_extension(self.preExec)
         if not self.pythonExec:
             self.pythonExec = settings.PYTHON_PATH
         self.currentProcess = self._preExecScriptProc
         self.__preScriptExecuted = True
         if ext == 'py':
             self._preExecScriptProc.start(self.pythonExec, [self.preExec])
         else:
             self._preExecScriptProc.start(self.preExec)
     else:
         self.__main_execution()
示例#34
0
    def validateCurrentPage(self):
        #Validate the current page before proceeding to the next one
        validPage = True

        if not QFile.exists(unicode(self.field("srcFile"))):
            self.ErrorInfoMessage("The specified source file does not exist.")
            validPage = False

        else:
            if self.dataReader:
                self.dataReader.reset()
            self.dataReader = OGRReader(unicode(self.field("srcFile")))

            if not self.dataReader.isValid():
                self.ErrorInfoMessage("The source file could not be opened."
                                      "\nPlease check is the given file type "
                                      "is supported")
                validPage = False

        if self.currentId() == 1:
            if self.destCheckedItem == None:
                self.ErrorInfoMessage("Please select the destination table.")
                validPage = False

        if self.currentId() == 2:
            validPage = self.execImport()

        return validPage
示例#35
0
    def apply(self, chart_item, composerWrapper, fromTemplate=False):
        if not isinstance(chart_item, QgsComposerPicture):
            return

        #Get the main picture editor widget and configure widgets
        picture_editor = composerWrapper.itemDock().widget()
        if not picture_editor is None:
            self._configure_picture_editor_properties(picture_editor)

        if not fromTemplate:
            #Disable outline in map composer item
            chart_item.setFrameEnabled(False)

            #Create data properties editor and it to the dock widget
            graph_config_editor = ComposerChartConfigEditor(composerWrapper)
            stdmDock = composerWrapper.stdmItemDock()
            stdmDock.setWidget(graph_config_editor)

            #Add widget to the composer wrapper widget mapping collection
            composerWrapper.addWidgetMapping(chart_item.uuid(), graph_config_editor)

        #Set default photo properties
        default_chart_pic = PLUGIN_DIR + "/images/icons/chart-512.png"
        if QFile.exists(default_chart_pic):
            chart_item.setPictureFile(default_chart_pic)

        #Set ID to match UUID
        chart_item.setId(chart_item.uuid())
示例#36
0
 def _styleFile(self, layerPath, layerName):
     # First see if the layer itself has a default style saved
     filePath = layerPath + '/' + layerName + '.qml'
     if QFile.exists(filePath):
         return filePath
     # Next see if the layer name has a style in the styles folder (which may
     # be a special folder, the site folder or the plugin folder)
     filePath = Settings.stylePath() + '/' + layerName + '.qml'
     if QFile.exists(filePath):
         return filePath
     # Finally, check the plugin folder for the default style
     filePath = self._pluginStylesPath() + '/' + layerName + '.qml'
     if QFile.exists(filePath):
         return filePath
     # If we didn't find that then something is wrong!
     return ''
示例#37
0
    def _build_photo_path(self, composition, composer_id,
                          document_parent_table, document_type, doc_id,
                          doc_name):
        pic_item = composition.getComposerItemById(composer_id)

        if pic_item is None:
            return

        extensions = doc_name.rsplit(".", 1)
        if len(extensions) < 2:
            return

        network_ph_path = network_document_path()
        if not network_ph_path:
            return

        img_extension = extensions[1]
        profile_name = self._current_profile.name.replace(' ', '_').lower()
        abs_path = u'{0}/{1}/{2}/{3}/{4}.{5}'.format(network_ph_path,
                                                     profile_name,
                                                     document_parent_table,
                                                     document_type, doc_id,
                                                     img_extension)

        if QFile.exists(abs_path):
            self._composeritem_value_handler(pic_item, abs_path)
示例#38
0
 def saveFile(self):
     ''' Save source file '''
     if (QFile.exists(self.filename)):
         f = open(self.filename, 'w')
         f.write(self.text())
         f.close()
         self.openFile()
示例#39
0
 def requestFinished(self):
     reply = self.sender()
     self.buttonBox.setEnabled(False)
     if reply.error() != QNetworkReply.NoError:
         self.mResult = reply.errorString()
         if reply.error() == QNetworkReply.OperationCanceledError:
             self.mResult += "<br/><br/>" + QCoreApplication.translate(
                 "QgsPluginInstaller",
                 "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options."
             )
         self.reject()
         reply.deleteLater()
         return
     self.file.open(QFile.WriteOnly)
     self.file.write(reply.readAll())
     self.file.close()
     self.stateChanged(0)
     reply.deleteLater()
     pluginDir = qgis.utils.home_plugin_path
     tmpPath = self.file.fileName()
     # make sure that the parent directory exists
     if not QDir(pluginDir).exists():
         QDir().mkpath(pluginDir)
     # if the target directory already exists as a link, remove the link without resolving:
     QFile(pluginDir + unicode(QDir.separator()) +
           self.plugin["id"]).remove()
     try:
         unzip(
             unicode(tmpPath), unicode(pluginDir)
         )  # test extract. If fails, then exception will be raised and no removing occurs
         # removing old plugin files if exist
         removeDir(QDir.cleanPath(
             pluginDir + "/" +
             self.plugin["id"]))  # remove old plugin if exists
         unzip(unicode(tmpPath), unicode(pluginDir))  # final extract.
     except:
         self.mResult = self.tr(
             "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:"
         ) + "\n" + pluginDir
         self.reject()
         return
     try:
         # cleaning: removing the temporary zip file
         QFile(tmpPath).remove()
     except:
         pass
     self.close()
示例#40
0
    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            msgBox = QMessageBox()
            msgBox.setTextFormat(Qt.RichText)
            dtdict = DICT_xml(self.dlg.lineEdit.text())
            # Prépare le formulaire
            titre, pdf = dtdict.formulaire()
            planPDF = dtdict.geometriePDF(titre)
            if QFile.exists(pdf) and \
                    all([QFile.exists(p) for p in planPDF]) and \
                    pdf and len(planPDF) > 0:
                out = QSettings().value("/DICT/configRep")

                fusion = QSettings().value("/DICT/fusionPDF") == u"true"

                if(fusion and
                   self.__checkPdftk(QSettings().value("/DICT/configPDFTK"))):
                    # Utilise pdftk pour fusionner les documents
                    s = os.path.join(out, u"envoi_" + titre + u".pdf")
                    subprocess.call([QSettings().value(
                                    "/DICT/configPDFTK"), pdf] +
                                    planPDF + ["cat", "output"] + [s])

                    msgBox.setText(u"Vous pouvez envoyer le fichier :" +
                                   "<br><a href='file://" + s + "'>" +
                                   s + "</a>")

                    os.remove(pdf)
                    for p in planPDF:
                        os.remove(p)
                else:
                    msgBox.setText(u"Vous pouvez envoyer les fichiers :" +
                                   u"<br>Récepissé : " + pdf + "<br>" +
                                   u"Plans : " + str(planPDF) + "<br>")

            else:
                msgBox.setText(u"Erreur lors de la création des fichiers :\
                \nRécepissé : "+pdf+u"\n \
                Plan : "+str(planPDF))

            msgBox.exec_()
示例#41
0
    def _prepare_specific_files(self, specification):
        """Prepare specific templates and files.

        :param specification: Specification instance containing template
            replacement keys/values.
        :type specification: PluginSpecification
        """
        for template_name, output_name in \
                self.template.template_files(specification).iteritems():
            self.populate_template(specification, self.template_dir,
                                   template_name, output_name)

        # copy the non-generated files to the new plugin dir
        for template_file, output_name in \
                self.template.copy_files(specification).iteritems():
            file = QFile(os.path.join(self.template_dir, template_file))
            file.copy(os.path.join(self.plugin_path, output_name))
示例#42
0
    def _add_raster_layer(self, raster_layer, layer_name):
        """Add a raster layer to the folder.

        :param raster_layer: The layer to add.
        :type raster_layer: QgsRasterLayer

        :param layer_name: The name of the layer in the datastore.
        :type layer_name: str

        :returns: A two-tuple. The first element will be True if we could add
            the layer to the datastore. The second element will be the layer
            name which has been used or the error message.
        :rtype: (bool, str)

        .. versionadded:: 4.0
        """
        if not self.is_writable():
            return False, 'The destination is not writable.'

        output = QFileInfo(self.uri.filePath(layer_name + '.tif'))

        source = QFileInfo(raster_layer.source())
        if source.exists() and source.suffix() in ['tiff', 'tif']:
            # If it's tiff file based.
            QFile.copy(source.absoluteFilePath(), output.absoluteFilePath())

        else:
            # If it's not file based.
            renderer = raster_layer.renderer()
            provider = raster_layer.dataProvider()
            crs = raster_layer.crs()

            pipe = QgsRasterPipe()
            pipe.set(provider.clone())
            pipe.set(renderer.clone())

            file_writer = QgsRasterFileWriter(output.absoluteFilePath())
            file_writer.Mode(1)

            file_writer.writeRaster(pipe, provider.xSize(), provider.ySize(),
                                    provider.extent(), crs)

            del file_writer

        assert output.exists()
        return True, output.baseName()
示例#43
0
def copy_holders_configuration():
    """
    Copies the default configuration for holders data source to destination
    mapping if there is none in the .stdm folder.
    """
    holders_config_path = u'{0}/templates/holders_config.ini'.format(
        os.path.dirname(__file__))

    # Exit if the holder config mapping does not exist
    if not QFile.exists(holders_config_path):
        return

    # Copy mapping file if none existed in USER_PLUGIN_DIR
    holders_conf_file = QFile(holders_config_path)
    holders_conf_dest = u'{0}/holders_config.ini'.format(USER_PLUGIN_DIR)

    copy_status = holders_conf_file.copy(holders_conf_dest)
示例#44
0
 def regularize(self, bound, outPath, offset, value, gridType, inset, crs):
     area = bound.width() * bound.height()
     if offset:
         seed()
     if gridType:
         pointSpacing = value
     else:
         # Calculate grid spacing
         pointSpacing = sqrt(area / value)
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     fields = QgsFields()
     fields.append(QgsField("ID", QVariant.Int))
     outFeat.setFields(fields)
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields,
                                  QGis.WKBPoint, crs)
     idVar = 0
     count = 10.00
     add = 90.00 / (area / pointSpacing)
     y = bound.yMaximum() - inset
     while y >= bound.yMinimum():
         x = bound.xMinimum() + inset
         while x <= bound.xMaximum():
             if offset:
                 pGeom = QgsGeometry().fromPoint(
                     QgsPoint(
                         uniform(x - (pointSpacing / 2.0),
                                 x + (pointSpacing / 2.0)),
                         uniform(y - (pointSpacing / 2.0),
                                 y + (pointSpacing / 2.0))))
             else:
                 pGeom = QgsGeometry().fromPoint(QgsPoint(x, y))
             if pGeom.intersects(bound):
                 outFeat.setGeometry(pGeom)
                 outFeat.setAttribute(0, idVar)
                 writer.addFeature(outFeat)
                 idVar = idVar + 1
                 x = x + pointSpacing
                 count = count + add
                 self.progressBar.setValue(count)
         y = y - pointSpacing
     del writer
示例#45
0
def copy_search_configuration():
    """
    Copies the configuration file containing the search settings to the
    user's ./stdm/search folder.
    """
    search_conf_path = u'{0}/templates/search/configuration.ini'.format(
        os.path.dirname(__file__))

    # Exit if the search config file does not exist
    if not QFile.exists(search_conf_path):
        return

    # Copy settings file if none existed in USER_PLUGIN_DIR
    search_conf_file = QFile(search_conf_path)
    search_conf_dest = u'{0}/search/configuration.ini'.format(USER_PLUGIN_DIR)

    copy_status = search_conf_file.copy(search_conf_dest)
def handle_download(reply):
    print "Download finish time: {}".format(datetime.now())
    print "Finished: {}".format(reply.isFinished())
    # print "Bytes received: {}".format(len(reply.readAll()))
    print(type(reply), dir(reply), help(reply.write))
    url = reply.url().path()
    print(url)
    #    with open("C:\Users\julien.moura\Documents\GIS DataBase\youhou.xml", "wb") as fifi:
    #        fifi.write(reply.writeData())
    newFile = QFile()
    newFile.setFileName(
        "C:\Users\julien.moura\Documents\GIS DataBase\youhou_2.htm")
    newFile.open(QIODevice.WriteOnly)
    newFile.write(reply.readAll())
    newFile.close()
    print("done")
    reply.deleteLater()
示例#47
0
    def acceptConnection(self):
        self.tcpServerConnection = self.tcpServer.nextPendingConnection()
        self.tcpServerConnection.readyRead.connect(self.updateLog)
        self.tcpServerConnection.error.connect(self.displayError)

        self.file = QFile(self.filename)
        if not self.file.open(QFile.Append):
            QMessageBox.warning(
                self, self.title, "Unable to write file {}:\n{}.".format(
                    self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.serverStatusLabel.setText("Logging ...")
        self.tcpServer.close()
示例#48
0
    def on_pushButton_4_clicked(self):

        # 我们先清空显示,然后显示“无法添加!”,这样如果添加失败则会显示“无法添加!”
        self.listWidget.clear()
        self.listWidget.addItem(QString("无法添加!"))
        file = QFile("my.xml")
        if (not file.open(QIODevice.ReadOnly)):
            raise Exception("open my.xml Err")
        doc = QDomDocument()

        status, rrorMsg, errorLine, errorColumn = doc.setContent(file)
        if not status:
            file.close()
            raise Exception(str(rrorMsg))

        file.close()
        root = doc.documentElement()  # 获取根元素
        book = doc.createElement(QString("图书"))
        id = doc.createAttribute(QString("编号"))
        title = doc.createElement(QString("书名"))
        author = doc.createElement(QString("作者"))
        text = QDomText()

        # 我们获得了最后一个孩子结点的编号,然后加1,便是新的编号
        num = root.lastChild().toElement().attribute(QString("编号"))
        count = num.toInt() + 1
        id.setValue(QString.number(count))

        book.setAttributeNode(id)
        text = doc.createTextNode(self.lineEdit_2.text())
        title.appendChild(text)
        text = doc.createTextNode(self.lineEdit_3.text())
        author.appendChild(text)
        book.appendChild(title)
        book.appendChild(author)
        root.appendChild(book)

        if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)):
            raise Exception("file open Err")

        out = QTextStream(file)
        doc.save(out, 4)
        file.close()
        # 最后更改显示为“添加成功!”
        self.listWidget.clear()
        self.listWidget.addItem(QString("添加成功!"))
示例#49
0
def get_style(style_sheet):
    try:
        mod = importlib.import_module("." + style_sheet, __name__)
        hasattr(mod, "qt_resource_name")
        f = QFile(":/%s/style.qss" % style_sheet)
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
    except ImportError as e:
        print "Style sheet not available. Use available_styles() to check for valid styles"
        return u""
    except Exception as e:
        print "Style sheet available, but an error occured..."
        traceback.print_exc()
        return u""

    return stylesheet
示例#50
0
def loadShapefileLayer(filePath, layerName):
    layer = None
    layerList = QgsMapLayerRegistry.instance().mapLayersByName(layerName)
    if (len(layerList) > 0):
        layer = layerList[0]
    elif QFile.exists(filePath):
        layer = QgsVectorLayer(filePath, layerName, 'ogr')
    return layer
示例#51
0
 def downloadFinished(self, reply):
     if reply.error():
         print("Failed to download")
     else:
         attFile = QFile(self.downloadAs)
         attFile.open(QIODevice.WriteOnly)
         attFile.write(reply.readAll())
         attFile.close()
         print("Succeeded")
     reply.deleteLater()
示例#52
0
    def load_viewer(self, document_widget, visible=True):
        """
        Open a new instance of the viewer or activate an existing one if the
        document had been previously loaded.
        :param document_widget: Contains all the necessary information required
        to load the specific document.
        :type document_widget: DocumentWidget
        :param visible: True to show the view manager after the viewer has
        been loaded, otherwise it will be the responsibility of the caller to
        enable visibility.
        :type visible: bool
        :returns: True if the document was successfully loaded, else False.
        :rtype: bool
        """
        doc_identifier = document_widget.file_identifier()

        if doc_identifier in self._doc_viewers:

            doc_sw = self._doc_viewers[doc_identifier]

            self._mdi_area.setActiveSubWindow(doc_sw)
            doc_sw.showNormal()

        else:
            doc_viewer = self._create_viewer(document_widget)

            abs_doc_path = self.absolute_document_path(document_widget)

            if not QFile.exists(abs_doc_path):
                msg = QApplication.translate(
                    "DocumentViewManager",
                    "The selected document does not exist."
                    "\nPlease check the supporting documents' "
                    "repository setting.")
                QMessageBox.critical(
                    self,
                    QApplication.translate("DocumentViewManager",
                                           "Invalid Document"), msg)

                return False

            doc_viewer.load_document(abs_doc_path)

            self._doc_viewers[doc_identifier] = doc_viewer

            self._mdi_area.addSubWindow(doc_viewer)

            doc_viewer.show()

        if not self.isVisible() and visible:
            self.setVisible(True)

        if self.isMinimized():
            self.showNormal()

        self.center()

        return True
示例#53
0
def load_stylesheet(pyside=True):
    """
    Load the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet() will not receive pyside parameter in version 3. "
        "Set QtPy environment variable to specify the Qt binding insteady.",
        FutureWarning
    )
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
示例#54
0
    def saveLog(self):
        save = QFileDialog.getSaveFileName(self, u"Protokolldatei angeben",
                                           ".", "Protokoll-Dateien (*.log)")
        if save is None:
            return

        f = QFile(save)
        if not f.open(QIODevice.WriteOnly):
            return

        for i in range(0, self.lwProtocol.count()):
            f.write(self.lwProtocol.item(i).text().encode("utf-8", "ignore"))
            f.write(os.linesep)
        f.close()
示例#55
0
    def save(self, content, path=None):
        """
        Write a temprorary file with .tnj extension and copy it over the
        original one.
        .nsf = Ninja Swap File
        #FIXME: Where to locate addExtension, does not fit here
        """
        if path and self._file_path:
            created_file = NFile(path).save(content)
            self.emit(SIGNAL("savedAsNewFile(PyQt_PyObject, QString, QString)"),
                        created_file, self._file_path, path)
            return created_file
        elif path and not self._file_path:
            self.attach_to_path(path)

        save_path = self._file_path

        if not save_path:
            raise NinjaNoFileNameException("I am asked to write a "
                                "file but no one told me where")
        swap_save_path = u"%s.nsp" % save_path

        flags = QIODevice.WriteOnly | QIODevice.Truncate
        f = QFile(swap_save_path)
        if settings.use_platform_specific_eol():
            flags |= QIODevice.Text

        if not f.open(flags):
            raise NinjaIOException(f.errorString())

        stream = QTextStream(f)
        encoding = get_file_encoding(content)
        if encoding:
            stream.setCodec(encoding)

        encoded_stream = stream.codec().fromUnicode(content)
        f.write(encoded_stream)
        f.flush()
        f.close()
        #SIGNAL: Will save (temp, definitive) to warn folder to do something
        self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path,
                                                        save_path)
        shutil.move(swap_save_path, save_path)
        self.reset_state()
        return self
示例#56
0
    def get_searchable_content(self):
        """
        Pulls out tags from the object and returns them in order to be used by the filtered() method.
        """
        f = QFile(self.fileinfo.absoluteFilePath())
        f.open(QIODevice.ReadOnly)
        #stream = QTextStream(f)
        #stream.setCodec("UTF-8")
        try:
            doc = QDomDocument()
            doc.setContent( f.readAll() )
            docelt = doc.documentElement()

            texts = []

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

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

            return u' '.join(texts)
        finally:
            f.close()
示例#57
0
    def on_pushButton_5_clicked(self):

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

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

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

        n = docElem.firstChild()
        while (not n.isNull()):
            if (n.isElement()):
                e = n.toElement()
                self.listWidget.addItem(e.tagName() +
                                        e.attribute(QString("编号")))
                list = e.childNodes()
                for i in range(list.count()):
                    node = list.at(i)
                    if (node.isElement()):
                        self.listWidget.addItem("   " +
                                                node.toElement().tagName() +
                                                " : " +
                                                node.toElement().text())
            n = n.nextSibling()
示例#58
0
    def deleteDocument(self, docmodel=None, doc_type=None):
        """
        Delete the source document from the central repository.
        """
        if not docmodel is None:
            #Build the path from the model variable values.
            fileName, fileExt = guess_extension(docmodel.filename)
            profile_name = self.curr_profile.name
            #Qt always expects the file separator be be "/" regardless of platform.
            absPath = '{}/{}/{}/{}/{}{}'.format(
                self.networkPath, profile_name.lower(), docmodel.source_entity,
                doc_type.lower().replace(' ', '_'),
                docmodel.document_identifier, fileExt)

            return QFile.remove(absPath)

        else:
            return QFile.remove(self.destinationPath)
示例#59
0
 def isValidDatabase(self, path):
     if not QFile.exists(path):
         return False
     try:
         conn = sqlite.connect(path)
     except self.connection_error_types() as e:
         return False
     conn.close()
     return True
示例#60
0
 def upload(self, filePath, returnDict=True):
     self.returnDict = returnDict
     file = QFile(filePath)
     file.open(QFile.ReadOnly)
     url = QUrl(self.apiUrl + "imports/?api_key={}".format(self.apiKey))
     files = {'file': file}
     multipart = self._createMultipart(files=files)
     request = QNetworkRequest(url)
     request.setHeader(
         QNetworkRequest.ContentTypeHeader,
         'multipart/form-data; boundary=%s' % multipart.boundary())
     request.setRawHeader('User-Agent', 'QGISCartoDB 0.2.x')
     reply = self.manager.post(request, multipart)
     loop = QEventLoop()
     reply.uploadProgress.connect(self.progressCB)
     reply.error.connect(self._error)
     reply.finished.connect(loop.exit)
     loop.exec_()