def toggle_organize_btn(): str_dir_src = window.edit_src_dir.text() dir_src = QDir(str_dir_src) str_dir_target = window.edit_target_dir.text() dir_trg = QDir(str_dir_target) # Double check as initializing a QDir with an empty string results in it pointing to the current dir if dir_src.exists() and dir_trg.exists( ) and len(str_dir_src) > 0 and len(str_dir_target) > 0: window.btn_organize_files.setEnabled(True) else: window.btn_organize_files.setEnabled(False)
def exportToPdf(self): data = self.textContent.toPlainText() if not data: return dir = QDir() docsPath = '{}/Documents'.format(dir.homePath()) if not dir.exists(docsPath): docsPath = '{}/Documentos'.format(dir.homePath()) #Regresa una tupla (filename, filter) filename = QFileDialog.getSaveFileName(self, 'Exportar a pdf', docsPath, 'Archivo pdf *.pdf') if not filename: return filename = filename[0] if not '.pdf' in filename: filename += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setPaperSize(QPrinter.Letter) printer.setPageMargins(2, 2, 2, 2, QPrinter.Millimeter) printer.setCreator('Notepad') printer.setPrintProgram('Notepad') printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) self.textContent.print_(printer) self.showMessage('Pdf guardado: {}'.format(filename))
def saveFileAs(self): dir = QDir() docsPath = '{}/Documents'.format(dir.homePath()) if not dir.exists(docsPath): docsPath = '{}/Documentos'.format(dir.homePath()) #Regresa una tupla (filename, filter) filename = QFileDialog.getSaveFileName(self, 'Guardar como', docsPath, self.fileFilter) if not filename: return if self.filename: windowTitle = self.windowTitle().split('-')[0] self.setWindowTitle('{} - {}'.format(windowTitle, filename[0])) else: self.setWindowTitle('{} - {}'.format(self.windowTitle(), filename[0])) self.filename = filename[0] file = QFile(self.filename) if not file.open(QIODevice.WriteOnly): return data = self.textContent.toPlainText() stream = QTextStream(file) stream.setCodec('UTF-8') stream << data file.flush() file.close() self.showMessage('Archivo guardado')
def clearCacheReports(self): dirci = QDir(self.mDir + QDir.separator() + "tempReports") if dirci.exists(): listFiles = [] listFiles = dirci.entryList(QDir.Files) for sdfile in listFiles: QDir().remove(dirci.path() + QDir.separator() + sdfile)
def __get_sqlite_name(self) -> str: """Create the name for the SqliteDB. Therefor combine the Qt Application Defs: QStandardPaths.DataLocation + QtCoreApplication.applicationName + .sqlite3 * *on Mac is this* `~/Library/Application Support/io.jmuelbert.github/jmbde/jmbde.sqlite3` * *on Linux this* `~/.local/share/<APPNAME>/jmbde.sqlite3` * *on Windows is this* `C:/Users/<USER>/AppData/Local/<APPNAME>/jmbde.sqlite3` Returns: The connection string fot the sqlite database. """ db_data_path = QStandardPaths.writableLocation( QStandardPaths.DataLocation) self.log.info("The Database: {}".format(db_data_path)) write_dir = QDir(db_data_path) if not write_dir.mkpath("."): self.log.error("Failed to create writable directory") if not write_dir.exists(): write_dir.mkpath(db_data_path) # Ensure that we have a writable location on all devices. filename = "{}/{}.sqlite3".format(write_dir.absolutePath(), QCoreApplication.applicationName()) return filename
def clearCacheScaleImage(self): dirci = QDir(self.mDir + QDir.separator() + "imagecache") if dirci.exists(): listFiles = [] listFiles = dirci.entryList(QDir.Files) for sdfile in listFiles: QDir().remove(dirci.path() + QDir.separator() + sdfile)
def scaleImage(self, pixels, path): dircache = QDir(self.mDir + QDir.separator() + "imagecache") if dircache.exists() == False: s = QDir(self.mDir) s.mkdir("imagecache") ima = QImage(path) wids = ima.width() heis = ima.height() if (wids > pixels or heis > pixels): imarescale = ima.scaledToWidth( pixels, Qt.SmoothTransformation) if ( wids > heis) else ima.scaledToHeight( pixels, Qt.SmoothTransformation) newImagePath = dircache.path() + QDir.separator( ) + "_temp_scaled_" + QFileInfo(path).fileName() imawriter = QImageWriter() imawriter.setFileName(newImagePath) # imawriter.setFormat("png"); if (imawriter.write(imarescale)): #qDebug()<<"si path"<<newImagePath return newImagePath else: #qDebug()<<"no path"<<newImagePath; return path return path
def getListCoreTranslations(self): dircorelan = QDir(self.mDir + QDir.separator() + "corelocale") if dircorelan.exists(): fileNames = dircorelan.entryList(["*.qm"]) listLocale = QJsonArray() for i in range(len(fileNames)): locale = "" locale = fileNames[i] locale = locale.split('.')[0] listLocale.append(locale) listLocale.append("en") return listLocale return QJsonArray()
def runReport(self, pid, method, par): self.boolDirect = True self.mtypeCall = "report" self.mpid = pid self.mmethod = method self.mparams = par # bparams = self.prepareParams() request = self.prepareRequest() # reply = self.data_request(request, bparams) data = reply.readAll() parseError = QJsonParseError() resultObject = {} resultObject["data"] = "error" document = QJsonDocument.fromJson(data, parseError) if parseError.error == True: resultObject["data"] = "error" else: if document.isObject(): jv = document.object() if jv.__contains__( "result") == True and jv["result"].__class__() == []: #tryton 4.0 #'result': ['pdf', {'base64':wwwwww, '__class__':'bytes'}, False,'Printis'] jre = jv["result"] namesecs = "tryton_" + self.mpid + str( QDateTime.currentMSecsSinceEpoch()) + "." + jre[0] mdir = QDir(self.mDir + QDir.separator() + "tempReports") if mdir.exists() == False: s = QDir(self.mDir) s.mkdir("tempReports") filename = self.mDir + QDir.separator( ) + "tempReports" + QDir.separator() + namesecs file = QFile(filename) if file.open(QIODevice.WriteOnly) == False: #error self.signalResponse.emit(self.mpid, 7, {}) print("error", filename, file.errorString()) else: bafile = QByteArray.fromBase64( jre[1]["base64"].encode()) file.write(bafile) file.close() QDesktopServices.openUrl(QUrl(filename)) else: if document.isArray() == True: self.signalResponse.emit(self.mpid, 7, {}) self.processingData(data, reply)
def generateDirectorys(self, _dir): sourceDir = QFileInfo(_dir).dir() if (sourceDir.exists()): return tempDir = '' directorys = sourceDir.path().split("/") for i in range(0, len(directorys), 1): tempDir += directorys[i] + "/" dir = QDir(tempDir) if (dir.exists() == False): dir.mkdir(tempDir)
def selectSystemTranslation(self, language, typemodule): dirsystem = "systemnet" if typemodule == True else "system" dirsyslan = QDir(self.mDir + QDir.separator() + dirsystem) if dirsyslan.exists(): if QFileInfo(dirsyslan.path() + QDir.separator() + language + ".qm").exists(): translator = QTranslator(self) translator.load(dirsyslan.path() + QDir.separator() + language) self.mApp.installTranslator(translator) else: language = language.split('_')[0] if len(language) == 2: if QFileInfo(dirsyslan.path() + QDir.separator() + language + ".qm").exists(): translator = QTranslator(self) translator.load(dirsyslan.path() + QDir.separator() + language) self.mApp.installTranslator(translator)
def selectCoreTranslation(self, language, settings): settings.setValue("translate", "en") dircorelan = QDir(self.mDir + QDir.separator() + "corelocale") if dircorelan.exists(): if QFileInfo(dircorelan.path() + QDir.separator() + language + ".qm").exists(): settings.setValue("translate", language) translator = QTranslator(self) translator.load(dircorelan.path() + QDir.separator() + language) self.mApp.installTranslator(translator) else: language = language.split('_')[0] if len(language) == 2: if QFileInfo(dircorelan.path() + QDir.separator() + language + ".qm").exists(): settings.setValue("translate", language) translator = QTranslator(self) translator.load(dircorelan.path() + QDir.separator() + language) self.mApp.installTranslator(translator)
def openFile(self): dir = QDir() docsPath = '{}/Documents'.format(dir.homePath()) if not dir.exists(docsPath): docsPath = '{}/Documentos'.format(dir.homePath()) #Regresa una tupla (filename, filter) filename = QFileDialog.getOpenFileName(self, 'Abrir', docsPath, self.fileFilter) if not filename: return self.filename = filename[0] file = QFile(self.filename) if not file.open(QIODevice.ReadOnly): return data = file.readAll() file.close() self.textContent.clear() self.textContent.setText(str(data, encoding='utf-8')) self.setWindowTitle('{} - {}'.format(self.windowTitle(), self.filename))
def rechargeNet(self, preferences, username): #version 1.1 up thesamodule data = self.m_qjsonnetwork.callDirect( "version internal", "model.thesamodule.config.search_read", [[], 0, 1, [], ["internal_version"], preferences]) if not data["data"] == "error": self.internal_version = data["data"]["result"][0][ "internal_version"] if float(self.internal_version) > 1.0: data = self.m_qjsonnetwork.callDirect( "cachedel", "model.thesamodule.config.search_read", [[], 0, 1, [], ["deletecache"], preferences]) if not data["data"] == "error": if data["data"]["result"][0]["deletecache"] == True: self.actionCache_ = "deleteOnCompleted" else: self.actionCache_ = "notDelete" sysdir = QDir(self.mDir + QDir.separator() + _dirSystem) DIR_QML_SYS = sysdir.path() DIR_QML_SYS_LOST = DIR_QML_SYS + QDir.separator() + "lost" sysdirlost = QDir(DIR_QML_SYS_LOST) #revisar folder systemnet if sysdir.exists() == False: s = QDir(self.mDir) s.mkdir(_dirSystem) #revisar folder systemnet lost if sysdirlost.exists() == False: sl = QDir(DIR_QML_SYS) sl.mkdir("lost") #find all files en folder net listSysFiles = os.listdir(DIR_QML_SYS) if "lost" in listSysFiles: listSysFiles.remove("lost") # data = {} data["data"] = "error" if float(self.internal_version) > 1.1: data = self.m_qjsonnetwork.callDirect( "findforuser", "model.thesamodule.usersfolder.search_read", [[ "AND", ["users.user.name", "=", username], ["activefolder", "=", True] ], 0, 1, [], ["qmlfiles"], preferences]) if not data["data"] == "error": result = data["data"]["result"] if len(result) > 0: idfiles = result[0]["qmlfiles"] data = self.m_qjsonnetwork.callDirect( "rechargeNetStep1", "model.thesamodule.thesamodule.read", [idfiles, [ "checksum", "filename", ], preferences]) if len(idfiles) == 0: self.m_qjsonnetwork.signalResponse.emit( "systemnet", 15, {"noqmlfiles": ""}) else: #buscar default data = self.m_qjsonnetwork.callDirect( "findforuser", "model.thesamodule.usersfolder.search_read", [[ "AND", ["type", "=", "default"], ["activefolder", "=", True] ], 0, 1, [], ["qmlfiles"], preferences]) if not data["data"] == "error": result = data["data"]["result"] if len(result) > 0: idfiles = result[0]["qmlfiles"] data = self.m_qjsonnetwork.callDirect( "rechargeNetStep1", "model.thesamodule.thesamodule.read", [ idfiles, [ "checksum", "filename", ], preferences ]) if len(idfiles) == 0: self.m_qjsonnetwork.signalResponse.emit( "systemnet", 15, {"noqmlfiles": ""}) else: self.m_qjsonnetwork.signalResponse.emit( "systemnet", 12, {"noqmlfiles": ""}) else: self.m_qjsonnetwork.signalResponse.emit( "systemnet", 13, {"error": ""}) else: self.m_qjsonnetwork.signalResponse.emit( "systemnet", 13, {"error": ""}) else: data = self.m_qjsonnetwork.callDirect( "rechargeNetStep1", "model.thesamodule.thesamodule.search_read", [[], 0, 1000, [], ["checksum", "filename"], preferences]) if not data["data"] == "error": resultnet = data["data"]["result"] mapnet = {} mapids = {} listNetFiles = [] for file in resultnet: mapnet[file["filename"]] = file["checksum"] mapids[file["filename"]] = file["id"] listNetFiles.append(file["filename"]) #buscar faltantes en system y los updates #buscar los que ya no deben estar mapsysnet = {} listToUpdate = set() #new or update listToErase = [] for file in listSysFiles: try: with open(DIR_QML_SYS + QDir.separator() + file, "rb") as binary_file: data = binary_file.read() chek = hashlib.md5(data).hexdigest() mapsysnet[file] = chek except: listToUpdate.add(file) for file in listNetFiles: if file in listSysFiles: if mapnet[file] != mapsysnet[file]: listToUpdate.add(file) # update else: listToUpdate.add(file) # new for file in listSysFiles: if not file in listNetFiles: listToErase.append(file) # erase listToUpdate = list(listToUpdate) ids = [] for file in listToUpdate: ids.append(mapids[file]) data = self.m_qjsonnetwork.callDirect( "rechargeNetStep2", "model.thesamodule.thesamodule.read", [ids, [ "filebinary", "filename", ], preferences]) errors = [] if not data["data"] == "error": resultnet = data["data"]["result"] for file in resultnet: filename = DIR_QML_SYS + QDir.separator( ) + file["filename"] qfile = QFile(filename) if qfile.open(QIODevice.WriteOnly) == False: errors.append(filename) print("error", filename, qfile.errorString()) else: print("update", file["filename"]) bafile = QByteArray.fromBase64( file["filebinary"]["base64"].encode()) qfile.write(bafile) qfile.close() if len(errors) > 0: self.m_qjsonnetwork.signalResponse.emit( "systemnet", 33, {"error": errors}) return False #erase for file in listToErase: print("moviendo", file) shutil.move(DIR_QML_SYS + QDir.separator() + file, DIR_QML_SYS_LOST + QDir.separator() + file) return True else: #erase all files, no conexion con thesa module for file in listSysFiles: print("moviendo", file) shutil.move(DIR_QML_SYS + QDir.separator() + file, DIR_QML_SYS_LOST + QDir.separator() + file) self.m_qjsonnetwork.signalResponse.emit("systemnet", 34, {"error": ""}) return False
def organize_files(): separator = window.cmb_separator.currentText() target_dir = QDir(window.edit_target_dir.text()) list_target_dirs = target_dir.entryList() progress = progress_window() progress.set_max(window.list_files.count()) for index in range(window.list_files.count()): progress.set_value(index) # # STEP 1: Create target directory if necessary # # Get folder name for file fn_src = window.list_files.item(index).text() progress.set_text("Processing \"{0}\"".format(fn_src)) md = pyexiv2.ImageMetadata(fn_src) image_ts = datetime.date try: md.read() image_ts = md['Exif.Photo.DateTimeOriginal'].value except: print("Cannot open file \"{0}\"".format(fn_src)) continue # Makes sure the day and month are always two digits def correct_format(number): if number < 10: return "0" + str(number) else: return str(number) folder_name_trg = str(image_ts.year) + separator + correct_format( image_ts.month) + separator + correct_format(image_ts.day) dir_name_trg = target_dir.absolutePath() + QDir.separator( ) + folder_name_trg # Create folder for day if necessary target_folder = QDir(dir_name_trg) if not target_folder.exists(): QDir.mkdir(target_dir, dir_name_trg) print("Created directory \"{0}\"".format(dir_name_trg)) # # STEP 2: Move file # # absolute file name of the new file fn_trg_abs = dir_name_trg + QDir.separator() + fn_src.split( QDir.separator())[-1] file_trg = QFile(fn_trg_abs) # Don't overwrite existing files if file_trg.exists(): print("Skipping file \"{0}\"".format(file_trg.fileName())) continue QFile.copy(fn_src, fn_trg_abs) print("Copied file from \"{0}\" to \"{1}\"".format(fn_src, fn_trg_abs)) print("Finished!")
if __name__ == "__main__": logger.info("Application started") import sys from src.controllers.maincontroller import MainController app = QApplication(sys.argv) qss = "qt_design/stylesheet.qss" with open(qss, "r") as fh: app.setStyleSheet(fh.read()) app.setApplicationName("CSCreator") data_location = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) data_dir = QDir(data_location) if not data_dir.exists(): data_dir.mkpath(data_location) if not data_dir.exists("importers"): data_dir.mkdir("importers") if os.environ.get("DEBUG") is not None: copytree("src/data/importers", os.path.join(data_location, "importers")) main_controller = MainController() main_view = main_controller.get_window() main_view.show() sys.exit(app.exec_())