示例#1
0
文件: __init__.py 项目: gltn/stdm
def copy_core_configuration():
    """
    Copies the basic STDM configuration to the user directory if there is none.
    """
    core_config_path = u'{0}/templates/configuration.stc'.format(
        os.path.dirname(__file__)
    )

    #Exit if the core configuration does not exist
    if not QFile.exists(core_config_path):
        return

    #File name of previous configuration
    v1_1_config_path = u'{0}/stdmConfig.xml'.format(USER_PLUGIN_DIR)

    #Only copy the new one if there is no copy of the previous version
    # since the version updater will automatically handle the upgrade.
    if QFile.exists(v1_1_config_path):
        #Version update will handle the migration
        return

    #Copy config assuming that the plugin user folder has no previous
    # configuration.
    conf_file = QFile(core_config_path)
    conf_dest = u'{0}/configuration.stc'.format(USER_PLUGIN_DIR)

    copy_status = conf_file.copy(conf_dest)
示例#2
0
文件: fTools.py 项目: Geoneer/QGIS
 def getThemeIcon(self, icon):
     settings = QSettings()
     pluginPath = os.path.dirname(__file__)
     themePath = "icons" + QDir.separator() + settings.value("/Themes", "default") + QDir.separator() + icon
     defaultPath = "icons" + QDir.separator() + "default" + QDir.separator() + icon
     if QFile.exists(pluginPath + QDir.separator() + themePath):
         return QIcon(":" + themePath)
     elif QFile.exists(pluginPath + QDir.separator() + defaultPath):
         return QIcon(":" + defaultPath)
     else:
         return QIcon()
示例#3
0
 def getThemeIcon(iconName):
     iconName = '/' + iconName
     if QFile.exists(QgsApplication.activeThemePath() + iconName):
         return QIcon(QgsApplication.activeThemePath() + iconName)
     elif QFile.exists(QgsApplication.defaultThemePath() + iconName):
         return QIcon(QgsApplication.defaultThemePath() + iconName)
     else:
         themePath = ':/icons/' + QSettings().value('/Themes', '', str) + iconName
         if QFile.exists(themePath):
             return QIcon(themePath)
         else:
             return QIcon(':/icons/default' + iconName)
示例#4
0
文件: islem.py 项目: mthnzbk/parcala
 def run(self):
     self.ui.label.setText(self.ui.ui.neredenEdit.text())
     dosyaOku = QFile(self.ui.ui.neredenEdit.text())
     dosyaOku.open(QIODevice.ReadOnly)
     oku = 1024*1024
     partBoyutu = int(self.ui.ui.mbEdit.text())
     self.ui.progressBar.setMaximum(dosyaOku.size()/oku)
     partAdi = self.ui.ui.nereyeEdit.text()
     sayac = 0
     partSayici = 1
     while not dosyaOku.atEnd():
         partAdi = "%s%s"%(partAdi[:-3], str(partSayici).zfill(3))
         self.ui.label2.setText(partAdi)
         partSayici += 1
         dosyaYaz = QFile(partAdi)
         if dosyaYaz.exists() and not self.uzerineYaz:
             self.emit(SIGNAL("durdur"))
             return
         dosyaYaz.open(QIODevice.WriteOnly)
         #self.uzerineYaz = False
         for i in range(partBoyutu):
             dosyaYaz.writeData(dosyaOku.read(oku))
             sayac += 1
             self.emit(SIGNAL("value"), sayac)
             self.msleep(1)
             if dosyaOku.atEnd(): break
         dosyaYaz.close()
     self.msleep(500)
示例#5
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
 def _loadBufferLayer(self, sourceLayer, layerPath, layerName):
     layer = None
     layerId = ''
     layerList = QgsMapLayerRegistry.instance().mapLayersByName(layerName)
     if (len(layerList) > 0):
         layer = layerList[0]
         self._iface.legendInterface().moveLayer(layer, self._bufferGroupIndex)
     else:
         fullLayerPath = self.projectPath + '/' + layerPath
         if (layerName and layerPath and sourceLayer and sourceLayer.isValid()):
             if not QFile.exists(fullLayerPath):
                 # If the layer doesn't exist, clone from the source layer
                 layer = layers.cloneAsShapefile(sourceLayer, fullLayerPath, layerName)
             else:
                 # If the layer does exist, then load it and copy the style
                 layer = QgsVectorLayer(fullLayerPath, layerName, 'ogr')
             layer = layers.addLayerToLegend(self._iface, layer, self._bufferGroupIndex)
     if layer and layer.isValid():
         layerId = layer.id()
         layers.loadStyle(layer, fromLayer=sourceLayer)
         self._setDefaultSnapping(layer)
         layer.startEditing()
         layer.setFeatureFormSuppress(QgsVectorLayer.SuppressOn)
         self._iface.legendInterface().setLayerExpanded(layer, False)
     else:
         layer = None
     return layer, layerId
