def _prepare_code(self, specification): """Prepare the code turning templates into python. :param specification: Specification instance containing template replacement keys/values. :type specification: PluginSpecification """ # process the user entries if specification.gen_makefile: self.populate_template( specification, self.shared_dir, 'Makefile.tmpl', 'Makefile') if specification.gen_pb_tool: self.populate_template( specification, self.shared_dir, 'pb_tool.tmpl', 'pb_tool.cfg') self.populate_template( specification, self.template_dir, '__init__.tmpl', '__init__.py') self.populate_template( specification, self.template_dir, 'module_name.tmpl', '%s.py' % specification.module_name) if specification.gen_scripts: release_script = QFile(os.path.join(self.shared_dir, 'release.sh')) release_script.copy(os.path.join(self.plugin_path, 'release.sh')) plugin_upload = QFile( os.path.join(self.shared_dir, 'plugin_upload.py')) plugin_upload.copy( os.path.join(self.plugin_path, 'plugin_upload.py')) # noinspection PyCallByClass,PyTypeChecker QFile.setPermissions( os.path.join(self.plugin_path, 'plugin_upload.py'), QFile.ReadOwner | QFile.WriteOwner | QFile.ExeOwner | QFile.ReadUser | QFile.WriteUser | QFile.ExeUser | QFile.ReadGroup | QFile.ExeGroup | QFile.ReadOther | QFile.ExeOther)
def _prepare_code(self, specification): """Prepare the code turning templates into python. :param specification: Specification instance containing template replacement keys/values. :type specification: PluginSpecification """ # process the user entries if specification.gen_makefile: self.populate_template(specification, self.shared_dir, 'Makefile.tmpl', 'Makefile') if specification.gen_pb_tool: self.populate_template(specification, self.shared_dir, 'pb_tool.tmpl', 'pb_tool.cfg') self.populate_template(specification, self.template_dir, '__init__.tmpl', '__init__.py') self.populate_template(specification, self.template_dir, 'module_name.tmpl', '%s.py' % specification.module_name) if specification.gen_scripts: release_script = QFile(os.path.join(self.shared_dir, 'release.sh')) release_script.copy(os.path.join(self.plugin_path, 'release.sh')) plugin_upload = QFile( os.path.join(self.shared_dir, 'plugin_upload.py')) plugin_upload.copy( os.path.join(self.plugin_path, 'plugin_upload.py')) # noinspection PyCallByClass,PyTypeChecker QFile.setPermissions( os.path.join(self.plugin_path, 'plugin_upload.py'), QFile.ReadOwner | QFile.WriteOwner | QFile.ExeOwner | QFile.ReadUser | QFile.WriteUser | QFile.ExeUser | QFile.ReadGroup | QFile.ExeGroup | QFile.ReadOther | QFile.ExeOther)
def initialise(notebookName, notebookPath): """ Called by create() A notebook directory will be initialised to: css/ notebook.conf notes/ """ # QDir().mkpath will create all necessary parent directories QDir().mkpath(os.path.join(notebookPath, "notes").replace(os.sep, '/')) QDir().mkpath(os.path.join(notebookPath, "css").replace(os.sep, '/')) cssFile = os.path.join(notebookPath, "css", "notebook.css").replace(os.sep, '/') searchCssFile = os.path.join(notebookPath, "css", "search-window.css").replace(os.sep, '/') cssTemplate = "/usr/share/mikidown/notebook.css" searchCssTemplate = "/usr/share/mikidown/search-window.css" if not os.path.exists(cssTemplate): cssTemplate = os.path.join(os.path.dirname(__file__), "css", "sphinx.css").replace(os.sep, '/') if not os.path.exists(searchCssTemplate): searchCssTemplate = os.path.join(os.path.dirname(__file__), "css", "search-window.css").replace( os.sep, '/') # If //cssFile// already exists, copy() returns false! print(cssTemplate) print(searchCssTemplate) QFile.copy(cssTemplate, cssFile) QFile.copy(searchCssTemplate, searchCssFile)
def convert_metadata(self): """Method invoked when OK button is clicked.""" # Converter parameter converter_parameter = {} # Target exposure if self.target_exposure_combo_box.isEnabled(): exposure_index = self.target_exposure_combo_box.currentIndex() exposure_key = self.target_exposure_combo_box.itemData( exposure_index, Qt.UserRole) converter_parameter['exposure'] = exposure_key # Metadata current_metadata = self.keyword_io.read_keywords(self.layer) old_metadata = convert_metadata(current_metadata, **converter_parameter) # Input input_layer_path = self.layer.source() input_directory_path = os.path.dirname(input_layer_path) input_file_name = os.path.basename(input_layer_path) input_base_name = os.path.splitext(input_file_name)[0] input_extension = os.path.splitext(input_file_name)[1] # Output output_path = self.output_path_line_edit.text() output_directory_path = os.path.dirname(output_path) output_file_name = os.path.basename(output_path) output_base_name = os.path.splitext(output_file_name)[0] # Copy all related files, if exists extensions = [ # Vector layer '.shp', '.geojson', '.qml', '.shx', '.dbf', '.prj', 'qpj', # Raster layer '.tif', '.tiff', '.asc', ] for extension in extensions: source_path = os.path.join(input_directory_path, input_base_name + extension) if not os.path.exists(source_path): continue target_path = os.path.join(output_directory_path, output_base_name + extension) QFile.copy(source_path, target_path) # Replace the metadata with the old one output_file_path = os.path.join(output_directory_path, output_base_name + input_extension) write_iso19115_metadata(output_file_path, old_metadata, version_35=True)
def openExampleDocument(self): if not self.confirmDestructiveAction(): return self.close() dirpath = tempfile.mkdtemp() destpath = op.join(dirpath, 'example.moneyguru') QFile.copy(':/example.moneyguru', destpath) self.model.load_from_xml(destpath) self.model.adjust_example_file() self.documentPath = None # As if it was a new doc. Save As is required. self.documentPathChanged.emit()
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()
def insertAttachment(self, filePath, fileType): item = self.parent.notesTree.currentItem() attDir = self.parent.notesTree.itemToAttachmentDir(item) filename, extension = os.path.splitext(filePath) filename = os.path.basename(filename) newFilePath = os.path.join(attDir, filename + extension) relativeFilePath = newFilePath.replace(self.settings.notebookPath, "..") QFile.copy(filePath, newFilePath) self.parent.updateAttachmentView() if fileType == self.imageFilter: text = "![%s](%s)" % (filename, relativeFilePath) else: text = "[%s%s](%s)\n" % (filename, extension, relativeFilePath) self.insertPlainText(text)
def method_4(self, iwin32Window_0, string_0, qafileVersion_0): try: count = len(self.Sessions) if (count <= 0 or not self.sessions[count - 1].Corrupted or len(self.sessions[count - 1].Children) != 0): tempFileName = define.appPath + "/tempFile.txt" fileT = QFile(string_0) binaryWriter = file(tempFileName, "w") # using (FileStream fileStream = File.Open(tempFileName, FileMode.Create, FileAccess.write, FileShare.Read)) # { # using (BinaryWriter binaryWriter = new BinaryWriter(fileStream)) # { binaryWriter.write("PHXQAA") for case in switch(qafileVersion_0): if case(QAFileVersion.V4) or case(QAFileVersion.V4_1): if (qafileVersion_0 != QAFileVersion.V4): binaryWriter.write(str(4.1)) else: binaryWriter.write(str(4)) self.method_14(binaryWriter, qafileVersion_0) break elif case(QAFileVersion.V8) or case(QAFileVersion.V8_1): if (qafileVersion_0 != QAFileVersion.V8): binaryWriter.write(str(8.1)) else: binaryWriter.write(str(8)) self.method_16(binaryWriter, qafileVersion_0) break elif case(QAFileVersion.V10): binaryWriter.write(10) self.method_16(binaryWriter, qafileVersion_0) break else: QMessageBox.warning( iwin32Window_0, "Error", Messages.ERR_UNSUPPORTED_QA_FILE_VERSION) raise SystemError if (fileT.exists()): string_0 = String.Str2QString(string_0) str0 = string_0.left(string_0.length() - 3) + "qab" if (QFile.exists(str0)): QFile.remove(str0) QFile.copy(string_0, str0) QFile.copy(tempFileName, string_0) except: QMessageBox.warning( iwin32Window_0, "Error", Messages.ERR_FAILED_TO_SAVE_ACTIVE_QA_FILE.format( sys.exc_info()[0]))
def initialise(notebookName, notebookPath): """ Called by create() A notebook directory will be initialised to: css/ notebook.conf notes/ """ # QDir().mkpath will create all necessary parent directories QDir().mkpath(os.path.join(notebookPath, "notes")) QDir().mkpath(os.path.join(notebookPath, "css")) cssFile = os.path.join(notebookPath, "css", "notebook.css") cssTemplate = "/usr/share/mikidown/notebook.css" if not os.path.exists(cssTemplate): cssTemplate = os.path.join( os.path.dirname(__file__), "notebook.css") # If //cssFile// already exists, copy() returns false! QFile.copy(cssTemplate, cssFile)
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)
def copy_core_configuration(): """ Copies the basic STDM configuration to the user directory if there is none. """ #check network config exist core_config_path = read_network_path() if not QFile.exists(core_config_path): return else: # if not core_config_path: # 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)
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))
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))
def insertAttachment(self, filePath, fileType): item = self.parent.notesTree.currentItem() attDir = self.parent.notesTree.itemToAttachmentDir(item) filename, extension = os.path.splitext(filePath) filename = os.path.basename(filename) newFilePath = os.path.join(attDir, filename + extension).replace(os.sep, '/') relativeFilePath = newFilePath.replace(self.settings.notebookPath, "..") if not os.path.exists(attDir): os.makedirs(attDir) QFile.copy(filePath, newFilePath) self.parent.updateAttachmentView() if fileType == self.imageFilter: text = "![%s](%s)" % (filename, relativeFilePath) else: text = "[%s%s](%s)\n" % (filename, extension, relativeFilePath) self.insertPlainText(text)
def testStatistics(self): """Test zonal stats""" sep = os.sep TEST_DATA_DIR = unitTestDataPath() + sep + "zonalstatistics" + sep myTempPath = QDir.tempPath() + sep testDir = QDir(TEST_DATA_DIR) for f in testDir.entryList(QDir.Files): QFile.remove(myTempPath + f) QFile.copy(TEST_DATA_DIR + f, myTempPath + f) myVector = QgsVectorLayer(myTempPath + "polys.shp", "poly", "ogr") myRasterPath = myTempPath + "edge_problem.asc" zs = QgsZonalStatistics(myVector, myRasterPath, "", 1) zs.calculateStatistics(None) feat = QgsFeature() # validate statistics for each feature request = QgsFeatureRequest().setFilterFid(0) feat = myVector.getFeatures(request).next() myMessage = ('Expected: %f\nGot: %f\n' % (12.0, feat[1])) assert feat[1] == 12.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (8.0, feat[2])) assert feat[2] == 8.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.666666666666667, feat[3])) assert abs(feat[3] - 0.666666666666667) < 0.00001, myMessage request.setFilterFid(1) feat = myVector.getFeatures(request).next() myMessage = ('Expected: %f\nGot: %f\n' % (9.0, feat[1])) assert feat[1] == 9.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2])) assert feat[2] == 5.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.555555555555556, feat[3])) assert abs(feat[3] - 0.555555555555556) < 0.00001, myMessage request.setFilterFid(2) feat = myVector.getFeatures(request).next() myMessage = ('Expected: %f\nGot: %f\n' % (6.0, feat[1])) assert feat[1] == 6.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2])) assert feat[2] == 5.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.833333333333333, feat[3])) assert abs(feat[3] - 0.833333333333333) < 0.00001, myMessage
def _prepare_code(self, specification, template_dir): """Prepare the code turning templates into python. :param specification: Specification instance containing template replacement keys/values. :type specification: PluginSpecification :param template_dir: Directory where template is. :type template_dir: str """ # process the user entries self.populate_template(specification, 'Makefile.tmpl', 'Makefile') self.populate_template(specification, '__init__.tmpl', '__init__.py') self.populate_template(specification, 'module_name.tmpl', '%s.py' % specification.module_name) self.populate_template(specification, 'module_name_dialog.tmpl', '%s_dialog.py' % specification.module_name) self.populate_template(specification, 'module_name_dialog_base.ui.tmpl', '%s_dialog_base.ui' % specification.module_name) self.populate_template(specification, 'resources.tmpl', 'resources.qrc') # copy the non-generated files to the new plugin dir icon = QFile(os.path.join(template_dir, 'icon.png')) icon.copy(os.path.join(self.plugin_path, 'icon.png')) release_script = QFile(os.path.join(template_dir, 'release.sh')) release_script.copy(os.path.join(self.plugin_path, 'release.sh')) plugin_upload = QFile(os.path.join(template_dir, 'plugin_upload.py')) plugin_upload.copy(os.path.join(self.plugin_path, 'plugin_upload.py')) # noinspection PyCallByClass,PyTypeChecker QFile.setPermissions( os.path.join(self.plugin_path, 'plugin_upload.py'), QFile.ReadOwner | QFile.WriteOwner | QFile.ExeOwner | QFile.ReadUser | QFile.WriteUser | QFile.ExeUser | QFile.ReadGroup | QFile.ExeGroup | QFile.ReadOther | QFile.ExeOther)
def _prepare_help(self, template_dir): """Prepare the help directory. :param template_dir: Directory where template is. :type template_dir: str """ # Copy over pylintrc # noinspection PyCallByClass,PyTypeChecker QFile.copy( os.path.join(template_dir, 'pylintrc'), os.path.join(self.plugin_path, 'pylintrc')) # Create sphinx default project for help QDir().mkdir(self.plugin_path + '/help') QDir().mkdir(self.plugin_path + '/help/build') QDir().mkdir(self.plugin_path + '/help/source') QDir().mkdir(self.plugin_path + '/help/source/_static') QDir().mkdir(self.plugin_path + '/help/source/_templates') # copy doc makefiles # noinspection PyCallByClass,PyTypeChecker QFile.copy( os.path.join(template_dir, 'help/make.bat'), os.path.join(self.plugin_path, 'help/make.bat')) # noinspection PyCallByClass,PyTypeChecker QFile.copy( os.path.join(template_dir, 'help/Makefile'), os.path.join(self.plugin_path, 'help/Makefile'))
def copyFile(source, dest, overwrite=False): if os.path.exists(dest): if overwrite or abs(QFileInfo(source).lastModified().secsTo(QFileInfo(dest).lastModified())) > 5: # use secsTo for different file systems if debug_mode: qDebug("Existing file removed: %s (%s, %s)" % (dest, str(QFileInfo(source).lastModified()), str(QFileInfo(dest).lastModified()))) QFile.remove(dest) else: if debug_mode: qDebug("File already exists: %s" % dest) return False if debug_mode: qDebug("File copied: %s to %s" % (source, dest)) return QFile.copy(source, dest)
def initialise(notebookName, notebookPath): """ Called by create() A notebook directory will be initialised to: css/ notebook.conf notes/ """ # QDir().mkpath will create all necessary parent directories QDir().mkpath(os.path.join(notebookPath, "notes").replace(os.sep,'/')) QDir().mkpath(os.path.join(notebookPath, "css").replace(os.sep,'/')) cssFile = os.path.join(notebookPath, "css", "notebook.css").replace(os.sep,'/') searchCssFile = os.path.join(notebookPath, "css", "search-window.css").replace(os.sep,'/') cssTemplate = "/usr/share/mikidown/notebook.css" searchCssTemplate = "/usr/share/mikidown/search-window.css" if not os.path.exists(cssTemplate): cssTemplate = os.path.join( os.path.dirname(__file__), "css", "sphinx.css").replace(os.sep,'/') if not os.path.exists(searchCssTemplate): searchCssTemplate = os.path.join( os.path.dirname(__file__), "css" , "search-window.css").replace(os.sep,'/') # If //cssFile// already exists, copy() returns false! print(cssTemplate) print(searchCssTemplate) QFile.copy(cssTemplate, cssFile) QFile.copy(searchCssTemplate, searchCssFile)
def map_qrc_to_file(match, destination_directory): """Map a qrc:/ path to its correspondent file:/// and create it. For example qrc:/plugins/inasafe/ajax-loader.gif is converted to file:////home/marco/.qgis2/python/plugins/ inasafe-master/safe_qgis/resources/img/ajax-loader.gif If the qrc asset is non file based (i.e. is compiled in resources_rc .pc) then a copy of is extracted to destination_directory. :param match: The qrc path to be mapped matched from a regular expression such as re.compile('qrc:/plugins/inasafe/([-./ \\w]*)'). :type match: re.match object :param destination_directory: The destination path to copy non file based qrc assets. :type destination_directory: str :returns: File path to the resource or None if the resource could not be created. :rtype: None, str """ # Resource alias on resources.qrc resource_alias = match.group(1) # The resource path (will be placed inside destination_directory) resource_path = os.path.join(destination_directory, resource_alias) # The file (resource) might be here due to a previous copy if not os.path.isfile(resource_path): # Get resource directory tree resource_path_directory = os.path.dirname(resource_path) # Create dirs recursively if resource_path_directory does not exist if not os.path.exists(resource_path_directory): os.makedirs(resource_path_directory) # Now, copy from qrc to file system source_file = ':/plugins/inasafe/%s' % resource_alias # noinspection PyTypeChecker copy_successful = QFile.copy(source_file, resource_path) if not copy_successful: #copy somehow failed resource_path = None #noinspection PyArgumentList return QUrl.fromLocalFile(resource_path).toString()
def map_qrc_to_file(match, destination_directory): """Map a qrc:/ path to its correspondent file:/// and create it. For example qrc:/plugins/inasafe/ajax-loader.gif is converted to file:////home/marco/.qgis2/python/plugins/ inasafe-master/safe_qgis/resources/img/ajax-loader.gif If the qrc asset is non file based (i.e. is compiled in resources_rc .pc) then a copy of is extracted to destination_directory. :param match: The qrc path to be mapped matched from a regular expression such as re.compile('qrc:/plugins/inasafe/([-./ \\w]*)'). :type match: re.match object :param destination_directory: The destination path to copy non file based qrc assets. :type destination_directory: str :returns: File path to the resource or None if the resource could not be created. :rtype: None, str """ # Resource alias on resources.qrc resource_alias = match.group(1) # The resource path (will be placed inside destination_directory) resource_path = os.path.join(destination_directory, resource_alias) # The file (resource) might be here due to a previous copy if not os.path.isfile(resource_path): # Get resource directory tree resource_path_directory = os.path.dirname(resource_path) # Create dirs recursively if resource_path_directory does not exist if not os.path.exists(resource_path_directory): os.makedirs(resource_path_directory) # Now, copy from qrc to file system source_file = ':/plugins/inasafe/%s' % resource_alias # noinspection PyTypeChecker copy_successful = QFile.copy(source_file, resource_path) if not copy_successful: # copy somehow failed resource_path = None # noinspection PyArgumentList return QUrl.fromLocalFile(resource_path).toString()
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 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)
def copyFile(source, dest, overwrite=False): if os.path.exists(dest): if overwrite or abs(QFileInfo(source).lastModified().secsTo(QFileInfo(dest).lastModified())) > 5: # use secsTo for different file systems if debug_mode: qDebug("Existing file removed: %s (%s, %s)" % (dest, str(QFileInfo(source).lastModified()), str(QFileInfo(dest).lastModified()))) QFile.remove(dest) else: if debug_mode: qDebug("File already exists: %s" % dest) return False ret = QFile.copy(source, dest) if debug_mode: if ret: qDebug("File copied: %s to %s" % (source, dest)) else: qDebug("Failed to copy file: %s to %s" % (source, dest)) return ret
def map_qrc_to_file(match, res_copy_dir): """Map a qrc:/ path to its correspondent file:/// and create it. For example qrc:/plugins/inasafe/ajax-loader.gif is converted to file:////home/marco/.qgis2/python/plugins/ inasafe-master/safe_qgis/resources/img/ajax-loader.gif If the qrc asset is non file based (i.e. is compiled in resources_rc .pc) then a copy of is extracted to res_copy_dir. :param match: The qrc path to be mapped matched from a regular expression such as re.compile('qrc:/plugins/inasafe/([-./ \\w]*)'). :type match: re.match object :param res_copy_dir: The path to copy non file based qrc assets. :type res_copy_dir: str :returns: File path to the resource or None if the resource could not be created. :rtype: None, str """ resources_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', 'resources')) res_alias = match.group(1) res_path = '%s/%s' % (resources_path, res_alias) if not os.path.isfile(res_path): res_path = os.path.join(res_copy_dir, res_alias) # file might be here due to a previous copy if not os.path.isfile(res_path): if not os.path.exists(res_copy_dir): os.makedirs(res_copy_dir) # copy from qrc to filesystem #noinspection PyTypeChecker copy_successful = QFile.copy( ':/plugins/inasafe/%s' % res_alias, res_path) if not copy_successful: #copy somehow failed res_path = None #noinspection PyArgumentList return QUrl.fromLocalFile(res_path).toString()
def map_qrc_to_file(match, res_copy_dir): """Map a qrc:/ path to its correspondent file:/// and create it. For example qrc:/plugins/inasafe/ajax-loader.gif is converted to file:////home/marco/.qgis2/python/plugins/ inasafe-master/safe_qgis/resources/img/ajax-loader.gif If the qrc asset is non file based (i.e. is compiled in resources_rc .pc) then a copy of is extracted to res_copy_dir. :param match: The qrc path to be mapped matched from a regular expression such as re.compile('qrc:/plugins/inasafe/([-./ \\w]*)'). :type match: re.match object :param res_copy_dir: The path to copy non file based qrc assets. :type res_copy_dir: str :returns: File path to the resource or None if the resource could not be created. :rtype: None, str """ resources_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'resources')) res_alias = match.group(1) res_path = '%s/%s' % (resources_path, res_alias) if not os.path.isfile(res_path): res_path = os.path.join(res_copy_dir, res_alias) # file might be here due to a previous copy if not os.path.isfile(res_path): if not os.path.exists(res_copy_dir): os.makedirs(res_copy_dir) # copy from qrc to filesystem #noinspection PyTypeChecker copy_successful = QFile.copy(':/plugins/inasafe/%s' % res_alias, res_path) if not copy_successful: #copy somehow failed res_path = None #noinspection PyArgumentList return QUrl.fromLocalFile(res_path).toString()
def _prepare_code(self, specification, template_dir): """Prepare the code turning templates into python. :param specification: Specification instance containing template replacement keys/values. :type specification: PluginSpecification :param template_dir: Directory where template is. :type template_dir: str """ # process the user entries self.populate_template( specification, 'Makefile.tmpl', 'Makefile') self.populate_template( specification, '__init__.tmpl', '__init__.py') self.populate_template( specification, 'module_name.tmpl', '%s.py' % specification.module_name) self.populate_template( specification, 'module_name_dialog.tmpl', '%s_dialog.py' % specification.module_name) self.populate_template( specification, 'module_name_dialog_base.ui.tmpl', '%s_dialog_base.ui' % specification.module_name) self.populate_template( specification, 'resources.tmpl', 'resources.qrc') # copy the non-generated files to the new plugin dir icon = QFile(os.path.join(template_dir, 'icon.png')) icon.copy(os.path.join(self.plugin_path, 'icon.png')) release_script = QFile(os.path.join(template_dir, 'release.sh')) release_script.copy(os.path.join(self.plugin_path, 'release.sh')) plugin_upload = QFile( os.path.join(template_dir, 'plugin_upload.py')) plugin_upload.copy( os.path.join(self.plugin_path, 'plugin_upload.py')) # noinspection PyCallByClass,PyTypeChecker QFile.setPermissions( os.path.join(self.plugin_path, 'plugin_upload.py'), QFile.ReadOwner | QFile.WriteOwner | QFile.ExeOwner | QFile.ReadUser | QFile.WriteUser | QFile.ExeUser | QFile.ReadGroup | QFile.ExeGroup | QFile.ReadOther | QFile.ExeOther)
def _copyInputFile(self): if self.inputFileName() != self.rawFileName() or self._inputFile.dir( ) != self._type()['raw']: QFile.copy(self._inputFile.absoluteFilePath(), self.rawFileInfo().absoluteFilePath())
def insertFromMimeData(self, source): """ Intended behavior If copy/drag something that hasUrls, then check the extension name: if image then apply image pattern ![Alt text](/path/to/img.jpg) else apply link pattern [text](http://example.net) If copy/drag something that hasImage, then ask for file name If copy/drag something that hasHtml, then html2text Else use the default insertFromMimeData implementation """ item = self.parent.notesTree.currentItem() attDir = self.parent.notesTree.itemToAttachmentDir(item) if not QDir(attDir).exists(): QDir().mkpath(attDir) if source.hasUrls(): for qurl in source.urls(): url = qurl.toString() filename, extension = os.path.splitext(url) filename = os.path.basename(filename) newFilePath = os.path.join(attDir, filename + extension).replace(os.sep, '/') relativeFilePath = newFilePath.replace(self.settings.notebookPath, "..") attachments = self.settings.attachmentImage + self.settings.attachmentDocument if QUrl(qurl).isLocalFile(): if extension.lower() in attachments: nurl = url.replace("file://", "") QFile.copy(nurl, newFilePath) self.parent.updateAttachmentView() if extension.lower() in self.settings.attachmentImage: text = "![%s](%s)" % (filename, relativeFilePath) elif extension.lower() in self.settings.attachmentDocument: text = "[%s%s](%s)\n" % (filename, extension, relativeFilePath) else: text = "[%s%s](%s)\n" % (filename, extension, url) else: if extension.lower() in attachments: self.downloadAs = newFilePath self.networkManager.get(QNetworkRequest(qurl)) if extension.lower() in self.settings.attachmentImage: text = "![%s](%s)" % (filename, relativeFilePath) elif extension.lower() in self.settings.attachmentDocument: text = "[%s%s](%s)\n" % (filename, extension, relativeFilePath) else: text = "[%s%s](%s)\n" % (filename, extension, url) super(MikiEdit, self).insertFromMimeData(self.mimeFromText(text)) elif source.hasImage(): img = source.imageData() attDir = self.parent.notesTree.itemToAttachmentDir(item) dialog = LineEditDialog(attDir, self) if dialog.exec_(): fileName = dialog.editor.text() if not QFileInfo(fileName).suffix(): fileName += '.jpg' filePath = os.path.join(attDir, fileName).replace(os.sep, '/') img.save(filePath) relativeFilePath = filePath.replace(self.settings.notebookPath, "..") text = "![%s](%s)" % (fileName, relativeFilePath) super(MikiEdit, self).insertFromMimeData(self.mimeFromText(text)) elif source.hasHtml(): html = source.html() if HAS_HTML2TEXT: backToMarkdown = html2text.HTML2Text() markdown = backToMarkdown.handle(html) super(MikiEdit, self).insertFromMimeData(self.mimeFromText(markdown)) else: super(MikiEdit, self).insertFromMimeData(self.mimeFromText(html)) else: super(MikiEdit, self).insertFromMimeData(source)
def _copyInputFile(self): if self.inputFileName() != self.rawFileName() or self._inputFile.dir() != self._type()['raw']: QFile.copy(self._inputFile.absoluteFilePath(), self.rawFileInfo().absoluteFilePath())
def insertFromMimeData(self, source): """ Intended behavior If copy/drag something that hasUrls, then check the extension name: if image then apply image pattern ![Alt text](/path/to/img.jpg) else apply link pattern [text](http://example.net) If copy/drag something that hasImage, then ask for file name If copy/drag something that hasHtml, then html2text Else use the default insertFromMimeData implementation """ item = self.parent.notesTree.currentItem() attDir = self.parent.notesTree.itemToAttachmentDir(item) if not QDir(attDir).exists(): QDir().mkpath(attDir) if source.hasUrls(): for qurl in source.urls(): url = qurl.toString() filename, extension = os.path.splitext(url) filename = os.path.basename(filename) newFilePath = os.path.join(attDir, filename + extension).replace( os.sep, '/') relativeFilePath = newFilePath.replace( self.settings.notebookPath, "..") attachments = self.settings.attachmentImage + self.settings.attachmentDocument if QUrl(qurl).isLocalFile(): if extension.lower() in attachments: nurl = url.replace("file://", "") QFile.copy(nurl, newFilePath) self.parent.updateAttachmentView() if extension.lower() in self.settings.attachmentImage: text = "![%s](%s)" % (filename, relativeFilePath) elif extension.lower( ) in self.settings.attachmentDocument: text = "[%s%s](%s)\n" % (filename, extension, relativeFilePath) else: text = "[%s%s](%s)\n" % (filename, extension, url) else: if extension.lower() in attachments: self.downloadAs = newFilePath self.networkManager.get(QNetworkRequest(qurl)) if extension.lower() in self.settings.attachmentImage: text = "![%s](%s)" % (filename, relativeFilePath) elif extension.lower( ) in self.settings.attachmentDocument: text = "[%s%s](%s)\n" % (filename, extension, relativeFilePath) else: text = "[%s%s](%s)\n" % (filename, extension, url) super(MikiEdit, self).insertFromMimeData(self.mimeFromText(text)) elif source.hasImage(): img = source.imageData() attDir = self.parent.notesTree.itemToAttachmentDir(item) dialog = LineEditDialog(attDir, self) if dialog.exec_(): fileName = dialog.editor.text() if not QFileInfo(fileName).suffix(): fileName += '.jpg' filePath = os.path.join(attDir, fileName).replace(os.sep, '/') img.save(filePath) relativeFilePath = filePath.replace(self.settings.notebookPath, "..") text = "![%s](%s)" % (fileName, relativeFilePath) super(MikiEdit, self).insertFromMimeData(self.mimeFromText(text)) elif source.hasHtml(): html = source.html() if HAS_HTML2TEXT: backToMarkdown = html2text.HTML2Text() markdown = backToMarkdown.handle(html) super(MikiEdit, self).insertFromMimeData(self.mimeFromText(markdown)) else: super(MikiEdit, self).insertFromMimeData(self.mimeFromText(html)) else: super(MikiEdit, self).insertFromMimeData(source)
def loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related composer items. """ 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 copy_file = filePath.replace('sdt', 'cpy') # remove existing copy file if QFile.exists(copy_file): copy_template = QFile(copy_file) copy_template.remove() orig_template_file = QFile(filePath) self.setDocumentFile(orig_template_file) # make a copy of the original orig_template_file.copy(copy_file) #templateFile = QFile(filePath) # work with copy templateFile = QFile(copy_file) self.copy_template_file = templateFile 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): table_config_collection = TableConfigurationCollection.create( templateDoc) ''' First load vector layers for the table definitions in the config collection before loading the composition from file. ''' load_table_layers(table_config_collection) self.clearWidgetMappings() #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) #Load data controls composerDS = ComposerDataSource.create(templateDoc) #Set title by appending template name title = QApplication.translate("STDMPlugin", "STDM Document Designer") composer_el = templateDoc.documentElement() if not composer_el is None: template_name = "" if composer_el.hasAttribute("title"): template_name = composer_el.attribute("title", "") elif composer_el.hasAttribute("_title"): template_name = composer_el.attribute("_title", "") if template_name: win_title = u"{0} - {1}".format(title, template_name) self.mainWindow().setWindowTitle(template_name) self._configure_data_controls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig) #Load photo editors photo_config_collection = PhotoConfigurationCollection.create( templateDoc) self._configure_photo_editors(photo_config_collection) # Load table editors self._configure_table_editors(table_config_collection) items = self.composerView().items() items = [] #Load chart property editors chart_config_collection = ChartConfigurationCollection.create( templateDoc) self._configure_chart_editors(chart_config_collection) # Load QR code property editors qrc_config_collection = QRCodeConfigurationCollection.create( templateDoc) self._configure_qr_code_editors(qrc_config_collection) self._sync_ids_with_uuids()
def loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related composer items. """ 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 copy_file = filePath.replace('sdt', 'cpy') # remove existing copy file if QFile.exists(copy_file): copy_template = QFile(copy_file) copy_template.remove() orig_template_file = QFile(filePath) self.setDocumentFile(orig_template_file) # make a copy of the original orig_template_file.copy(copy_file) #templateFile = QFile(filePath) # work with copy templateFile = QFile(copy_file) self.copy_template_file = templateFile 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): table_config_collection = TableConfigurationCollection.create(templateDoc) ''' First load vector layers for the table definitions in the config collection before loading the composition from file. ''' load_table_layers(table_config_collection) self.clearWidgetMappings() #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) #Load data controls composerDS = ComposerDataSource.create(templateDoc) #Set title by appending template name title = QApplication.translate("STDMPlugin", "STDM Document Designer") composer_el = templateDoc.documentElement() if not composer_el is None: template_name = "" if composer_el.hasAttribute("title"): template_name = composer_el.attribute("title", "") elif composer_el.hasAttribute("_title"): template_name = composer_el.attribute("_title", "") if template_name: win_title = u"{0} - {1}".format(title, template_name) self.mainWindow().setWindowTitle(template_name) self._configure_data_controls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create(templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig) #Load photo editors photo_config_collection = PhotoConfigurationCollection.create(templateDoc) self._configure_photo_editors(photo_config_collection) # Load table editors self._configure_table_editors(table_config_collection) items = self.composerView().items() items = [] #Load chart property editors chart_config_collection = ChartConfigurationCollection.create(templateDoc) self._configure_chart_editors(chart_config_collection) # Load QR code property editors qrc_config_collection = QRCodeConfigurationCollection.create(templateDoc) self._configure_qr_code_editors(qrc_config_collection) self._sync_ids_with_uuids()