def installAssets(self, assets_path): assets = QDir(assets_path) assets.mkdir("plugins") assets.cd("plugins") assets.mkdir("animate") QFile.copy(":/animate.css", assets_path + "/plugins/animate/animate.css")
def export_css_style_to_file(self, style_identifier: str, filepath: str) -> None: """Exports a css style to a file""" styles = self.get_setting_value("Render/Css_styles") style_path = styles[style_identifier]["path"] QFile.copy(style_path, filepath)
def import_color_schema_from_file(self, filepath: str) -> None: """Imports color schema from a file""" # Parse schema try: schema = toml.load(filepath) except Exception as e: print( f"Failed to parse color schema at path: {filepath} Error: {str(e)}" ) return # Assume file is not Manuwrite color schema if it doesn't have this key-value pair try: if not schema["Data type"] == "Manuwrite color schema": raise ValueError except ValueError: return schema_name = schema["Schema name"] new_path = self.get_appdata_path( ) + "/color_schemas/" + schema_name + "/schema.toml" try: # Create schema dir directory = QDir(self.get_appdata_path() + "/color_schemas") directory.mkdir(schema_name) # Copy schema to its dir and add to SettingsManager schemas = self.get_setting_value("Colors/Color_schemas") schemas[schema_name] = {"name": schema_name, "path": new_path} self.set_setting_value("Colors/Color_schemas", schemas) QFile.copy(filepath, new_path) except Exception: print(f"Failed to copy color schema files to path: {new_path}")
def update_render_settings(self) -> None: """Update render information settings in Project manager with info from gui""" # Update files to render files_to_render = [] for i in range(self.ui.FilesToRenderListWidget.count()): if not self.ui.FilesToRenderListWidget.item(i).text().endswith( "(File not found!)"): files_to_render.append( self.ui.FilesToRenderListWidget.item(i).text()) self.ProjectManager.set_setting_value("Files to render", files_to_render) # Update css style info if self.ui.CssStyleCombobox.currentIndex() == 0: self.ProjectManager.set_setting_value("Css_style", "") self.pandoc_kwargs["css"] = "" else: style_identifier = self.ui.CssStyleCombobox.currentData() self.ProjectManager.set_setting_value("Css_style", style_identifier) # Copy css style to project folder styles = self.SettingsManager.get_setting_value( "Render/Css_styles") old_path = styles[style_identifier]["path"] new_path = self.ProjectManager.get_setting_value( "Absolute path") + "/style.css" QFile.copy(old_path, new_path) self.pandoc_kwargs["css"] = "style.css" # Update csl style info if self.ui.CslStyleCombobox.currentIndex() == 0: self.ProjectManager.set_setting_value("Csl_style", "") self.pandoc_kwargs["csl"] = "" else: style_identifier = self.ui.CslStyleCombobox.currentData() self.ProjectManager.set_setting_value("Csl_style", style_identifier) # Copy csl style to project folder styles = self.SettingsManager.get_setting_value( "Render/Csl_styles") old_path = styles[style_identifier]["path"] new_path = self.ProjectManager.get_setting_value( "Absolute path") + "/csl_style.csl" QFile.copy(old_path, new_path) self.pandoc_kwargs["csl"] = "csl_style.csl" # Update output format and filename format_identifier = self.ui.OutputFormatCombobox.currentData() self.ProjectManager.set_setting_value("Render to", format_identifier) formats = self.SettingsManager.get_setting_value("Render/Formats") current_format = formats[format_identifier] self.pandoc_kwargs["to"] = current_format["pandoc_option"] self.pandoc_kwargs[ "output"] = f"output.{current_format['file_extension']}" output_path = self.ProjectManager.get_setting_value( "Absolute path") + "/" + self.pandoc_kwargs["output"] self.ProjectManager.set_setting_value("Output_path", output_path)
def browseFile(self): config_file, ok = QFileDialog.getOpenFileName( self, _translate('Dialog', 'Select File to use as CONFIG_FILE')) if not ok: return if not config_file.startswith(os.getcwd() + '/'): qfile = QFile(config_file) if qfile.size() < 20971520: # if file < 20Mb copy_dialog = ProxyCopyDialog() copy_dialog.setFile(config_file) copy_dialog.exec() if copy_dialog.result(): if copy_dialog.rename_file: base, pt, extension = os.path.basename( config_file).rpartition('.') config_file = "%s.%s" % (proxy.session_name, extension) if not base: config_file = proxy.session_name else: config_file = os.path.basename(config_file) qfile.copy(config_file) self.config_file = os.path.relpath(config_file) if (proxy.session_name and (self.config_file == proxy.session_name or self.config_file.startswith("%s." % proxy.session_name))): self.config_file = self.config_file.replace(proxy.session_name, "$RAY_SESSION_NAME") self.ui.lineEditConfigFile.setText(self.config_file)
def saveFile(self): if (self.movie_cutter): result_filename, _ = QFileDialog.getSaveFileName( self, "Экспортировать файл", QDir.homePath(), "Видео-файл (*." + self.movie_cutter.format + ")", "", QFileDialog.DontUseNativeDialog) QFile.copy(self.movie_cutter.output_file, result_filename + "." + self.movie_cutter.format)
def export_color_scheme_to_file(self, scheme_identifier: str, filepath: str) -> None: """Exports a color scheme to file""" # Get filepath of a scheme schemes = self.get_setting_value("Colors/Color_schemas") scheme_path = schemes[scheme_identifier]["path"] # Copy file QFile.copy(scheme_path, filepath)
def copyFile(filePath): file = QFile(filePath) if file.exists() is False: import resource_rc file.open(QIODevice.ReadWrite) fileName = filePath.split("/")[-1] cp_to_path = os.path.join(tmp_folder, fileName) # print(cp_to_path) file.copy(cp_to_path) file.close()
def export_csl_style_to_file(self, style_identifier: str, export_path: str) -> None: """Exports a csl style to a file""" styles = self.get_setting_value("Render/Csl_styles") style_path = styles[style_identifier]["path"] try: QFile.copy(style_path, export_path) except Exception: print(f"Failed to copy style to path: {export_path}")
def installAssets(self, assets_path): assets = QDir(assets_path) assets.mkdir("plugins") assets.cd("plugins") assets.mkdir("animate") dst = os.path.join(assets_path, "plugins", "animate", "animate.css") QFile.copy(":/animate.css", dst) os.chmod( dst, stat.S_IWRITE | stat.S_IREAD | stat.S_IWGRP | stat.S_IRGRP | stat.S_IROTH)
def transferFile(self, src_path): dest_path = self.model.filePath(self.rootIndex()) src_file = QFile() src_file.setFileName(src_path) src_file_info = QFileInfo(src_path) dst_path = os.path.join(dest_path, src_file_info.fileName()) src_file.copy(dst_path)
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 get_app_settings() -> QSettings: FixedSettings.config_path = QStandardPaths.writableLocation( QStandardPaths.AppConfigLocation) settings_ini = os.path.join( FixedSettings.config_path, '%s.ini' % FixedSettings.applicationName.lower()) if not os.path.exists(settings_ini): os.makedirs(FixedSettings.config_path, exist_ok=True) QFile.copy(':%s.ini' % FixedSettings.applicationName.lower(), settings_ini) QFile.setPermissions(settings_ini, QFile.ReadOwner | QFile.WriteOwner) return QSettings(settings_ini, QSettings.IniFormat)
def create_beep(beep_count, beep_notif): one_beep_tmp = '.\\media\\beep-01.mp3' if pathlib.Path(beep_notif).exists(): pathlib.Path(beep_notif).unlink() if not pathlib.Path(one_beep_tmp).exists(): beep = QFile("://audio/beep-01a.mp3") QFile.copy(beep.fileName(), one_beep_tmp) destination = open(beep_notif, 'wb') for i in range(1, beep_count + 1): beep_tmp = open(one_beep_tmp, 'rb') shutil.copyfileobj(beep_tmp, destination) beep_tmp.close() destination.close() pathlib.Path(one_beep_tmp).chmod(33206) pathlib.Path(one_beep_tmp).unlink()
def copyFiles(self, src, dst, names=None, overwrite=True): """ Copy files from src directory to dst directory. Subfolders are ignored. If names is provided, copies only files matching those names. Symlinks are not copied """ moDebug("Copying files from {} to {}. Names: {}".format( src, dst, names)) srcDir = QDir(src, "", QDir.IgnoreCase, QDir.Files | QDir.NoSymLinks) dstDir = QDir(dst) if not srcDir.exists() or not dstDir.exists(): moWarn("Failed to copy files with non-existant directories") return False success = True if names: srcDir.setNameFilters(names) fileNames = srcDir.entryList() for name in fileNames: if dstDir.exists(name): if not overwrite: continue dstDir.remove(name) success = QFile.copy(srcDir.filePath(name), dstDir.filePath(name)) if not success: moWarn('Failed to copy "{}" from "{}" to "{}"'.format( name, src, dst)) return success
def _copy_lib_file(cls, file_name, dir_name, dst_file_name=None): """ Copy a library file to a directory and return the full pathname of the copy. """ # Note that we use the Qt file operations to support the possibility # that pyqtdeploy itself has been deployed as a single executable. if dst_file_name is None: dst_file_name = file_name s_file_name = cls._get_lib_file_name(file_name) else: s_file_name = file_name d_file_name = dir_name + '/' + dst_file_name # Make sure the destination doesn't exist. QFile.remove(d_file_name) if not QFile.copy(s_file_name, d_file_name): raise UserException("Unable to copy file {0}".format(file_name)) # The file will be read-only if it was embedded. QFile.setPermissions(d_file_name, QFileDevice.ReadOwner | QFileDevice.WriteOwner) return d_file_name
def _copy_lib_file(cls, file_name, dir_name, dst_file_name=None): """ Copy a library file to a directory and return the full pathname of the copy. """ # Note that we use the Qt file operations to support the possibility # that pyqtdeploy itself has been deployed as a single executable. if dst_file_name is None: dst_file_name = file_name s_file_name = cls._get_lib_file_name(file_name) else: s_file_name = file_name d_file_name = dir_name + '/' + dst_file_name # Make sure the destination doesn't exist. QFile.remove(d_file_name) if not QFile.copy(s_file_name, d_file_name): raise UserException("Unable to copy file {0}".format(file_name)) # The file will be read-only if it was embedded. QFile.setPermissions(d_file_name, QFileDevice.ReadOwner|QFileDevice.WriteOwner) return d_file_name
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False): dir = QDir() dir.setPath(from_dir) from_dir += QDir.separator() to_dir += QDir.separator() if not os.path.exists(to_dir): os.makedirs(to_dir) for file_ in dir.entryList(QDir.Files): from_ = from_dir + file_ to_ = to_dir + file_ if os.path.exists(to_): if replace_on_conflict: if not QFile.remove(to): return False else: continue if not QFile.copy(from_, to_): return False for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot): from_ = from_dir + dir_ to_ = to_dir + dir_ if not os.path.exists(to_): os.makedirs(to_) if not copy_dir_recursive(from_, to_, replace_on_conflict): return False return True
def addImages(self): imageFileNames = QFileDialog.getOpenFileNames( caption="Select image files to label") if not imageFileNames[0] or len(imageFileNames[0]) == 0: return imageFileNames = imageFileNames[0] labelsDir = QFileInfo(self.labelsFileName).absoluteDir() originDir = QFileInfo(imageFileNames[0]).absoluteDir() #Copy image files to the labels folder if originDir.absolutePath() != labelsDir.absolutePath(): progDialog = QProgressDialog( "Copying image files to the labels folder", "Cancel", 0, len(imageFileNames), self) i = 0 for imageFileName in imageFileNames: progDialog.setValue(i) oldName = QFileInfo(imageFileName).fileName() newPath = labelsDir.absoluteFilePath(oldName) print("Copying {} to {}".format(imageFileName, newPath)) ok = QFile.copy(imageFileName, newPath) QApplication.processEvents() if not ok: print("Error copying {} to {}".format(imageFileName, newPath)) i += 1 progDialog.setValue(len(imageFileNames)) progDialog.close() currentImageFileNames = [s.fileName for s in self.labeledImages] newImgIdx = len(self.labeledImages) for imageFileName in imageFileNames: normalizedFileName = QFileInfo(imageFileName).fileName() if normalizedFileName in currentImageFileNames: print("File {} already in dataset, skipping".format( normalizedFileName)) continue self.labeledImages.append(LabeledImage(normalizedFileName, [])) self.fileListModel.setStringList( [s.fileName for s in self.labeledImages]) self.loadImageAtIndex(newImgIdx) print("Added {} images to dataset".format(len(imageFileNames))) print("New length of labeledImages array {}".format( len(self.labeledImages)))
def dropEvent(self, e): """Qt event override for drop event""" try: name_image = face_recognition.load_image_file(e.mimeData().urls()[0].toLocalFile()) encoding = face_recognition.face_encodings(name_image)[0] except IndexError: print("The image has no faces in it, or a face can't be found") msgBox = QMessageBox() msgBox.setText("The image has no faces in it, or a face can't be found"); msgBox.exec_(); return # finally: # print("Unknown Error") # return d = {'Name': "", 'Surname': "", 'nikname': "", 'mail': "", 'password': ""} dialog = DataDialog(d) ret = dialog.exec_() for key in d: d[key] = dialog.le_dict[key].text() if ret is 1: # accepted d['encoding'] = json.dumps(encoding.tolist()) qi = QFileInfo(e.mimeData().urls()[0].toLocalFile()) d['id'] = str(uuid.uuid1()) d['im_path'] = d['id'] + qi.fileName() im_path = path_to_faces + d['im_path'] QFile.copy(e.mimeData().urls()[0].toLocalFile(), im_path) query = QSqlQuery() query.prepare("INSERT into faces values(:id, :Name, :Surname, :nikname, :mail, :password, :im_path, :encoding)") query.bindValue(":id", d['id']) query.bindValue(":Name", d['Name']) query.bindValue(":Surname", d['Surname']) query.bindValue(":nikname", d['nikname']) query.bindValue(":mail", d['mail']) query.bindValue(":password", d['password']) query.bindValue(":im_path", d['im_path']) query.bindValue(":encoding", d['encoding']) query.exec_() self.new_id.emit()
def iconClicked(self, itemselector, button): mi = itemselector.item() action = "" if button == Qt.LeftButton: fileName = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter( QCoreApplication.translate("MenuEditor", "Images") + " (*.png *.gif *.jpg)All (*)") dialog.setWindowTitle( QCoreApplication.translate("MenuEditor", "Load Image")) dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptOpen) if dialog.exec_(): fileName = dialog.selectedFiles().first() del dialog if not fileName: return # copy file to assets dir info = QFileInfo(fileName) name = info.fileName().replace(" ", "_") path = os.path.join(self.site.source_path, "assets", "images", name) QFile.copy(fileName, path) # also copy file to deploy dir for previews dpath = os.path.join(self.site.source_path, self.site.output, "assets", "images", name) QFile.copy(fileName, dpath) mi.setIcon(path.mid(path.indexOf("assets/images/"))) itemselector.setImage(QImage(path)) action = "icon changed" elif button == Qt.RightButton: action = "icon removed" mi.setIcon("") itemselector.setImage(QImage(":/images/image_placeholder.png")) self.menuChanged.emit(self.getUndoRedoText(mi, action))
def import_css_style_from_file(self, filepath: str, style_name: str) -> None: """Imports a css style from a file""" # Generate style identifier used_identifiers = set( self.get_setting_value("Render/Css_styles").keys()) style_identifier = common.generate_identifier( style_name, used_identifiers=used_identifiers, placeholder="Style") try: # Create directory for the style and copy it style_path = self.get_appdata_path( ) + "/css_styles/" + style_identifier directory = QDir(self.get_appdata_path()) directory.mkpath(style_path) new_path = style_path + "/style.css" QFile.copy(filepath, new_path) except Exception: print(f"Failed to copy css style to path: {style_path}") return styles = self.get_setting_value("Render/Css_styles") style_info = { "identifier": style_identifier, "name": style_name, "path": new_path } try: # Generate description.toml file_handle = open(style_path + "/description.toml", "w+") toml.dump(style_info, file_handle) file_handle.close() except Exception as e: print(f"Failed to create style description. Error: {str(e)}") return # Add style to settings manager styles[style_identifier] = style_info self.set_setting_value("Render/Css_styles", styles)
def import_csl_style_from_file(self, filepath: str) -> None: """Imports a csl style from a file choosen by the user""" title = self.extract_csl_style_name(filepath) if title is None: return # Copy csl file to the designated directory try: new_path = self.get_appdata_path( ) + "/csl_styles/" + title + ".csl" QFile.copy(filepath, new_path) except Exception: print( "Failed to copy csl style to designated path while importing") return # Add style to SettingsManager styles = self.get_setting_value("Render/Csl_styles") style_info = {"name": title, "path": new_path} styles[title] = style_info self.set_setting_value("Render/Csl_styles", styles)
def on_showScriptSourceButton_clicked(self): """ Private slot to show an editor window with the source code. """ from Helpviewer import HelpUtilities tmpFileName = HelpUtilities.ensureUniqueFilename( os.path.join(QDir.tempPath(), "tmp-userscript.js")) if QFile.copy(self.__script.fileName(), tmpFileName): from QScintilla.MiniEditor import MiniEditor editor = MiniEditor(tmpFileName, "JavaScript", self) editor.show()
def browseConfigFile(self): work_dir_base = self.getWorkDirBase() work_dir = "%s/%s" % (self._session.path, work_dir_base) config_file, ok = QFileDialog.getOpenFileName( self, _translate('Dialog', 'Select File to use as CONFIG_FILE'), work_dir) if not ok: return if not config_file.startswith(work_dir + '/'): qfile = QFile(config_file) if qfile.size() < 20971520: # if file < 20Mb copy_dialog = RayHackCopyDialog(self) copy_dialog.setFile(config_file) copy_dialog.exec() if copy_dialog.result(): if copy_dialog.rename_file: base, pt, extension = os.path.basename( config_file).rpartition('.') config_file = "%s.%s" % (self._session.name, extension) if not base: config_file = self._session.name else: config_file = os.path.basename(config_file) qfile.copy(config_file) self.config_file = os.path.relpath(config_file, work_dir) if (self._session.name and (self.config_file == self._session.name or self.config_file.startswith("%s." % self._session.name))): self.config_file = self.config_file.replace( self._session.name, "$RAY_SESSION_NAME") self.rhack.lineEditConfigFile.setText(self.config_file)
def installAssets(self, assets_path): assets = QDir(assets_path) assets.mkdir("plugins") assets.cd("plugins") assets.mkdir("revolution-slider") assets.cd("revolution-slider") assets.mkdir("css") assets.mkdir("js") assets.mkdir("assets") QFile.copy(":/css", assets_path + "/plugins/revolution-slider/css") QFile.copy(":/js", assets_path + "/js") QFile.copy(":/js/plugins", assets_path + "/plugins/revolution-slider/js") QFile.copy(":/assets", assets_path + "/plugins/revolution-slider/assets")
def on_btnFile_copy_clicked(self): self.__showBtnInfo(self.sender()) sous=self.ui.editFile.text().strip() #源文件 if sous=="": self.ui.textEdit.appendPlainText("请先选择一个文件") return fileInfo=QFileInfo(sous) newFile=fileInfo.path()+"/"+fileInfo.baseName()+"--副本."+fileInfo.suffix() if QFile.copy(sous,newFile): self.ui.textEdit.appendPlainText("源文件:"+sous) self.ui.textEdit.appendPlainText("复制为文件:"+newFile+"\n") else: self.ui.textEdit.appendPlainText("复制文件失败")
def redo(self): redo = QFile(self.redoFilename) if redo.exists(): dest = QFile(self.filename) if dest.exists(): dest.remove() QFile.copy(self.redoFilename, self.filename) self.editor.load() else: QFile.copy(self.filename, self.undoFilename) self.editor.save() QFile.copy(self.filename, self.redoFilename)
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 on_logo_btn_clicked(self): image_path, ext = QFileDialog.getOpenFileName(self, "p", QDir.homePath(), "Images (*.png)") logo_path = '../static/logo.png' if QFile.exists(logo_path): if not QFile.remove(logo_path): return if QFile.copy(image_path, logo_path): self.bank_logo_btn.setText("") self.bank_logo_btn.setIcon(QIcon(logo_path)) self.bank_logo_btn.setIconSize(QSize(35, 35)) else: QMessageBox.critical(self, "Error", "Image not copy, please try again/after") return
def fileSave(self): infile = QFile(self.outfile) path, _ = QFileDialog.getSaveFileName( self, "Save as...", QDir.homePath() + "/Videos/" + self.recname + ".mp4", "Video (*.mp4)") if os.path.exists(path): os.remove(path) if (path != ""): savefile = path if QFile(savefile).exists: QFile(savefile).remove() print("saving " + savefile) if not infile.copy(savefile): QMessageBox.warning( self, "Error", "cannot write file %s:\n%s." % (path, infile.errorString())) if infile.exists: infile.remove()
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False): dir = QDir() dir.setPath(from_dir) from_dir += QDir.separator() to_dir += QDir.separator() if not os.path.exists(to_dir): os.makedirs(to_dir) for file_ in dir.entryList(QDir.Files): from_ = from_dir + file_ to_ = to_dir + file_ if str(to_).endswith(".src"): to_ = str(to_).replace(".src", "") if os.path.exists(to_): if replace_on_conflict: if not QFile.remove(to_): return False else: continue if not QFile.copy(from_, to_): return False for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot): from_ = from_dir + dir_ to_ = to_dir + dir_ if not os.path.exists(to_): os.makedirs(to_) if not copy_dir_recursive(from_, to_, replace_on_conflict): return False return True