示例#7
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()
示例#8
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 ''
示例#9
0
    def downloadFile(self):
        url = QUrl(self.url_to_download)

        fileName = QFileDialog.getSaveFileName(self, "Enregistrer la liste des dossiers", self.nameFile, "conf")

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

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(self, 'Erreur','Impossible d\'enregistrer le fichier %s: %s.' % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        #Création que la connexion HTTPS
        mode = QHttp.ConnectionModeHttps
        port = 0
        self.http.setHost(url.host(), mode, port)
        
        self.requeteHTTPannule = False
        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        #Concaténation des paramètres à l'URL
        path = path+("?")
        for item in url.queryItems():
            path = path + item[0] + "=" + item[1] + "&" 
        
        self.http.setUser(self.login, self.password)
        self.httpGetId = self.http.get(path, self.outFile)
示例#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 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
示例#12
0
 def downloadFile(self):
     url = QUrl(self.downloadUrl)
     fileInfo = QFileInfo(url.path())
     #fileName = fileInfo.fileName()
     fileName = self.targetDirectory + fileInfo.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
     print url
     path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
     if path:
         path = str(path)
     else:
         path = '/'
     # Right at the end we append the query string that is lost, the original author did not include this unfortunately.
     parsedUrl = urlparse(self.downloadUrl)
     if not parsedUrl.query == '':
         # fix this mess, otherwise leave it alone
         path = path + "?" + parsedUrl.query
         print path
     # Download the file.
     self.httpGetId = self.http.get(path, self.outFile)
示例#13
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
示例#14
0
 def updateFileMenu(self):
     """
     Creates new file menu everytime the user invokes it. File menu can't be created
     only once, because of recent files section which has to be refreshed.
     """
     self.fileMenu.clear()
     # add all fixed actions, but close
     self.fileMenu.addActions(self.fileMenuActions[:-1])
     current = QString(self.model.fname) \
             if self.model.fname is not None else None
     recentFiles = []
     for fname in self.recentFiles:
         if fname != current and QFile.exists(fname):
             recentFiles.append(fname)
     if recentFiles:
         self.fileMenu.addSeparator()
         self.recentFilesMenu = self.fileMenu.addMenu("Recent Files")
         for i, fname in enumerate(recentFiles):
             action = QAction("&%d %s" % (
                     i + 1, QFileInfo(fname).fileName()), self)
             action.setData(QVariant(fname))
             self.connect(action, SIGNAL("triggered()"),
                          lambda file = fname: self.loadRecentFile(file))
             self.recentFilesMenu.addAction(action)
     self.fileMenu.addSeparator()
     # add the last action - close
     self.fileMenu.addAction(self.fileMenuActions[-1])
示例#15
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()
示例#16
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)
示例#17
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")
示例#18
0
 def loadTemplate(self,filePath):
     """
     Loads a document template into the view and updates the necessary STDM-related controls.
     """
     if not QFile.exists(filePath):
             QMessageBox.critical(self.composerView(), QApplication.translate("OpenTemplateConfig","Open Template Error"), \
                                         QApplication.translate("OpenTemplateConfig","The specified template does not exist."))
             return
         
     templateFile = QFile(filePath)
     
     if not templateFile.open(QIODevice.ReadOnly):
         QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Open Operation Error"), \
                                         "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Cannot read template file."), \
                                                   templateFile.errorString()
                                                   ))
         return    
      
     templateDoc = QDomDocument()
     
     if templateDoc.setContent(templateFile):
         #Load items into the composition and configure STDM data controls
         self.composition().loadFromTemplate(templateDoc)
         self.clearWidgetMappings()
         
         #Load data controls
         composerDS = ComposerDataSource.create(templateDoc)
         self._configureDataControls(composerDS)
         
         #Load symbol editors
         spatialFieldsConfig = SpatialFieldsConfiguration.create(templateDoc)
         self._configureSpatialSymbolEditor(spatialFieldsConfig)
示例#19
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
示例#20
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()
示例#21
0
 def _loadLogLayer(self, sourceLayer, layerPath, layerName):
     layer = None
     layerId = ''
     layerList = QgsMapLayerRegistry.instance().mapLayersByName(layerName)
     if (len(layerList) > 0):
         layer = layerList[0]
         self._iface.legendInterface().moveLayer(layer, self._bufferGroupIndex)
     else:
         fullLayerPath = self.projectPath + '/' + layerPath
         if (layerName and layerPath and sourceLayer and sourceLayer.isValid()):
             if not QFile.exists(fullLayerPath):
                 # If the layer doesn't exist, clone from the source layer
                 layer = layers.cloneAsShapefile(sourceLayer, fullLayerPath, layerName)
                 if layer and layer.isValid():
                     layer.dataProvider().addAttributes([QgsField('timestamp', QVariant.String, '', 10, 0, 'timestamp')])
                     layer.dataProvider().addAttributes([QgsField('event', QVariant.String, '', 6, 0, 'event')])
             else:
                 # If the layer does exist, then load it and copy the style
                 layer = QgsVectorLayer(fullLayerPath, layerName, 'ogr')
                 if layer and layer.isValid():
                     layers.loadStyle(layer, fromLayer=sourceLayer)
     if layer and layer.isValid():
         layerId = layer.id()
         layer.setFeatureFormSuppress(QgsVectorLayer.SuppressOn)
         self._iface.legendInterface().setLayerExpanded(layer, False)
     else:
         layer = None
     return layer, layerId
