def __load_compressed_complex(self, filename: str): obj = tarfile.open(filename, "r") members = obj.getmembers() obj.extract(members[0], QDir.tempPath()) extracted_filename = os.path.join(QDir.tempPath(), obj.getnames()[0]) self._fulldata = np.fromfile(extracted_filename, dtype=np.complex64) os.remove(extracted_filename)
def setDirPath(self, path): dir = QDir(path) self.beginResetModel() self.fileList = dir.entryList() self.fileCount = 0 self.endResetModel()
def __installEric6Doc(self, engine): """ Private method to install/update the eric6 help documentation. @param engine reference to the help engine (QHelpEngineCore) @return flag indicating success (boolean) """ versionKey = "eric6_ide" info = engine.customValue(versionKey, "") lst = info.split('|') dt = QDateTime() if len(lst) and lst[0]: dt = QDateTime.fromString(lst[0], Qt.ISODate) qchFile = "" if len(lst) == 2: qchFile = lst[1] docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help") files = docsPath.entryList(["*.qch"]) if not files: engine.setCustomValue( versionKey, QDateTime().toString(Qt.ISODate) + '|') return False for f in files: if f == "source.qch": fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f) if dt.isValid() and \ fi.lastModified().toString(Qt.ISODate) == \ dt.toString(Qt.ISODate) and \ qchFile == fi.absoluteFilePath(): return False namespace = QHelpEngineCore.namespaceName( fi.absoluteFilePath()) if not namespace: continue if namespace in engine.registeredDocumentations(): engine.unregisterDocumentation(namespace) if not engine.registerDocumentation(fi.absoluteFilePath()): self.errorMessage.emit( self.tr( """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>""") .format(fi.absoluteFilePath, engine.error()) ) return False engine.setCustomValue( versionKey, fi.lastModified().toString(Qt.ISODate) + '|' + fi.absoluteFilePath()) return True return False
def display_downloaded_content(self): """Open downloaded non-html content in a separate application. Called when an unsupported content type is finished downloading. """ file_path = ( QDir.toNativeSeparators( QDir.tempPath() + "/XXXXXX_" + self.content_filename ) ) myfile = QTemporaryFile(file_path) myfile.setAutoRemove(False) if myfile.open(): myfile.write(self.reply.readAll()) myfile.close() subprocess.Popen([ (self.config.get("content_handlers") .get(str(self.content_type))), myfile.fileName() ]) # Sometimes downloading files opens an empty window. # So if the current window has no URL, close it. if(str(self.url().toString()) in ('', 'about:blank')): self.close()
def load_extensions(self): """Load active extensions in topological order.""" root = self.root_directory() if not root in sys.path: sys.path.append(root) for ext in [ext for ext in self._extensions_ordered if not ext in self.inactive_extensions()]: try: # measure loading time start = perf_counter() # Try importing the module. Will fail here if there's # no Python module in the subdirectory or loading the module # produces errors module = importlib.import_module(ext) # Add extension's icons dir (if present) to icon search path icon_path = os.path.join(self.root_directory(), ext, 'icons') if os.path.isdir(icon_path): search_paths = QDir.searchPaths('icons') QDir.setSearchPaths('icons', [icon_path] + search_paths) # Instantiate the extension, # this will fail if the module is no valid extension # (doesn't have an Extension class) or has other errors in it extension = module.Extension(self, ext) end = perf_counter() extension.set_load_time( "{:.2f} ms".format((end - start) * 1000)) self._extensions[ext] = extension except Exception as e: self._failed_extensions[ext] = sys.exc_info()
def populateTemplates(self): self.tree.clear() self.tree.setIndentation(0) # Add templates item = self.addTopLevelItem(self.tr("Fiction")) templates = [i for i in self.templates() if i[2] == "Fiction"] for t in templates: sub = QTreeWidgetItem(item, [t[0]]) # Add templates: non-fiction item = self.addTopLevelItem(self.tr("Non-fiction")) templates = [i for i in self.templates() if i[2] == "Non-fiction"] for t in templates: sub = QTreeWidgetItem(item, [t[0]]) # Add Demo project item = self.addTopLevelItem(self.tr("Demo projects")) dir = QDir(appPath("sample-projects")) for f in dir.entryList(["*.msk"], filters=QDir.Files): sub = QTreeWidgetItem(item, [f[:-4]]) sub.setData(0, Qt.UserRole, f) self.tree.expandAll()
def getExportExtensionsList(self): extensions = [] for extsprefix in datadirs: extsdir = QDir(extsprefix+'/export-extensions/') if extsdir.exists(): for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'], QDir.Files | QDir.Readable): extensions.append(self.readExtension(fileInfo.filePath())) locale = QLocale.system().name() self.extensionActions = [] for extension in extensions: try: if ('Name[%s]' % locale) in extension: name = extension['Name[%s]' % locale] elif ('Name[%s]' % locale.split('_')[0]) in extension: name = extension['Name[%s]' % locale.split('_')[0]] else: name = extension['Name'] data = {} for prop in ('FileFilter', 'DefaultExtension', 'Exec'): if 'X-ReText-'+prop in extension: data[prop] = extension['X-ReText-'+prop] elif prop in extension: data[prop] = extension[prop] else: data[prop] = '' action = self.act(name, trig=self.extensionFunction(data)) if 'Icon' in extension: action.setIcon(self.actIcon(extension['Icon'])) mimetype = extension['MimeType'] if 'MimeType' in extension else None except KeyError: print('Failed to parse extension: Name is required', file=sys.stderr) else: self.extensionActions.append((action, mimetype))
def _appBundlePluginsPath(cls, appDirPath): ''' path to plugin directory of OSX app's bundle (especially when sandboxed, i.e. in a cls-contained bundle w/o shared libraries) If not (platform is OSX and app has PlugIns dir in the bundle), returns None. On other platforms (or when OSX app is not sandboxed) plugins are not usually bundled, but in the shared install directory of the Qt package. Implementation: use Qt since it understands colons (e.g. ':/') for resource paths. (Instead of Python os.path, which is problematic.) Convert string to QDir, move it around, convert back to string of abs path without colons. ''' # appDirPath typically "/Users/<user>/Library/<appName>.app/Contents/MacOS" on OSX. appDir = QDir(appDirPath) if not appDir.cdUp(): logAlert("Could not cdUp from appDir") # assert like ..../Contents if appDir.cd("PlugIns"): # !!! Capital I result = appDir.absolutePath() # assert like ..../Contents/PlugIns else: logAlert("Could not cd to PlugIns") result = None assert result is None or isinstance(result, str) return result
def requireScripts(self, urlList): """ Public method to get the sources of all required scripts. @param urlList list of URLs (list of string) @return sources of all required scripts (string) """ requiresDir = QDir(self.requireScriptsDirectory()) if not requiresDir.exists() or len(urlList) == 0: return "" script = "" settings = QSettings( os.path.join(self.requireScriptsDirectory(), "requires.ini"), QSettings.IniFormat) settings.beginGroup("Files") for url in urlList: if settings.contains(url): fileName = settings.value(url) try: f = open(fileName, "r", encoding="utf-8") source = f.read() f.close() except (IOError, OSError): source = "" script += source.strip() + "\n" return script
def on_mainscriptButton_clicked(self): """ Private slot to display a file selection dialog. """ dir = self.dirEdit.text() if not dir: dir = QDir.currentPath() patterns = [] for pattern, filetype in list(self.project.pdata["FILETYPES"].items()): if filetype == "SOURCES": patterns.append(pattern) filters = self.tr("Source Files ({0});;All Files (*)")\ .format(" ".join(patterns)) fn = E5FileDialog.getOpenFileName( self, self.tr("Select main script file"), dir, filters) if fn: ppath = self.dirEdit.text() if ppath: ppath = QDir(ppath).absolutePath() + QDir.separator() fn = fn.replace(ppath, "") self.mainscriptEdit.setText(Utilities.toNativeSeparators(fn))
def __locate_code_in_project(self, queue_folders, nproject): file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable while not self._cancel and not queue_folders.empty(): current_dir = QDir(queue_folders.get()) #Skip not readable dirs! if not current_dir.isReadable(): continue #Collect all sub dirs! current_sub_dirs = current_dir.entryInfoList(dir_filter) for one_dir in current_sub_dirs: queue_folders.put(one_dir.absoluteFilePath()) #all files in sub_dir first apply the filters current_files = current_dir.entryInfoList( ['*{0}'.format(x) for x in nproject.extensions], file_filter) #process all files in current dir! global files_paths for one_file in current_files: try: self._grep_file_symbols(one_file.absoluteFilePath(), one_file.fileName()) files_paths[nproject.path].append( one_file.absoluteFilePath()) except Exception as reason: logger.error( '__locate_code_in_project, error: %r' % reason) logger.error( '__locate_code_in_project fail for file: %r' % one_file.absoluteFilePath())
def file_less_suffix(FBTS): qd = QDir( FBTS.folderpath() ) qd.setFilter(QDir.Files | QDir.Readable) if qd.exists(FBTS.basename()): a_file = QFile( qd.absoluteFilePath(FBTS.basename()) ) return _qfile_to_stream(a_file, FBTS.open_mode()) return None
def on_pathButton_clicked(self): """ Private slot called to open a directory selection dialog. """ path = E5FileDialog.getExistingDirectory( self, self.tr("Select source directory"), QDir.fromNativeSeparators(self.pathnameEdit.text()) ) if path: self.pathnameEdit.setText(QDir.toNativeSeparators(path))
def populateProjectDirectoryItem(self, parentItem, repopulate=False): """ Public method to populate a directory item's subtree. @param parentItem reference to the directory item to be populated @param repopulate flag indicating a repopulation (boolean) """ self._addWatchedItem(parentItem) qdir = QDir(parentItem.dirName()) if Preferences.getUI("BrowsersListHiddenFiles"): filter = QDir.Filters(QDir.AllEntries | QDir.Hidden | QDir.NoDotAndDotDot) else: filter = QDir.Filters(QDir.AllEntries | QDir.NoDot | QDir.NoDotDot) entryInfoList = qdir.entryInfoList(filter) if len(entryInfoList) > 0: if repopulate: self.beginInsertRows(self.createIndex( parentItem.row(), 0, parentItem), 0, len(entryInfoList) - 1) states = {} if self.project.vcs is not None: for f in entryInfoList: fname = f.absoluteFilePath() states[os.path.normcase(fname)] = 0 dname = parentItem.dirName() self.project.vcs.clearStatusCache() states = self.project.vcs.vcsAllRegisteredStates(states, dname) for f in entryInfoList: if f.isDir(): node = ProjectBrowserDirectoryItem( parentItem, Utilities.toNativeSeparators(f.absoluteFilePath()), parentItem.getProjectTypes()[0], False) else: node = ProjectBrowserFileItem( parentItem, Utilities.toNativeSeparators(f.absoluteFilePath()), parentItem.getProjectTypes()[0]) if self.project.vcs is not None: fname = f.absoluteFilePath() if states[os.path.normcase(fname)] == \ self.project.vcs.canBeCommitted: node.addVcsStatus(self.project.vcs.vcsName()) self.project.clearStatusMonitorCachedState( f.absoluteFilePath()) else: node.addVcsStatus(self.tr("local")) self._addItem(node, parentItem) if repopulate: self.endInsertRows()
def select_new_dir(self): self.hyperlpr_dir_path = QFileDialog.getExistingDirectory( self, "读取文件夹", QDir.currentPath()) if len(self.hyperlpr_dir_path) > 0: hyperlpr_dir_info_filepath = QDir.homePath() + "/hyperlpr_dir_file" with open(hyperlpr_dir_info_filepath, 'w') as f: f.write(self.hyperlpr_dir_path) self.reset_info_gui()
def __load(self): """ Private slot to load the available scripts into the manager. """ scriptsDir = QDir(self.scriptsDirectory()) if not scriptsDir.exists(): scriptsDir.mkpath(self.scriptsDirectory()) if not scriptsDir.exists("requires"): scriptsDir.mkdir("requires") self.__disabledScripts = \ Preferences.getHelp("GreaseMonkeyDisabledScripts") from .GreaseMonkeyScript import GreaseMonkeyScript for fileName in scriptsDir.entryList(["*.js"], QDir.Files): absolutePath = scriptsDir.absoluteFilePath(fileName) script = GreaseMonkeyScript(self, absolutePath) if script.fullName() in self.__disabledScripts: script.setEnabled(False) if script.startAt() == GreaseMonkeyScript.DocumentStart: self.__startScripts.append(script) else: self.__endScripts.append(script)
def path_with_tilde_homepath(path): if IS_WINDOWS: return path home_path = QDir.homePath() fi = QFileInfo(QDir.cleanPath(path)) outpath = fi.absoluteFilePath() if outpath.startswith(home_path): outpath = "~" + outpath[len(home_path):] else: outpath = path return outpath
def _write_package_contents(self, contents, dst_dir, src_dir, dir_stack, job_writer, resource_contents): """ Write the contents of a single package directory. """ self._create_directory(dst_dir) for content in contents: if not content.included: continue if isinstance(content, QrcDirectory): dir_stack.append(content.name) self._write_package_contents(content.contents, dst_dir + '/' + content.name, src_dir + '/' + content.name, dir_stack, job_writer, resource_contents) dir_stack.pop() else: freeze_file = True src_file = content.name src_path = src_dir + '/' + src_file if src_file.endswith('.py'): dst_file = src_file[:-3] + '.pyo' elif src_file.endswith('.pyw'): dst_file = src_file[:-4] + '.pyo' else: # Just copy the file. dst_file = src_file freeze_file = False dst_path = dst_dir + '/' + dst_file file_path = list(dir_stack) file_path.append(dst_file) file_path = '/'.join(file_path) if freeze_file: self._freeze(job_writer, dst_path, src_path, file_path[:-1]) else: src_path = QDir.toNativeSeparators(src_path) dst_path = QDir.toNativeSeparators(dst_path) try: shutil.copyfile(src_path, dst_path) except FileNotFoundError: raise UserException( "{0} does not seem to exist".format(src_path)) resource_contents.append(file_path)
def setCurrentFile(self): self.setWindowTitle("") self.tabWidget.setTabText(self.ind, self.currentTab.getDocumentTitle(baseName=True)) self.setWindowFilePath(self.currentTab.fileName) files = readListFromSettings("recentFileList") while self.currentTab.fileName in files: files.remove(self.currentTab.fileName) files.insert(0, self.currentTab.fileName) if len(files) > 10: del files[10:] writeListToSettings("recentFileList", files) QDir.setCurrent(QFileInfo(self.currentTab.fileName).dir().path()) self.docTypeChanged()
def copy_freeze(src, dst): for skip in skip_dirs: if skip in src: break else: if dst.endswith('.py'): src = QDir.fromNativeSeparators(src) dst = QDir.fromNativeSeparators(dst) rel_dst = dst[len(resources_dir) + 1:] + 'o' self._freeze(job_writer, dst + 'o', src, rel_dst) resource_contents.append(rel_dst)
def _freeze(job_writer, out_file, in_file, name, as_c=False): """ Freeze a Python source file to a C header file or a data file. """ out_file = QDir.toNativeSeparators(out_file) in_file = QDir.toNativeSeparators(in_file) if as_c: conversion = 'C' else: name = ':/' + name conversion = 'data' job_writer.writerow([out_file, in_file, name, conversion])
def related_file(FBTS, filename, encoding=None): qd = QDir( FBTS.folderpath() ) qd.setFilter(QDir.Files | QDir.Readable) qd.setSorting(QDir.Type | QDir.Reversed) qd.setNameFilters( [filename] ) # literal name or 'foo*.*' names = qd.entryList() if names : # list is not empty, open the first a_file = QFile( qd.absoluteFilePath(names[0]) ) return _qfile_to_stream(a_file, QIODevice.ReadOnly, encoding) return None
def validate_project(project_dir): selected_dir = QDir(project_dir) if not selected_dir.exists(): QMessageBox.critical(None, 'Dir does not exist', 'Dir does not exist', QMessageBox.Yes, QMessageBox.Yes) return False if not selected_dir.exists('src/global.config'): QMessageBox.critical(None, 'Project validation error', 'Project dir does not contain src/global.config', QMessageBox.Yes, QMessageBox.Yes) return False return True
def findStampFileName(name, currentFileName=''): invalidChars = QRegularExpression("[^\\w -]+") prefs = preferences.Preferences.instance() stampsDir = QDir(prefs.stampsDirectory()) suggestedFileName = name.toLower().remove(invalidChars) fileName = suggestedFileName + ".stamp" if (fileName == currentFileName or not stampsDir.exists(fileName)): return fileName n = 2 while (fileName != currentFileName and stampsDir.exists(fileName)): fileName = suggestedFileName + QString.number(n) + ".stamp" n += 1 return fileName
def __init__(self, parent, dirName): """ Constructor @param parent parent widget (QWidget) @param dirName name of directory to show (string) """ super(IconsPreviewDialog, self).__init__(parent) self.setupUi(self) dir = QDir(dirName) for icon in dir.entryList(["*.png"]): QListWidgetItem( QIcon(os.path.join(dirName, icon)), icon, self.iconView)
def _run_freeze(self, freeze, job_filename, opt): """ Run the accumlated freeze jobs. """ # Note that we assume a relative filename is on PATH rather than being # relative to the project file. interp = os.path.expandvars(self._project.python_host_interpreter) # On Windows the interpreter name is simply 'python'. So in order to # make the .pdy file more portable we strip any trailing version # number. if sys.platform == 'win32': for i in range(len(interp) - 1, -1, -1): if interp[i] not in '.0123456789': interp = interp[:i + 1] break argv = [QDir.toNativeSeparators(interp)] if opt == 2: argv.append('-OO') elif opt == 1: argv.append('-O') argv.append(freeze) argv.append(job_filename) self.run(argv, "Unable to freeze files")
def __init__(self, defaultClassName, defaultFile, defaultPath, parent=None): """ Constructor @param defaultClassName proposed name for the new class (string) @param defaultFile proposed name for the source file (string) @param defaultPath default path for the new file (string) @param parent parent widget if the dialog (QWidget) """ super(NewDialogClassDialog, self).__init__(parent) self.setupUi(self) self.pathButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.okButton = self.buttonBox.button(QDialogButtonBox.Ok) self.okButton.setEnabled(False) self.pathnameCompleter = E5DirCompleter(self.pathnameEdit) self.classnameEdit.setText(defaultClassName) self.filenameEdit.setText(defaultFile) self.pathnameEdit.setText(QDir.toNativeSeparators(defaultPath)) msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def get_save_file_name(*args, **kwargs): filename, _selected_filter = QFileDialog.getSaveFileName(*args, **kwargs) if len(filename) > 0: filename = QDir.toNativeSeparators(filename) return filename
def __init__(self, vcs, project, parent=None): """ Constructor @param vcs reference to the version control object @param project reference to the project object @param parent parent widget (QWidget) """ super(SvnOptionsDialog, self).__init__(parent) self.setupUi(self) self.vcsUrlPicker.setMode(E5PathPickerModes.DirectoryMode) self.project = project self.protocolCombo.addItems(ConfigSvnProtocols) hd = Utilities.toNativeSeparators(QDir.homePath()) hd = os.path.join(hd, 'subversionroot') self.vcsUrlPicker.setText(hd) self.vcs = vcs self.localPath = hd self.networkPath = "localhost/" self.localProtocol = True msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def Successful_Tmp(self):# CheckTmpDir, StateTmpDir failed = lambda: not self.tdir or not self.tdir.isValid() if failed():# not successfully self.tdir = QTemporaryDir() if failed(): QMessageBox.critical(self, "Unexpected Failurer", "The application has detected a problem trying to\nCreate or Access a Temporary File!.") return None else: self.tdir.setAutoRemove(True) d = QDir(self.tdir.path()) if not d.exists("ninja-ide"): if not d.mkdir("ninja-ide"): self.tdir = None d.cd("ninja-ide") return d
def join(self, filelist: list, output: str) -> bool: args = '-f concat -safe 0 -i "%s" -c copy -y "%s"' % ( filelist, QDir.fromNativeSeparators(output)) return self.cmdExec(self.backend, args)
# PyQt5 Imports from PyQt5 import uic from PyQt5.QtWidgets import QWidget from PyQt5.QtCore import pyqtSignal, QDir # Own Imports from kmap import __directory__ # Load .ui File UI_file = __directory__ + QDir.toNativeSeparators('/ui/realplotoptions.ui') RealPlotOptions_UI, _ = uic.loadUiType(UI_file) class RealPlotOptions(QWidget, RealPlotOptions_UI): set_camera = pyqtSignal(int, int, int) show_grid_changed = pyqtSignal(int) show_mesh_changed = pyqtSignal(int) show_bonds_changed = pyqtSignal(int) show_photon_changed = pyqtSignal(int) show_hemisphere_changed = pyqtSignal(int) iso_val_changed = pyqtSignal() def __init__(self, plot_item): # Setup GUI super(RealPlotOptions, self).__init__() self.setupUi(self) self._connect() def reset_camera(self):
def export(self): fname, _ = QFileDialog.getSaveFileName(self, "Export device list as...", directory=QDir.homePath(), filter="CSV files (*.csv)") if fname: if not fname.endswith(".csv"): fname += ".csv" with open(fname, "w", encoding='utf8') as f: column_titles = ['mac', 'topic', 'friendly_name', 'full_topic', 'cmnd_topic', 'stat_topic', 'tele_topic', 'module', 'module_id', 'firmware', 'core'] c = csv.writer(f) c.writerow(column_titles) for r in range(self.device_model.rowCount()): d = self.device_model.index(r,0) c.writerow([ self.device_model.mac(d), self.device_model.topic(d), self.device_model.friendly_name(d), self.device_model.fullTopic(d), self.device_model.commandTopic(d), self.device_model.statTopic(d), self.device_model.teleTopic(d), # modules.get(self.device_model.module(d)), self.device_model.module(d), self.device_model.firmware(d), self.device_model.core(d) ])
def _readSettings(self): self.settings.beginGroup("FileSystem") self._file_open_path = self.settings.value("openpath", QDir().homePath()) self.settings.endGroup()
def tempFile(name): "Returns a temp file." return os.path.join(QDir.tempPath(), name)
# Python Imports import logging # PyQt5 Imports from PyQt5 import uic from PyQt5.QtCore import pyqtSignal, QDir from PyQt5.QtWidgets import QWidget # Own Imports from kmap import __directory__ # Load .ui File UI_file = __directory__ + QDir.toNativeSeparators('/ui/polarization.ui') Polarization_UI, _ = uic.loadUiType(UI_file) class Polarization(QWidget, Polarization_UI): polarization_changed = pyqtSignal() def __init__(self, *args, **kwargs): # Setup GUI super(Polarization, self).__init__(*args, **kwargs) self.setupUi(self) self._connect() def change_polarization(self): self.polarization_changed.emit()
def __init__(self): super().__init__() self.start_log() self.get_config() self.grid_layout = QGridLayout() self.image_folder = QDir.currentPath() self.setWindowTitle("BS Downloader 3.0.0-alpha.2") self.setLayout(self.grid_layout) # Textbox Burning Series Url self.label_url = QLabel(self) self.label_url.setText("Burning Series Url: ") self.grid_layout.addWidget(self.label_url, 0, 0) self.textbox_url = QLineEdit(self) self.textbox_url.setToolTip("The url of the series you want to download from Burning Series.") self.grid_layout.addWidget(self.textbox_url, 0, 1, 1, 3) self.textbox_url.editingFinished.connect(self.textbox_change) # Save Folder self.label_save_folder = QLabel(self) self.label_save_folder.setText("Save Folder: ") self.grid_layout.addWidget(self.label_save_folder, 1, 0) self.button_save_folder = QPushButton("Browse...") self.button_save_folder.setToolTip("The folder the series is gonna be saved to, can be auto selected.") self.grid_layout.addWidget(self.button_save_folder, 1, 1, 1, 3) self.button_save_folder.clicked.connect(self.on_save_folder_click) # Download from self.label_download_from = QLabel(self) self.label_download_from.setText("Download from: ") self.grid_layout.addWidget(self.label_download_from, 2, 0) self.textbox_download_from = QLineEdit(self) self.textbox_download_from.setToolTip("The Episode you want to start downloading at.") try: fcount = 0 for file in os.listdir(self.cfg_dlfolder): fcount += 1 self.textbox_download_from.setText(str(fcount + 1)) except: pass self.grid_layout.addWidget(self.textbox_download_from, 2, 1) # to self.label_download_to = QLabel(self) self.label_download_to.setText("Download to: ") self.grid_layout.addWidget(self.label_download_to, 2, 2) self.textbox_download_to = QLineEdit(self) self.textbox_download_to.setToolTip("The Episode you want to stop downloading at.") self.grid_layout.addWidget(self.textbox_download_to, 2, 3) # Preferred Platform self.label_preferred_platform = QLabel(self) self.label_preferred_platform.setText("Preferred Platform: ") self.grid_layout.addWidget(self.label_preferred_platform, 3, 0) self.combobox_preferred_platform = QComboBox(self) self.combobox_preferred_platform.addItem("Vivo") self.combobox_preferred_platform.addItem("Streamtape") self.combobox_preferred_platform.addItem("Vupload") self.combobox_preferred_platform.addItem("Vidoza") self.combobox_preferred_platform.setCurrentIndex(0) self.combobox_preferred_platform.setToolTip("The streaming service the series will be downloaded from.") self.grid_layout.addWidget(self.combobox_preferred_platform, 3, 1, 1, 3) # Use Threading self.label_threading = QLabel(self) self.label_threading.setText("Threading: ") self.grid_layout.addWidget(self.label_threading, 4, 0) def box_change(): if self.checkbox_threading.checkState() == 0: self.textbox_threading.setDisabled(True) else: self.textbox_threading.setEnabled(True) self.checkbox_threading = QCheckBox("Use Threading") self.checkbox_threading.setChecked(True) self.checkbox_threading.setToolTip("Simultaneous Downloads.") self.grid_layout.addWidget(self.checkbox_threading, 4, 1) self.checkbox_threading.stateChanged.connect(box_change) self.textbox_threading = QLineEdit(self) self.textbox_threading.setText("5") self.textbox_threading.setToolTip("How many simultaneous downloads you want.") self.grid_layout.addWidget(self.textbox_threading, 4, 2, 1, 2) # Config & Start self.button_config = QPushButton(self) self.button_config.setText("Config") self.button_config.setToolTip("Open the configuration.") self.grid_layout.addWidget(self.button_config, 5, 0) self.button_config.clicked.connect(self.on_config_click) self.button_start = QPushButton(self) self.button_start.setText("Start!") self.button_start.setToolTip("Start the download.") self.grid_layout.addWidget(self.button_start, 5, 1, 1, 3) self.button_start.clicked.connect(self.on_start_click)
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QMessageBox from PyQt5.QtCore import QDir # Own Imports from kmap import __directory__, __version__ from kmap.controller.databasewindows import (OrbitalDatabase, SlicedDatabaseWindow) from kmap.controller.tabwidget import TabWidget from kmap.controller.tabchoosewindow import TabChooseWindow from kmap.model.mainwindow_model import MainWindowModel from kmap.controller.sliceddatatab import SlicedDataTab from kmap.controller.orbitaldatatab import OrbitalDataTab from kmap.config.config import config # Load .ui File UI_file = __directory__ + QDir.toNativeSeparators('/ui/mainwindow.ui') MainWindow_UI, _ = uic.loadUiType(UI_file) class MainWindow(QMainWindow, MainWindow_UI): def __init__(self): # Setup GUI super(MainWindow, self).__init__() self.setupUi(self) self._setup() self._connect() self.sub_windows = {} self.model = MainWindowModel(self)
@pyqtSlot(str) def callme(self, arg: str): # b = a.toObject() print(arg) js_call = jscall() channel = QWebChannel(Page) channel.registerObject("webobj", js_call) Page.setWebChannel(channel) def _status(status): print('load status: ', status) # Page.runJavaScript('window.d487 = document.getElementsByTagName("img")', _js) # Page.runJavaScript('d487[1].src',_js) # Page.runJavaScript('Qt.ev("document.getElementsByTagName(\'a\')")[1].click()', _js) Page.runJavaScript('Qt.register()', _js) def _js(result): print('js result: ', result) Page.loadFinished.connect(_status) Page.load(QUrl.fromLocalFile(QDir.currentPath()+'/index.html')) view.show() app.exec()
def browseForOutput(self): directory = QFileDialog.getExistingDirectory(self, "Select output folder", QDir.currentPath()) self.outputPath.setText(directory)
def test_generation(self): """ Complex test including much functionality 1) Load a Signal 2) Set Decoding in Compareframe 3) Move with encoding to Generator 4) Generate datafile 5) Read datafile and compare with original signal """ # Load a Signal self.add_signal_to_form("ask.complex") signal_frame = self.form.signal_tab_controller.signal_frames[0] signal_frame.ui.cbModulationType.setCurrentIndex(0) # ASK signal_frame.ui.spinBoxInfoLen.setValue(300) signal_frame.ui.spinBoxInfoLen.editingFinished.emit() signal_frame.ui.spinBoxCenterOffset.setValue(0.032) signal_frame.ui.spinBoxCenterOffset.editingFinished.emit() signal_frame.ui.cbProtoView.setCurrentIndex(0) proto = "1011001001011011011011011011011011001000000" self.assertTrue( signal_frame.ui.txtEdProto.toPlainText().startswith(proto)) # Set Decoding self.form.ui.tabWidget.setCurrentIndex(1) cfc = self.form.compare_frame_controller cfc.ui.cbDecoding.setCurrentIndex(1) # NRZ-I proto_inv = cfc.proto_analyzer.decoded_proto_bits_str[0] self.assertTrue(self.__is_inv_proto(proto, proto_inv)) # Move with encoding to generator gframe = self.form.generator_tab_controller # type: GeneratorTabController gframe.ui.cbViewType.setCurrentIndex(0) self.add_signal_to_generator(signal_index=0) self.assertEqual(array.array("B", list(map(int, proto_inv))), gframe.table_model.display_data[0]) self.assertNotEqual(array.array("B", list(map(int, proto))), gframe.table_model.display_data[0]) gframe.table_model.protocol.messages[0].pause = 0 # Generate Datafile modulator = gframe.modulators[0] modulator.modulation_type = "ASK" modulator.samples_per_symbol = 300 buffer = gframe.prepare_modulation_buffer( gframe.total_modulated_samples, show_error=False) modulated_data = gframe.modulate_data(buffer) filename = os.path.join(QDir.tempPath(), "test_generator.complex") modulated_data.tofile(filename) # Reload datafile and see if bits match self.form.add_signalfile(filename) self.assertEqual(len(self.form.signal_tab_controller.signal_frames), 2) signal_frame = self.form.signal_tab_controller.signal_frames[1] self.assertEqual(signal_frame.signal.num_samples, 300 * len(proto)) signal_frame.ui.cbProtoView.setCurrentIndex(0) self.assertEqual(signal_frame.ui.lineEditSignalName.text(), "test_generator") signal_frame.ui.cbModulationType.setCurrentIndex(0) # ASK signal_frame.ui.spinBoxNoiseTreshold.setValue(0) signal_frame.ui.spinBoxNoiseTreshold.editingFinished.emit() signal_frame.ui.spinBoxInfoLen.setValue(295) signal_frame.ui.spinBoxInfoLen.editingFinished.emit() signal_frame.ui.spinBoxCenterOffset.setValue(0.1) signal_frame.ui.spinBoxCenterOffset.editingFinished.emit() signal_frame.ui.spinBoxTolerance.setValue(6) signal_frame.ui.spinBoxTolerance.editingFinished.emit() self.assertEqual(len(signal_frame.proto_analyzer.messages), 1) gen_proto = signal_frame.ui.txtEdProto.toPlainText() gen_proto = gen_proto[:gen_proto.index(" ")] self.assertTrue(proto.startswith(gen_proto))
def mqtt_message(self, topic, msg): found = self.device_model.findDevice(topic) if found.reply == 'LWT': if not msg: msg = "offline" if found.index.isValid(): self.console_log(topic, "LWT update: {}".format(msg), msg) self.device_model.updateValue(found.index, DevMdl.LWT, msg) self.initial_query(found.index, queued=True) elif msg == "Online": self.console_log( topic, "LWT for unknown device '{}'. Asking for FullTopic.". format(found.topic), msg, False) self.mqtt_queue.append( ["cmnd/{}/fulltopic".format(found.topic), ""]) self.mqtt_queue.append( ["{}/cmnd/fulltopic".format(found.topic), ""]) elif found.reply == 'RESULT': try: full_topic = loads(msg).get('FullTopic') new_topic = loads(msg).get('Topic') template_name = loads(msg).get('NAME') ota_url = loads(msg).get('OtaUrl') teleperiod = loads(msg).get('TelePeriod') if full_topic: # TODO: update FullTopic for existing device AFTER the FullTopic changes externally (the message will arrive from new FullTopic) if not found.index.isValid(): self.console_log( topic, "FullTopic for {}".format(found.topic), msg, False) new_idx = self.device_model.addDevice(found.topic, full_topic, lwt='online') tele_idx = self.telemetry_model.addDevice( TasmotaDevice, found.topic) self.telemetry_model.devices[found.topic] = tele_idx #TODO: add QSortFilterProxyModel to telemetry treeview and sort devices after adding self.initial_query(new_idx) self.console_log( topic, "Added {} with fulltopic {}, querying for STATE". format(found.topic, full_topic), msg) self.tview.expand(tele_idx) self.tview.resizeColumnToContents(0) elif new_topic: if found.index.isValid() and found.topic != new_topic: self.console_log( topic, "New topic for {}".format(found.topic), msg) self.device_model.updateValue(found.index, DevMdl.TOPIC, new_topic) tele_idx = self.telemetry_model.devices.get( found.topic) if tele_idx: self.telemetry_model.setDeviceName( tele_idx, new_topic) self.telemetry_model.devices[ new_topic] = self.telemetry_model.devices.pop( found.topic) elif template_name: self.device_model.updateValue( found.index, DevMdl.MODULE, "{} (0)".format(template_name)) elif ota_url: self.device_model.updateValue(found.index, DevMdl.OTA_URL, ota_url) elif teleperiod: self.device_model.updateValue(found.index, DevMdl.TELEPERIOD, teleperiod) except JSONDecodeError as e: self.console_log( topic, "JSON payload decode error. Check error.log for additional info." ) with open("{}/TDM/error.log".format(QDir.homePath()), "a+") as l: l.write("{}\t{}\t{}\t{}\n".format( QDateTime.currentDateTime().toString( "yyyy-MM-dd hh:mm:ss"), topic, msg, e.msg)) elif found.index.isValid(): ok = False try: if msg.startswith("{"): payload = loads(msg) else: payload = msg ok = True except JSONDecodeError as e: self.console_log( topic, "JSON payload decode error. Check error.log for additional info." ) with open("{}/TDM/error.log".format(QDir.homePath()), "a+") as l: l.write("{}\t{}\t{}\t{}\n".format( QDateTime.currentDateTime().toString( "yyyy-MM-dd hh:mm:ss"), topic, msg, e.msg)) if ok: try: if found.reply == 'STATUS': self.console_log(topic, "Received device status", msg) payload = payload['Status'] self.device_model.updateValue( found.index, DevMdl.FRIENDLY_NAME, payload['FriendlyName'][0]) self.telemetry_model.setDeviceFriendlyName( self.telemetry_model.devices[found.topic], payload['FriendlyName'][0]) module = payload['Module'] if module == 0: self.mqtt.publish( self.device_model.commandTopic(found.index) + "template") else: self.device_model.updateValue( found.index, DevMdl.MODULE, modules.get(module, 'Unknown')) self.device_model.updateValue(found.index, DevMdl.MODULE_ID, module) elif found.reply == 'STATUS1': self.console_log(topic, "Received program information", msg) payload = payload['StatusPRM'] self.device_model.updateValue( found.index, DevMdl.RESTART_REASON, payload.get('RestartReason')) self.device_model.updateValue(found.index, DevMdl.OTA_URL, payload.get('OtaUrl')) elif found.reply == 'STATUS2': self.console_log(topic, "Received firmware information", msg) payload = payload['StatusFWR'] self.device_model.updateValue(found.index, DevMdl.FIRMWARE, payload['Version']) self.device_model.updateValue(found.index, DevMdl.CORE, payload['Core']) elif found.reply == 'STATUS3': self.console_log(topic, "Received syslog information", msg) payload = payload['StatusLOG'] self.device_model.updateValue(found.index, DevMdl.TELEPERIOD, payload['TelePeriod']) elif found.reply == 'STATUS5': self.console_log(topic, "Received network status", msg) payload = payload['StatusNET'] self.device_model.updateValue(found.index, DevMdl.MAC, payload['Mac']) self.device_model.updateValue(found.index, DevMdl.IP, payload['IPAddress']) elif found.reply in ('STATE', 'STATUS11'): self.console_log(topic, "Received device state", msg) if found.reply == 'STATUS11': payload = payload['StatusSTS'] self.parse_state(found.index, payload) elif found.reply in ('SENSOR', 'STATUS8'): self.console_log(topic, "Received telemetry", msg) if found.reply == 'STATUS8': payload = payload['StatusSNS'] self.parse_telemetry(found.index, payload) elif found.reply.startswith('POWER'): self.console_log( topic, "Received {} state".format(found.reply), msg) payload = {found.reply: msg} self.parse_power(found.index, payload) except KeyError as k: self.console_log( topic, "JSON key error. Check error.log for additional info.") with open("{}/TDM/error.log".format(QDir.homePath()), "a+") as l: l.write("{}\t{}\t{}\tKeyError: {}\n".format( QDateTime.currentDateTime().toString( "yyyy-MM-dd hh:mm:ss"), topic, payload, k.args[0]))
def get_qml_resource(qmlpath): path_qml = QDir.fromNativeSeparators( os.path.join(resources.QML_FILES, qmlpath)) path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file')) return QUrl(path_qml)
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from pkg_resources import resource_filename, resource_string from PyQt5.QtGui import QPixmap, QIcon, QMovie from PyQt5.QtCore import QDir import os # The following lines add the images and css directories to the search path. QDir.addSearchPath("images", resource_filename(__name__, "images")) QDir.addSearchPath("css", resource_filename(__name__, "css")) def path(name, resource_dir="images/", ext=""): """Return the filename for the referenced image.""" return resource_filename(__name__, resource_dir + name + ext) def load_icon(name): """Load an icon from the resources directory.""" svg_path = path(name, ext=".svg") if os.path.exists(svg_path): svg_icon = QIcon(svg_path) if svg_icon: return svg_icon
def _open_config_folder(self): QDesktopServices.openUrl( QUrl("file:///" + QDir.toNativeSeparators(cfclient.config_path)))
def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) pasteBox = QHBoxLayout() self.textLine = QLineEdit() self.textLine.setToolTip('Current Director/selected File') self.pasteButton = QToolButton() self.pasteButton.setEnabled(False) self.pasteButton.setText('Paste') self.pasteButton.setToolTip( 'Copy file from copy path to current directory/file') self.pasteButton.clicked.connect(self.paste) self.pasteButton.hide() pasteBox.addWidget(self.textLine) pasteBox.addWidget(self.pasteButton) self.copyBox = QFrame() hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.copyLine = QLineEdit() self.copyLine.setToolTip('File path to copy from, when pasting') self.copyButton = QToolButton() self.copyButton.setText('Copy') self.copyButton.setToolTip('Record current file as copy path') self.copyButton.clicked.connect(self.recordCopyPath) hbox.addWidget(self.copyButton) hbox.addWidget(self.copyLine) self.copyBox.setLayout(hbox) self.copyBox.hide() self.model = QFileSystemModel() self.model.setRootPath(QDir.currentPath()) self.model.setFilter(QDir.AllDirs | QDir.NoDot | QDir.Files) self.model.setNameFilterDisables(False) self.model.rootPathChanged.connect(self.folderChanged) self.list = QListView() self.list.setModel(self.model) self.list.resize(640, 480) self.list.clicked[QModelIndex].connect(self.listClicked) self.list.activated.connect(self._getPathActivated) self.list.setAlternatingRowColors(True) self.list.hide() self.table = QTableView() self.table.setModel(self.model) self.table.resize(640, 480) self.table.clicked[QModelIndex].connect(self.listClicked) self.table.activated.connect(self._getPathActivated) self.table.setAlternatingRowColors(True) header = self.table.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.Stretch) header.setSectionResizeMode(1, QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QHeaderView.ResizeToContents) header.swapSections(1, 3) header.setSortIndicator(1, Qt.AscendingOrder) self.table.setSortingEnabled(True) self.table.setColumnHidden(2, True) # type self.table.verticalHeader().setVisible(False) # row count header self.cb = QComboBox() self.cb.currentIndexChanged.connect(self.filterChanged) self.fillCombobox(INFO.PROGRAM_FILTERS_EXTENSIONS) self.cb.setMinimumHeight(30) self.cb.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.button2 = QToolButton() self.button2.setText('User') self.button2.setSizePolicy( QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.button2.setMinimumSize(60, 30) self.button2.setToolTip( 'Jump to User directory.\nLong press for Options.') self.button2.clicked.connect(self.onJumpClicked) self.button3 = QToolButton() self.button3.setText('Add Jump') self.button3.setSizePolicy( QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.button3.setMinimumSize(60, 30) self.button3.setToolTip('Add current directory to jump button list') self.button3.clicked.connect(self.onActionClicked) self.settingMenu = QMenu(self) self.button2.setMenu(self.settingMenu) hbox = QHBoxLayout() hbox.addWidget(self.button2) hbox.addWidget(self.button3) hbox.insertStretch(2, stretch=0) hbox.addWidget(self.cb) windowLayout = QVBoxLayout() windowLayout.addLayout(pasteBox) windowLayout.addWidget(self.copyBox) windowLayout.addWidget(self.list) windowLayout.addWidget(self.table) windowLayout.addLayout(hbox) self.setLayout(windowLayout) self.show()
def open(self): from src.operations import ImageOperations self.imgpath = QFileDialog.getOpenFileName(self, "Open Image", QDir.currentPath())[0] imgopt = ImageOperations.ImageOperations() imgopt.openImage(self, self.imgpath)
def __init__(self, filename: str, name: str, wav_is_qad_demod=False, modulation: str = None, sample_rate: float = 1e6, parent=None): super().__init__(parent) self.__name = name self.__tolerance = 5 self.__bit_len = 100 self._qad = None self.__qad_center = 0 self._noise_threshold = 0 self.__sample_rate = sample_rate self.noise_min_plot = 0 self.noise_max_plot = 0 self.block_protocol_update = False self.auto_detect_on_modulation_changed = True self.wav_mode = filename.endswith(".wav") self.__changed = False self.qad_demod_file_loaded = wav_is_qad_demod if modulation is None: modulation = "FSK" self.__modulation_type = self.MODULATION_TYPES.index(modulation) self.__parameter_cache = { mod: { "qad_center": None, "bit_len": None } for mod in self.MODULATION_TYPES } if len(filename) > 0: # Daten auslesen if not self.wav_mode: if not filename.endswith(".coco"): if filename.endswith(".complex16u"): # two 8 bit unsigned integers raw = np.fromfile(filename, dtype=[('r', np.uint8), ('i', np.uint8)]) self._fulldata = np.empty(raw.shape[0], dtype=np.complex64) self._fulldata.real = (raw['r'] / 127.5) - 1.0 self._fulldata.imag = (raw['i'] / 127.5) - 1.0 elif filename.endswith(".complex16s"): # two 8 bit signed integers raw = np.fromfile(filename, dtype=[('r', np.int8), ('i', np.int8)]) self._fulldata = np.empty(raw.shape[0], dtype=np.complex64) self._fulldata.real = (raw['r'] + 0.5) / 127.5 self._fulldata.imag = (raw['i'] + 0.5) / 127.5 else: self._fulldata = np.fromfile( filename, dtype=np.complex64) # Uncompressed else: obj = tarfile.open(filename, "r") members = obj.getmembers() obj.extract(members[0], QDir.tempPath()) extracted_filename = os.path.join(QDir.tempPath(), obj.getnames()[0]) self._fulldata = np.fromfile(extracted_filename, dtype=np.complex64) os.remove(extracted_filename) self._fulldata = np.ascontiguousarray( self._fulldata, dtype=np.complex64) # type: np.ndarray else: f = wave.open(filename, "r") n = f.getnframes() unsigned_bytes = struct.unpack('<{0:d}B'.format(n), f.readframes(n)) if not self.qad_demod_file_loaded: # Complex To Real WAV File load self._fulldata = np.empty(n, dtype=np.complex64, order="C") self._fulldata.real = np.multiply( 1 / 256, np.subtract(unsigned_bytes, 128)) self._fulldata.imag = [-1 / 128] * n else: self._fulldata = np.multiply( 1 / 256, np.subtract(unsigned_bytes, 128).astype(np.int8)).astype(np.float32) self._fulldata = np.ascontiguousarray(self._fulldata, dtype=np.float32) f.close() self.filename = filename if not self.qad_demod_file_loaded: self.noise_threshold = self.calc_noise_threshold( int(0.99 * self.num_samples), self.num_samples) else: self.filename = ""
def findQmFiles(self): trans_dir = QDir(':/translations') fileNames = trans_dir.entryList(['*.qm'], QDir.Files, QDir.Name) return [trans_dir.filePath(fn) for fn in fileNames]
def __loadDirectory(self): """ Private slot loading the directory and preparing the listing page. """ dir = QDir(self.url().toLocalFile()) dirItems = dir.entryInfoList( QDir.AllEntries | QDir.Hidden | QDir.NoDotAndDotDot, QDir.Name | QDir.DirsFirst) u = self.url() if not u.path().endswith("/"): u.setPath(u.path() + "/") baseUrl = self.url().toString() basePath = u.path() linkClasses = {} iconSize = QWebSettings.globalSettings().fontSize( QWebSettings.DefaultFontSize) parent = u.resolved(QUrl("..")) if parent.isParentOf(u): icon = UI.PixmapCache.getIcon("up.png") linkClasses["link_parent"] = \ self.__cssLinkClass(icon, iconSize).format("link_parent") parentStr = self.tr( """ <p><a class="link_parent" href="{0}">""" """Change to parent directory</a></p>""").format( parent.toString()) else: parentStr = "" row = \ """ <tr class="{0}">"""\ """<td class="name"><a class="{1}" href="{2}">{3}</a></td>"""\ """<td class="size">{4}</td>"""\ """<td class="modified">{5}</td>"""\ """</tr>\n""" table = self.tr(""" <tr>""" """<th align="left">Name</th>""" """<th>Size</th>""" """<th align="left">Last modified</th>""" """</tr>\n""") i = 0 for item in dirItems: name = item.fileName() if item.isDir() and not name.endswith("/"): name += "/" child = u.resolved(QUrl(name.replace(":", "%3A"))) if item.isFile(): size = item.size() unit = 0 while size: newSize = size // 1024 if newSize and unit < len(self.__units): size = newSize unit += 1 else: break sizeStr = self.tr("{0} {1}", "size unit")\ .format(size, self.__units[unit]) linkClass = "link_file" if linkClass not in linkClasses: icon = UI.PixmapCache.getIcon("fileMisc.png") linkClasses[linkClass] = \ self.__cssLinkClass(icon, iconSize).format(linkClass) else: sizeStr = "" linkClass = "link_dir" if linkClass not in linkClasses: icon = UI.PixmapCache.getIcon("dirClosed.png") linkClasses[linkClass] = \ self.__cssLinkClass(icon, iconSize).format(linkClass) table += row.format( i == 0 and "odd" or "even", linkClass, child.toString(), Utilities.html_encode(item.fileName()), sizeStr, item.lastModified().toString("yyyy-MM-dd hh:mm"), ) i = 1 - i content = dirListPage_html.format( Utilities.html_encode(baseUrl), "".join(linkClasses.values()), self.tr("Listing of {0}").format(basePath), parentStr, table) self.__content = QByteArray(content.encode("utf8")) self.__content.append(512 * b' ') self.open(QIODevice.ReadOnly | QIODevice.Unbuffered) self.setHeader(QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8") self.setHeader(QNetworkRequest.ContentLengthHeader, self.__content.size()) self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200) self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok") self.metaDataChanged.emit() self.downloadProgress.emit(self.__content.size(), self.__content.size()) self.readyRead.emit() self.finished.emit()
def show_file_dialog_for_dir(self, title: str) -> str: options = QFileDialog.Options() choose_dir = QFileDialog.getExistingDirectory( None, title, directory=QDir.homePath(), options=options) return choose_dir
def fillFileList(self): """ Generates the list of files for the file listbox. Most of the work is to deal with directories in that list. It only sees *.data and *.wav files.""" if not os.path.isdir(self.dirName): print("ERROR: directory %s doesn't exist" % self.dirName) return listOfDirs = QDir(self.dirName).entryList(['..'], filters=QDir.AllDirs | QDir.NoDotAndDotDot) self.listOfWavs = QDir(self.dirName).entryList(['*.wav']) self.listOfDataFiles = QDir(self.dirName).entryList(['*.wav.data']) # check if files have timestamps: haveTime = 0 for f in self.listOfWavs: infilestem = f[:-4] try: datestamp = infilestem.split("_")[-2:] # get [date, time] datestamp = '_'.join(datestamp) # make "date_time" # check both 4-digit and 2-digit codes (century that produces closest year to now is inferred) try: d = dt.datetime.strptime(datestamp, "%Y%m%d_%H%M%S") except ValueError: d = dt.datetime.strptime(datestamp, "%y%m%d_%H%M%S") haveTime += 1 except ValueError: print("Could not identify timestamp in", f) for f in self.listOfDataFiles: infilestem = f[:-9] try: datestamp = infilestem.split("_")[-2:] # get [date, time] datestamp = '_'.join(datestamp) # make "date_time" # check both 4-digit and 2-digit codes (century that produces closest year to now is inferred) try: d = dt.datetime.strptime(datestamp, "%Y%m%d_%H%M%S") except ValueError: d = dt.datetime.strptime(datestamp, "%y%m%d_%H%M%S") haveTime += 1 except ValueError: print("Could not identify timestamp in", f) # Currently, haveTime sums are not used anywhere... # check the selected dir and print info if len(listOfDirs) == 0: self.labelDirs.setText("Folder looks good (no subfolders)") elif len(listOfDirs) < 4: self.labelDirs.setText( "Warning: detected subfolders will not be processed: %s" % ", ".join(listOfDirs)) else: self.labelDirs.setText( "Warning: detected subfolders will not be processed: %s..." % ", ".join(listOfDirs[:3])) if len(self.listOfWavs) == 0: self.labelWavs.setText("ERROR: no WAV files detected!") noWav = True elif len(self.listOfWavs) < 4: self.labelWavs.setText( "Found <b>%d</b> WAV files: %s" % (len(self.listOfWavs), ", ".join(self.listOfWavs))) noWav = False else: self.labelWavs.setText( "Found <b>%d</b> WAV files: %s..." % (len(self.listOfWavs), ", ".join(self.listOfWavs[:3]))) noWav = False if len(self.listOfDataFiles) == 0: self.labelDatas.setText("No DATA files detected") noData = True elif len(self.listOfDataFiles) < 4: self.labelDatas.setText( "Found <b>%d</b> DATA files: %s" % (len(self.listOfDataFiles), ", ".join(self.listOfDataFiles))) noData = False else: self.labelDatas.setText("Found <b>%d</b> DATA files: %s..." % (len( self.listOfDataFiles), ", ".join(self.listOfDataFiles[:3]))) noData = False self.indirOk = not (noData and noWav) if self.indirOk: self.labelSum.setText( "Will split %d WAV files and %d DATA files into pieces of %d min %d s." % (len(self.listOfWavs), len(self.listOfDataFiles), self.cutLen // 60, self.cutLen % 60)) else: self.labelSum.setText("Please select files to split")
def slot_output(self): dir_tmp = QFileDialog.getExistingDirectory(self, "select a existing directory", '../../data/') self.lineEdit_output.setText(dir_tmp) QDir.setCurrent(dir_tmp)
def create_project_structure(base_dir): base_qdir = QDir(base_dir) base_qdir.mkpath('normalizado/heStain') base_qdir.mkpath('train/print') base_qdir.mkpath('train/mitosis') base_qdir.mkpath('train/candidates') base_qdir.mkpath('test/mitosis') base_qdir.mkdir('anotations')
def open(self): if self.maybeSave(): fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if fileName: self.scribbleArea.openImage(fileName)
def install_translations(cls, config_lang): """ Get current system language and load translation We need more than one translator: one for the individual appplication strings and some other for the standard qt message texts. :param config_lang: two-character language string, or "System" """ # remove possible existing translators if cls.cfg.translator_qthelp is not None: cls.cfg._parent.removeTranslator(cls.cfg.translator_qthelp) cls.cfg.translator_qthelp = None if cls.cfg.translator_qtmm is not None: cls.cfg._parent.removeTranslator(cls.cfg.translator_qtmm) cls.cfg.translator_qtmm = None if cls.cfg.translator_qt is not None: cls.cfg._parent.removeTranslator(cls.cfg.translator_qt) cls.cfg.translator_qt = None if cls.cfg.translator_app is not None: cls.cfg._parent.removeTranslator(cls.cfg.translator_app) cls.cfg.translator_app = None # decide, if we load the system language or specified language from config if config_lang == "System": # search if we have a language file according to system locale found = False for filePath in QDir(cls.cfg._app_locale_path).entryList(): fileName = os.path.basename(filePath) fileMatch = re.match(cls.cfg.applangprefix + "_([a-z]{2,}).qm", fileName) if fileMatch: if fileMatch.group(1) == cls.cfg._syslocale: found = True # if we don't have a language file, fall back to "en" if not found: cls.cfg.logger.debug( "No language file for system locale found. Falling back to English." ) use_local = QtCore.QLocale("en") else: cls.cfg.logger.debug("Language file for system locale found.") use_local = QtCore.QLocale().system() qm_qt = "qt_%s" % use_local.name()[:2] qm_app = cls.cfg.applangprefix + '_%s' % use_local.name()[:2] cls.cfg.logger.debug("Installing language: " + use_local.name()[:2]) else: use_local = QtCore.QLocale(config_lang) qm_qt = 'qt_%s.qm' % config_lang qm_app = cls.cfg.applangprefix + '_%s.qm' % config_lang cls.cfg.logger.debug("Installing language: " + config_lang) cls.cfg.logger.debug("Load Qt standard translation: " + qm_qt + " from: " + cls.cfg._qt_locale_path) cls.cfg.logger.debug("Load application translation: " + qm_app + " from: " + cls.cfg._app_locale_path) # create translators # translator_qt.load(use_local, "qtquick1", "_", qt_locale_path, ".qm") # translator_qt.load(use_local, "qtmultimedia", "_", qt_locale_path, ".qm") # translator_qt.load(use_local, "qtxmlpatterns", "_", qt_locale_path, ".qm") # qt base cls.cfg.translator_qt = QtCore.QTranslator(cls.cfg._parent) if cls.cfg.translator_qt.load(use_local, "qtbase", "_", cls.cfg._qt_locale_path, ".qm"): cls.cfg.logger.debug("Qtbase translations successfully loaded.") # qt help cls.cfg.translator_qthelp = QtCore.QTranslator(cls.cfg._parent) if cls.cfg.translator_qthelp.load(use_local, "qt_help", "_", cls.cfg._qt_locale_path, ".qm"): cls.cfg.logger.debug("Qthelp translations successfully loaded.") # qt multimedia cls.cfg.translator_qtmm = QtCore.QTranslator(cls.cfg._parent) if cls.cfg.translator_qtmm.load(use_local, "qtmultimedia", "_", cls.cfg._qt_locale_path, ".qm"): cls.cfg.logger.debug( "Qtmultimedia translations successfully loaded.") # application cls.cfg.translator_app = QtCore.QTranslator(cls.cfg._parent) if cls.cfg.translator_app.load(use_local, "opsipackagebuilder", "_", cls.cfg._app_locale_path, ".qm"): cls.cfg.logger.debug( "Application translations successfully loaded.") # install translators to app if not cls.cfg.translator_qthelp.isEmpty(): cls.cfg._parent.installTranslator(cls.cfg.translator_qthelp) if not cls.cfg.translator_qtmm.isEmpty(): cls.cfg._parent.installTranslator(cls.cfg.translator_qtmm) if not cls.cfg.translator_qt.isEmpty(): cls.cfg._parent.installTranslator(cls.cfg.translator_qt) if not cls.cfg.translator_app.isEmpty(): cls.cfg._parent.installTranslator(cls.cfg.translator_app) # save current language cls.cfg._current_lang = use_local.name()[:2]
def __init__(self, jeName="JPEG Export", jeVersion="testing", parent=None): super(JEMainWindow, self).__init__( os.path.join(os.path.dirname(__file__), 'resources', 'jemainwindow.ui'), parent) self.__notifier = None # another instance already exist, exit if JEMainWindow.__IS_OPENED: self.close() return self.__accepted = False self.__timerPreview = 0 # timer used for preview update self.__timerResize = 0 # timer used for resize update self.__tmpDoc = None # internal document used for export (not added to view) self.__tmpDocTgtNode = None self.__tmpDocPreview = None # document used for preview (added to view) self.__tmpDocPreviewFileNode = None self.__tmpDocPreviewSrcNode = None self.__jeName = jeName self.__jeVersion = jeVersion self.__viewScrollbarH = None self.__viewScrollbarV = None self.__positionFull = None self.__positionCrop = None self.__doc = Krita.instance().activeDocument() self.__boundsSource = None self.__sizeTarget = None if self.__doc is None: # no document opened: cancel plugin QMessageBox.warning( QWidget(), f"{jeName}", i18n( "There's no active document: <i>JPEG Export</i> plugin only works with opened documents" )) self.close() return JEMainWindow.__IS_OPENED = True basename, ext = os.path.splitext( os.path.basename(self.__doc.fileName())) self.__tmpExportPreviewFile = os.path.join( QDir.tempPath(), f'{basename} (JPEG Export Preview).jpeg') self.__tmpExportFile = os.path.join( QDir.tempPath(), f'jpegexport-{QUuid.createUuid().toString(QUuid.Id128)}.jpeg') self.__docFileName = self.__doc.fileName() self.__notifier = Krita.instance().notifier() self.__notifier.imageClosed.connect(self.__imageClosed) self.setModal(False) self.setWindowTitle(i18n(f'{jeName} v{jeVersion}')) self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint | Qt.WindowStaysOnTopHint) self.__initialiseUi() self.__initialiseDoc() self.show()
CMDLINE_LANGUAGE = None CURRENT_LANGUAGE = 'en_US' SUPPORTED_LANGUAGES = ['en_US'] try: from language import openshot_lang language_path = ":/locale/" except ImportError: language_path = os.path.join(PATH, 'language') print("Compiled translation resources missing!") print("Loading translations from: {}".format(language_path)) # Compile language list from :/locale resource try: from PyQt5.QtCore import QDir langdir = QDir(language_path) langs = langdir.entryList(['OpenShot.*.qm'], QDir.NoDotAndDotDot | QDir.Files, sort=QDir.Name) for trpath in langs: SUPPORTED_LANGUAGES.append(trpath.split('.')[1]) except ImportError: # Fail gracefully if we're running without PyQt5 (e.g. CI tasks) pass SETUP = { "name": NAME, "version": VERSION, "author":
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self._version = __version__ self.setWindowIcon(QIcon(":/logo.png")) self.setWindowTitle("Tasmota Device Manager {}".format(self._version)) self.unknown = [] self.env = TasmotaEnvironment() self.device = None self.topics = [] self.mqtt_queue = [] self.fulltopic_queue = [] # ensure TDM directory exists in the user directory if not os.path.isdir("{}/TDM".format(QDir.homePath())): os.mkdir("{}/TDM".format(QDir.homePath())) self.settings = QSettings("{}/TDM/tdm.cfg".format(QDir.homePath()), QSettings.IniFormat) self.devices = QSettings("{}/TDM/devices.cfg".format(QDir.homePath()), QSettings.IniFormat) self.setMinimumSize(QSize(1000, 600)) # configure logging logging.basicConfig(filename="{}/TDM/tdm.log".format(QDir.homePath()), level=self.settings.value("loglevel", "INFO"), datefmt="%Y-%m-%d %H:%M:%S", format='%(asctime)s [%(levelname)s] %(message)s') logging.info("### TDM START ###") # load devices from the devices file, create TasmotaDevices and add the to the envvironment for mac in self.devices.childGroups(): self.devices.beginGroup(mac) device = TasmotaDevice(self.devices.value("topic"), self.devices.value("full_topic"), self.devices.value("friendly_name")) device.debug = self.devices.value("debug", False, bool) device.p['Mac'] = mac.replace("-", ":") device.env = self.env self.env.devices.append(device) # load device command history self.devices.beginGroup("history") for k in self.devices.childKeys(): device.history.append(self.devices.value(k)) self.devices.endGroup() self.devices.endGroup() self.device_model = TasmotaDevicesModel(self.env) self.setup_mqtt() self.setup_main_layout() self.add_devices_tab() self.build_mainmenu() # self.build_toolbars() self.setStatusBar(QStatusBar()) pbSubs = QPushButton("Show subscriptions") pbSubs.setFlat(True) pbSubs.clicked.connect(self.showSubs) self.statusBar().addPermanentWidget(pbSubs) self.queue_timer = QTimer() self.queue_timer.timeout.connect(self.mqtt_publish_queue) self.queue_timer.start(250) self.auto_timer = QTimer() self.auto_timer.timeout.connect(self.auto_telemetry) self.load_window_state() if self.settings.value("connect_on_startup", False, bool): self.actToggleConnect.trigger() self.tele_docks = {} self.consoles = []
def cut(self, source: str, output: str, frametime: str, duration: str) -> bool: args = '-i "%s" -ss %s -t %s -vcodec copy -acodec copy -y "%s"'\ % (source, frametime, duration, QDir.fromNativeSeparators(output)) return self.cmdExec(self.backend, args)