示例#22
0
文件: import_data.py 项目: gltn/stdm
    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
示例#23
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)
示例#24
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())
示例#25
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()
示例#26
0
文件: islem.py 项目: mthnzbk/parcala
 def run(self):
     self.ui.label.setText(self.ui.ui.nereyeEdit.text())
     dosyaListesi = self.birlestir(self.ui.ui.neredenEdit.text())
     dosyaYaz = QFile(self.ui.ui.nereyeEdit.text())
     if dosyaYaz.exists() and not self.uzerineYaz:
         self.emit(SIGNAL("durdur"))
         return
     dosyaYaz.open(QIODevice.WriteOnly)
     
     oku = 1024*1024
     boyut = self.toplamBoyut(dosyaListesi)/oku
     self.ui.progressBar.setMaximum(boyut)
     sayac = 0
     for i in dosyaListesi:
         self.ui.label2.setText(i)
         dosyaOku = QFile(i)
         dosyaOku.open(QIODevice.ReadOnly)
         while not dosyaOku.atEnd():
             dosyaYaz.writeData(dosyaOku.read(oku))
             sayac += 1
             self.emit(SIGNAL("value"), sayac)
             self.msleep(1)
             if dosyaOku.atEnd(): break
     dosyaYaz.close()
     self.msleep(500)
示例#27
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())
示例#28
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:
            #Enable outline in map composer item
            frame_width = 0.15
            photo_item.setFrameEnabled(True)
            photo_item.setFrameOutlineWidth(frame_width)

            #Create data properties editor and it to the dock widget
            photo_data_source_editor = ComposerPhotoDataSourceEditor(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
        default_photo = PLUGIN_DIR + "/images/icons/photo_512.png"
        if QFile.exists(default_photo):
            photo_item.setPictureFile(default_photo)

        #Set ID to match UUID
        photo_item.setId(photo_item.uuid())
示例#29
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)
示例#30
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
示例#31
0
    def __init__(self, uri):
        DBConnector.__init__(self, uri)

        self.dbname = uri.database()
        if not QFile.exists(self.dbname):
            raise ConnectionError(
                QApplication.translate("DBManagerPlugin",
                                       '"{0}" not found').format(self.dbname))

        try:
            self.connection = sqlite.connect(self._connectionInfo())

        except self.connection_error_types() as e:
            raise ConnectionError(e)

        self._checkSpatial()
        self._checkRaster()
        self._checkGeopackage()
示例#32
0
    def accept(self):
        self.buttonOk.setEnabled(False)

        if self.inShape.currentText() == "":
            QMessageBox.information(self, self.tr("Eliminate"),
                                    self.tr("No input shapefile specified"))
        else:
            outFileName = self.outShape.text()

            if outFileName == "":
                QMessageBox.information(
                    self, self.tr("Eliminate"),
                    self.tr("Please specify output shapefile"))
                self.buttonOk.setEnabled(True)
                return None
            else:
                outFile = QFile(outFileName)

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

                outFileName = unicode(outFileName)

            inLayer = ftools_utils.getVectorLayerByName(
                unicode(self.inShape.currentText()))

            if inLayer.selectedFeatureCount() == 0:
                QMessageBox.information(self, self.tr("Eliminate"),
                                        self.tr("No selection in input layer"))
            else:
                self.progressBar.setValue(5)
                boundary = self.boundary.isChecked()
                self.eliminate(inLayer, boundary, self.progressBar,
                               outFileName)
                self.progressBar.setValue(100)
                self.outShape.clear()

        self.progressBar.setValue(0)
        self.buttonOk.setEnabled(True)
示例#33
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
    """
    # Validate that rc files is updated
    compile_qrc.compile_all()

    # Smart import of the rc file
    if pyside:
        import qdarkgraystyle.pyside_style_rc
    else:
        import qdarkgraystyle.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(':qdarkgraystyle/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
示例#34
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
示例#35
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 vnTrader.qdarkstyle.pyside_style_rc
    else:
        import vnTrader.qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        # PyQt 4/5 compatibility
        try:
            from PyQt4.QtCore import QFile, QTextStream
        except ImportError:
            from PyQt5.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
示例#36
0
文件: mainwindow.py 项目: vertrex/DFF
 def addHelpWidget(self):
     if hasattr(sys, "frozen"):
         path = os.path.abspath(
             os.path.join(os.path.dirname(sys.executable),
                          "resources/docs/dff_doc.qhc"))
     else:
         conf = Conf()
         path = conf.docPath
     file = QFile(path)
     if not file.exists(path):
         if path:
             dialog = QMessageBox.warning(
                 self, self.errorLoadingHelp,
                 QString(path) + ": " + self.notAnHelpFile)
         else:
             dialog = QMessageBox.warning(self, self.errorLoadingHelp,
                                          self.noSuchHelpFile)
         return
     self.addDockWidgets(Help(self, path=path), 'help')
示例#37
0
    def smethod_0(iwin32Window_0):
        FatoList.FatoList()
        fatoList = FatoList()

        if (not QFile.exists(FatoList.fileName)):
            return fatoList
        file0 = QFile(FatoList.fileName)
        file0.open(QIODevice.ReadOnly)
        dataStream = QDataStream(file0)
        str0 = dataStream.readQString()
        num = dataStream.readInt()
        if (not (str0 == "PHXHSAF") or num != 1):
            raise Messages.ERR_INVALID_FILE_FORMAT
            # throw new Exception(Messages.ERR_INVALID_FILE_FORMAT)
        num1 = dataStream.readInt()
        for i in range(num1):
            fatoList.append(Fato.smethod_0(dataStream, num))
        fatoList.method_1()
        return fatoList
示例#38
0
 def updateFileMenu(self):
     self.fileMenu.clear()
     self.addActions(self.fileMenu, self.fileMenuActions[:-1])
     current = (QString(self.filename)
                if self.filename is not None else None)
     recentFiles = []
     for fname in self.recentFiles:
         if fname != current and QFile.exists(fname):
             recentFiles.append(fname)
     if recentFiles:
         self.fileMenu.addSeparator()
         for i, fname in enumerate(recentFiles):
             action = QAction(QIcon(":/icon.png"),
                     "&{0} {1}".format(i + 1, QFileInfo(
                     fname).fileName()), self)
             action.setData(QVariant(fname))
             action.triggered.connect(self.loadFile)
             self.fileMenu.addAction(action)
     self.fileMenu.addSeparator()
     self.fileMenu.addAction(self.fileMenuActions[-1])
示例#39
0
文件: pqHelp.py 项目: jlg234bob/PPQT
    def __init__(self, parent=None):
        super(helpDisplay, self).__init__(parent)
        # make page unmodifiable
        self.page().setContentEditable(False)
        # initialize settings
        # Find out the nearest font to Palatino
        qf = QFont()
        qf.setStyleStrategy(QFont.PreferAntialias + QFont.PreferMatch)
        qf.setStyleHint(QFont.Serif)
        qf.setFamily(QString(u'Palatino'))
        qfi = QFontInfo(qf)
        # set the default font to that serif font
        self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family())
        self.settings().setFontSize(QWebSettings.DefaultFontSize, 16)
        self.settings().setFontSize(QWebSettings.MinimumFontSize, 6)
        self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
        self.textZoomFactor = 1.0
        self.setTextSizeMultiplier(self.textZoomFactor)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        self.settings().setAttribute(QWebSettings.JavaEnabled, False)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
        self.settings().setAttribute(QWebSettings.ZoomTextOnly, True)
        #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
        self.userFindText = QString()
        # Look for pqHelp.html in the app folder and copy its text into
        # a local buffer. If it isn't found, put a message there instead.
        # We need to keep it in order to implement the "back" function.
        helpPath = os.path.join(IMC.appBasePath, u'pqHelp.html')
        helpFile = QFile(helpPath)
        if not helpFile.exists():
            self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p>
	    <p>Looking in {0}'''.format(helpPath))
        elif not helpFile.open(QIODevice.ReadOnly):
            self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p>
	    <p>Looking in {0}</p><p>Error code {1}</p>'''.format(
                helpPath, helpFile.error()))
        else:
            helpStream = QTextStream(helpFile)
            helpStream.setCodec('ISO8859-1')
            self.HTMLstring = helpStream.readAll()
        self.setHtml(self.HTMLstring)
示例#40
0
    def load_workbook(self, path):
        """
        Loads the workbook contained in the specified file to the view.
        :param path: Path to fil containing workbook data.
        :type path: str
        """
        xfile = QFile(path)
        if not xfile.exists():
            QMessageBox.critical(
                self, self.tr('Invalid path'),
                u'\'{0}\' {1}'.format(path, self.tr('does not exist.')))

            return

        # Check permissions
        xfileinfo = QFileInfo(xfile)
        if not xfileinfo.isReadable():
            QMessageBox.critical(
                self, self.tr('Unreadable file'),
                u'{0} {1}'.format(path, self.tr('is not readable.')))

            return

        # Clear view
        self.clear_view()

        # Show progress bar
        self._pg_par.setVisible(True)
        pg_val = 0

        # Add sheets
        wb = open_workbook(path)
        self._pg_par.setRange(0, wb.nsheets)
        for s in wb.sheets():
            self.add_xlrd_sheet(s)

            # Update progress bar
            pg_val += 1
            self._pg_par.setValue(pg_val)

        self._pg_par.setVisible(False)
示例#41
0
    def __init__(self, parent=None, metadata=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self._metadata = metadata

        #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)
            #Insert plugin info
            self._insert_metadata_info()

        else:
            QMessageBox.critical(
                self,
                QApplication.translate("AboutSTDMDialog",
                                       "File Does Not Exist"),
                QApplication.translate(
                    "AboutSTDMDialog",
                    "'About STDM' source file does not exist."))
            self.reject()
示例#42
0
    def ReadUserInfoFile(self):
        try:
            if not QFile.exists(self.m_strUserInfoFullName):
                return
            file0 = QFile(self.m_strUserInfoFullName)
            file0.open(QIODevice.ReadOnly)
            dataStream = QDataStream(file0)
            str0 = dataStream.readQString()
            self.m_strUserInfoFullName = dataStream.readQString()
            self.m_Key = dataStream.readQString()
            self.m_IV = dataStream.readQString()
            userInfoCount = dataStream.readInt()
            for i in range(userInfoCount):
                userInfo = MYUSERINFO()
                userInfo.readData(dataStream)
                self.ListUserInfo.append(userInfo)

            file0.close()
            return True
        except:
            return False
示例#43
0
def check_for_recovery_file(filePath):
    """ Check for presence of recovery file. If we have
    one, ask we if should open if and return a tuple
    (status, filename of file to open).

    """

    returnPath = (False, filePath)
    recoveryFilePath = generate_recovery_filepath(filePath)
    recoveryFile = QFile(recoveryFilePath)
    fileName = QFileInfo(filePath).fileName()
    if recoveryFile.exists():
        answer = QMessageBox.question(
            None, msg.recoveryFilePresentTitle,
            msg.recoveryFilePresentText.format(fileName),
            QMessageBox.Ok | QMessageBox.Cancel)

        if (answer == QMessageBox.Ok):
            returnPath = (True, recoveryFilePath)

    return returnPath
示例#44
0
def load_stylesheet_pyqt5():
    """
    Load 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
    """
    warnings.warn(
        "load_stylesheet_pyqt5() will be deprecated in version 3,"
        "set QtPy environment variable to specify the Qt binding and "
        "use load_stylesheet()",
        PendingDeprecationWarning
    )
    # 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: #32414B;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
示例#45
0
def load_stylesheet_pyqt5():
    """
    Load 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
    """
    warnings.warn(
        "load_stylesheet_pyqt5() will be deprecated in version 3,"
        "set QtPy environment variable to specify the Qt binding and "
        "use load_stylesheet()", PendingDeprecationWarning)
    # Compiles SCSS/SASS files to QSS
    from qdarkstyle.utils.scss import create_qss
    create_qss()

    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QCoreApplication, QFile, QTextStream
    from PyQt5.QtGui import QColor, QPalette

    # Apply palette fix. See issue #139
    _apply_palette_fix(QCoreApplication, QPalette, QColor)

    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()

        # Apply OS specific patches
        # stylesheet = _apply_stylesheet_patches(stylesheet)
        return stylesheet
示例#46
0
    def downloadFile(self):

        url = QUrl(self.url_text.text())
        if self.txt_location.text() == "":
            QDir.setCurrent("$HOME/Downloads")
        else:
            QDir.setCurrent(self.loc)

        self.statusbar.showMessage("Downloading")

        fileInfo = QFileInfo(url.path())
        fileName = fileInfo.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 = '$HOME/Downloads'

        # Download the file.
        self.httpGetId = self.http.get(path, self.outFile)
示例#47
0
    def readThemeIndex(self, themeName):

        dirList = []
        parents = []
        themeIndex = QFile()

        # Read theme index files
        for i in range(len(self.iconDirs)):
            themeIndex.setFileName(
                path.join(unicode(self.iconDirs[i]), unicode(themeName),
                          "index.theme"))
            if themeIndex.exists():
                indexReader = QSettings(themeIndex.fileName(),
                                        QSettings.IniFormat)
                for key in indexReader.allKeys():
                    if key.endsWith("/Size"):
                        size = indexReader.value(key).toInt()
                        dirList.append(
                            (size[0], unicode(key.left(key.size() - 5))))
                parents = indexReader.value('Icon Theme/Inherits')
                parents = parents.toStringList()
                break
        return QIconTheme(dirList, parents)
示例#48
0
    def pageToFile(self, page):
        """ get filepath from page
            filepath = notePath + page + fileExt
            fileExt is stored in notebook.conf
        """

        # When exists foo.md, foo.mkd, foo.markdown,
        # the one with defExt will be returned
        extName = ['.md', '.mkd', '.markdown']
        defExt = self.settings.fileExt
        if defExt in extName:
            extName.remove(defExt)
        else:
            print("Warning: detected file extension name is", defExt)
            print("    Your config file is located in", self.notePath + "/notebook.conf")
        extName.insert(0, defExt)
        for ext in extName:
            filepath = os.path.join(self.notePath, page + ext)
            if QFile.exists(filepath):
                return filepath

        # return filename with default extension name even if file not exists.
        return os.path.join(self.notePath, page + defExt)
示例#49
0
    def geometry(self, myLayer, myParam, myField):
        if self.myFunction == 9:
            vlayer = ftools_utils.getMapLayerByName(myLayer)
        else:
            vlayer = ftools_utils.getVectorLayerByName(myLayer)

        if (self.myFunction == 5 and self.chkWriteShapefile.isChecked()) or self.myFunction != 5:
            check = QFile(self.shapefileName)
            if check.exists():
                if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                    QMessageBox.warning(self, self.tr("Geometry"),
                                        self.tr("Unable to delete existing shapefile."))
                    return

        if self.myFunction == 5 and not self.chkWriteShapefile.isChecked():
            self.shapefileName = None
            self.encoding = None

            res = QMessageBox.warning(self, self.tr("Geometry"),
                                      self.tr("Currently QGIS doesn't allow simultaneous access from "
                                              "different threads to the same datasource. Make sure your layer's "
                                              "attribute tables are closed. Continue?"),
                                      QMessageBox.Yes | QMessageBox.No)
            if res == QMessageBox.No:
                return

        self.buttonOk.setEnabled(False)
        self.testThread = geometryThread(self.iface.mainWindow(), self, self.myFunction,
                                         vlayer, myParam, myField, self.shapefileName, self.encoding,
                                         self.cmbCalcType.currentIndex(), self.chkWriteShapefile.isChecked(),
                                         self.chkByFeatures.isChecked(), self.chkUseSelection.isChecked())
        QObject.connect(self.testThread, SIGNAL("runFinished( PyQt_PyObject )"), self.runFinishedFromThread)
        QObject.connect(self.testThread, SIGNAL("runStatus( PyQt_PyObject )"), self.runStatusFromThread)
        QObject.connect(self.testThread, SIGNAL("runRange( PyQt_PyObject )"), self.runRangeFromThread)
        self.cancel_close.setText(self.tr("Cancel"))
        QObject.connect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread)
        self.testThread.start()
示例#50
0
 def _loadLogLayer(self, sourceLayer, layerPath, layerName):
     layer = None
     layerId = ''
     layerList = QgsMapLayerRegistry.instance().mapLayersByName(layerName)
     if (len(layerList) > 0):
         layer = layerList[0]
         self._iface.legendInterface().moveLayer(layer,
                                                 self._bufferGroupIndex)
     else:
         fullLayerPath = self.projectPath + '/' + layerPath
         if (layerName and layerPath and sourceLayer
                 and sourceLayer.isValid()):
             if not QFile.exists(fullLayerPath):
                 # If the layer doesn't exist, clone from the source layer
                 layer = layers.cloneAsShapefile(sourceLayer, fullLayerPath,
                                                 layerName)
                 if layer and layer.isValid():
                     layer.dataProvider().addAttributes([
                         QgsField('timestamp', QVariant.String, '', 10, 0,
                                  'timestamp')
                     ])
                     layer.dataProvider().addAttributes([
                         QgsField('event', QVariant.String, '', 6, 0,
                                  'event')
                     ])
             else:
                 # If the layer does exist, then load it and copy the style
                 layer = QgsVectorLayer(fullLayerPath, layerName, 'ogr')
                 if layer and layer.isValid():
                     layers.loadStyle(layer, fromLayer=sourceLayer)
     if layer and layer.isValid():
         layerId = layer.id()
         layer.setFeatureFormSuppress(QgsVectorLayer.SuppressOn)
         self._iface.legendInterface().setLayerExpanded(layer, False)
     else:
         layer = None
     return layer, layerId
示例#51
0
    def initTree(self, notepath, parent):
        if parent == "":
            # site wide index page
            htmlfile = os.path.join(self.sitepath, "index.html")
        else:
            # append subpages to page
            htmlfile = os.path.join(self.htmlpath, parent + ".html")
        html = QFile(htmlfile)
        html.open(QIODevice.Append)
        savestream = QTextStream(html)

        noteDir = QDir(notepath)
        notesList = noteDir.entryInfoList(['*.md', '*.mkd', '*.markdown'],
                                          QDir.NoFilter,
                                          QDir.Name | QDir.IgnoreCase)
        nl = [note.completeBaseName() for note in notesList]
        noduplicate = list(set(nl))
        noduplicate.sort(key=str.lower)
        htmlDir = os.path.join(self.htmlpath, parent)
        if len(noduplicate) > 0 and not QDir(htmlDir).exists():
            QDir().mkdir(htmlDir)

        for name in noduplicate:
            path = notepath + '/' + name
            filename = os.path.join(parent, name)
            for ext in self.extName:
                notefile = os.path.join(self.notepath, filename + ext)
                if QFile.exists(notefile):
                    break
            htmlfile = os.path.join(self.htmlpath, filename + ".html")
            #print(notefile, htmlfile)
            self.convert(notefile, htmlfile, os.path.join(parent, name))
            self.initTree(path, os.path.join(parent, name))

            # append subpages to page
            savestream << '<li><a href="/notes/' + filename + '.html">' + name + '</a></li>'
        html.close()
示例#52
0
    def method_0(self, iwin32Window_0):
        if QFile.exists(FatoList.fileName):
            fl = QFile.remove(FatoList.fileName)
            f = open(FatoList.fileName, 'w')
            f.flush()
            f.close()

        else:
            f = open(FatoList.fileName, 'w')
            # f = open("D:/xml/phxasar.txt")
            f.flush()
            f.close()

        file0 = QFile(FatoList.fileName)
        file0.open(QIODevice.WriteOnly)
        dataStream = QDataStream(file0)
        dataStream.writeQString(QString("PHXHSAF"))
        dataStream.writeInt(1)
        dataStream.writeInt(len(self))

        for fato in self:
            fato.method_6(dataStream)
        file0.flush()
        file0.close()
示例#53
0
 def importPageCore(self, filename):
     fh = QFile(filename)
     fh.open(QIODevice.ReadOnly)
     fileBody = QTextStream(fh).readAll()
     fh.close()
     page = QFileInfo(filename).completeBaseName()
     fh = QFile(self.notesTree.pageToFile(page))
     if fh.exists():
         QMessageBox.warning(self, self.tr("Import Error"),
                             self.tr("Page already exists: %s") % page)
         dialog = LineEditDialog(self.notePath, self)
         if dialog.exec_():
             page = dialog.editor.text()
             fh.close()
             fh = QFile(self.notesTree.pageToFile(page))
         else:
             return
     fh.open(QIODevice.WriteOnly)
     savestream = QTextStream(fh)
     savestream << fileBody
     fh.close()
     item = QTreeWidgetItem(self.notesTree, [page])
     self.notesTree.sortItems(0, Qt.AscendingOrder)
     self.notesTree.setCurrentItem(item)
示例#54
0
 def loadInitialFile(self):
     settings = QSettings()
     fname = unicode(settings.value("LastFile").toString())
     if fname and QFile.exists(fname):
         self.loadFile(fname)
示例#55
0
    def _extract_photo_info(self, composition, config_collection, record):
        """
        Extracts the photo information from the config using the record value
        and builds an absolute path for use by the picture composer item.
        :param composition: Map composition.
        :type composition: QgsComposition
        :param config_collection: Photo configuration collection specified in
        template file.
        :type config_collection: PhotoConfigurationCollection
        :param record: Matching record from the result set.
        :type record: object
        """
        ph_configs = config_collection.items().values()

        for conf in ph_configs:
            photo_tb = conf.linked_table()
            referenced_column = conf.source_field()
            referencing_column = conf.linked_field()
            document_type = conf.document_type.replace(' ', '_').lower()
            document_type_id = int(conf.document_type_id)

            #Get name of base supporting documents table
            supporting_doc_base = self._current_profile.supporting_document.name

            #Get parent table of supporting document table
            s_doc_entities = self._current_profile.supporting_document_entities(
            )
            photo_doc_entities = [
                de for de in s_doc_entities if de.name == photo_tb
            ]

            if len(photo_doc_entities) == 0:
                continue

            photo_doc_entity = photo_doc_entities[0]
            document_parent_table = photo_doc_entity.parent_entity.name

            #Get id of base photo
            alchemy_table, results = self._exec_query(
                photo_tb, referencing_column,
                getattr(record, referenced_column, ''))

            #Filter results further based on document type
            results = [
                r for r in results if r.document_type == document_type_id
            ]
            '''
            There are no photos in the referenced table column hence insert no
            photo image
            '''
            if len(results) == 0:
                pic_item = composition.getComposerItemById(conf.item_id())

                if not pic_item is None:
                    no_photo_path = PLUGIN_DIR + "/images/icons/no_photo.png"

                    if QFile.exists(no_photo_path):
                        self._composeritem_value_handler(
                            pic_item, no_photo_path)

                    continue

            for r in results:
                base_ph_table, doc_results = self._exec_query(
                    supporting_doc_base, 'id', r.supporting_doc_id)

                for dr in doc_results:
                    self._build_photo_path(composition, conf.item_id(),
                                           document_parent_table,
                                           document_type,
                                           dr.document_identifier, dr.filename)

                #TODO: Only interested in one photograph, should support more?
                break
示例#56
0
    def insertDocumentFromFile(self, path, doc_type_id, entity, record_count=1):
        """
        Insert a new document into one of the registered containers with the
        document type id. This document is registered
        :param path: The local user path of the document
        :type path: String
        :param doc_type_id: The entity document type id
        :type doc_type_id: Integer
        :param entity: The entity in which the document is inserted into.
        :type entity: Entity class
        :param record_count: The number of records for which a
        document is uploaded. Default is 1. For instance, more
        records could be used in STR wizard in multi-party.
        :type record_count: Integer
        :return: None
        :rtype: NoneType
        """
        if len(self.containers) > 0:
            if doc_type_id in self.containers:
                container = self.containers[doc_type_id]

                #Check if the file exists
                if QFile.exists(path):

                    network_location = network_document_path()

                    if not network_location:
                        self._doc_repository_error()

                        return

                    #Check if the directory exists
                    doc_dir = QDir(network_location)

                    if not doc_dir.exists():
                        msg = QApplication.translate(
                            "sourceDocumentManager",
                            u"The root document "
                            u"repository '{0}' does "
                            u"not exist.\nPlease "
                            u"check the path settings."
                        )
                        parent = self.parent()
                        if not isinstance(parent, QWidget):
                            parent = None

                        QMessageBox.critical(
                            parent,
                            QApplication.translate(
                                "sourceDocumentManager",
                                "Document Manager"
                            ),
                            msg.format(network_location)
                        )
                        return

                    for i in range(record_count):
                        # Use the default network file manager
                        networkManager = NetworkFileManager(
                            network_location, self.parent()
                        )
                        # Add document widget
                        docWidg = DocumentWidget(
                            self.document_model,
                            networkManager,
                            parent=self.parent(),
                            view_manager=self._doc_view_manager
                        )
                        # Connect slot once the document
                        # has been successfully uploaded.
                        docWidg.fileUploadComplete.connect(
                            lambda: self.onFileUploadComplete(doc_type_id)
                        )
                        self._linkWidgetRemovedSignal(docWidg)

                        doc_type_entity = entity.supporting_doc.document_type_entity
                        doc_type_value = entity_id_to_attr(
                            doc_type_entity, 'value', doc_type_id
                        )

                        docWidg.setFile(
                            path, entity.name, doc_type_value, doc_type_id
                        )
                        container.addWidget(docWidg)
示例#57
0
def foreign_key_parent_tables(table_name, search_parent=True, filter_exp=None):
    """
    Functions that searches for foreign key references in the specified table.
    :param table_name: Name of the database table.
    :type table_name: str
    :param search_parent: Select True if table_name is the child and
    parent tables are to be retrieved, else child tables will be
    returned.
    :type search_parent: bool
    :param filter_exp: A regex expression to filter related table names.
    :type filter_exp: QRegExp
    :return: A list of tuples containing the local column name, foreign table
    name and corresponding foreign column name.
    :rtype: list
    """
    #Check if the view for listing foreign key references exists
    fk_ref_view = pg_table_exists("foreign_key_references")

    #Create if it does not exist
    if not fk_ref_view:
        script_path = PLUGIN_DIR + "/scripts/foreign_key_references.sql"

        script_file = QFile(script_path)
        if script_file.exists():
            if not script_file.open(QIODevice.ReadOnly):
                return None

            reader = QTextStream(script_file)
            sql = reader.readAll()
            if sql:
                t = text(sql)
                _execute(t)

        else:
            return None

    if search_parent:
        ref_table = "foreign_table_name"
        search_table = "table_name"
    else:
        ref_table = "table_name"
        search_table = "foreign_table_name"

    #Fetch foreign key references
    sql = u"SELECT column_name,{0},foreign_column_name FROM " \
          u"foreign_key_references where {1} =:tb_name".format(ref_table,
                                                               search_table)
    t = text(sql)
    result = _execute(t, tb_name=table_name)

    fk_refs = []

    for r in result:
        rel_table = r[ref_table]

        fk_ref = r["column_name"], rel_table,\
                 r["foreign_column_name"]

        if not filter_exp is None:
            if filter_exp.indexIn(rel_table) >= 0:
                fk_refs.append(fk_ref)

                continue

        fk_refs.append(fk_ref)

    return fk_refs
示例#58
0
 def test_default_north_arrow_path(self):
     """Verify the call to default north arrow path works.
     """
     # Check if it exists
     path = QFile(default_north_arrow_path())
     self.assertTrue(QFile.exists(path))
示例#59
0
 def test_supporters_logo_path(self):
     """Verify the call to default supporters logo path works.
     """
     # Check if it exists
     logo_path = QFile(supporters_logo_path())
     self.assertTrue(QFile.exists(logo_path))
示例#60
0
 def test_black_inasafe_logo_path(self):
     """Verify the call to default InaSAFE logo path works.
     """
     # Check if it exists
     logo_path = QFile(black_inasafe_logo_path())
     self.assertTrue(QFile.exists(logo_path))