def __init__(self, editor, window): super(ReTextFakeVimHandler, self).__init__(window) self.__window = window self.__editor = editor self.__blockSelection = BlockSelection(self.__editor) self.__blockSelection.hide() self.__searchSelections = [] fm = self.__editor.fontMetrics() self.__cursorWidth = fm.averageCharWidth() self.__oldCursorWidth = self.__editor.cursorWidth() self.__editor.setCursorWidth(self.__cursorWidth) self.__handler = FakeVimHandler(self.__editor, self) self.__proxy = Proxy(self.__window, self.__editor, self) self.__handler.installEventFilter() self.__handler.setupWidget() self.__handler.handleCommand( 'source {home}/.vimrc'.format(home = QDir.homePath())) self.__saveAction = None self.__quitAction = None # Update selections if cursor changes because of current line can be highlighted. self.__editor.cursorPositionChanged.connect(self.__updateSelections)
def getHomeDir(): """ Function to get a users home directory @return home directory (string) """ return unicode(QDir.homePath())
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 run_chordii(self, input_file=None, output_file=None, preview=False): """ Run Chordii to produce output. :param input_file: The name of the ChordPro file to compile. If None, all chordii files in the project will be compiled. :type input_file: str :param output_file: The filename of the resulting pdf. If None, a temp file will be created. :type output_file: str :param preview: Whether to compile a single song as a preview, or the whole project. :type preview: bool """ chordii_command = which("chordii") if chordii_command is None: chordii_command = which("chordii430") if chordii_command is None: ret = QMessageBox.critical(self, self.tr(self.app_name + " - Chordii problem"), self.tr("Couldn't find a chordii executable in the PATH. \ Please specify chordii's location to continue."), QMessageBox.Open | QMessageBox.Cancel, QMessageBox.Open) if ret == QMessageBox.Open: chordii_command = QFileDialog.getOpenFileName(self, self.tr("Specify the chordii executable"), QDir.homePath())[0] command = [chordii_command, "-i", "-L", "-p", "1"] if not preview else [chordii_command] if not output_file: out_dir = os.path.join(os.path.dirname(self.project_file), "output") output_file = os.path.join(out_dir, self.songbook.name) if not os.path.exists(out_dir): os.makedirs(out_dir) if not input_file: for i in range(self.ui.fileWidget.rowCount()): command.append(self.ui.fileWidget.item(i, 0).data(Qt.UserRole)) else: command.append(input_file) command.append("-o") command.append(output_file + '.ps') print('{}'.format(' '.join(map(str, command)))) try: response = subprocess.check_output(command, stderr=subprocess.STDOUT).decode() if not preview: if response: msg_box = WarningMessageBox() msg_box.setWindowTitle(self.tr(self.app_name + " - Chordii warning")) msg_box.setText(self.tr("Chordii exited with warnings.")) msg_box.setDetailedText(response) msg_box.setIcon(QMessageBox.Warning) msg_box.exec_() else: QMessageBox.information(self, self.tr(self.app_name + " - Chordii was successful"), self.tr("Chordii compiled the songbook without warnings!")) except subprocess.CalledProcessError as e: if not preview: message = self.tr("Chordii crashed while compiling.") if e.stderr: message += '<br' + self.tr("Chordii output:") + '<br><pre>' + e.stderr + '</pre>' else: message += '<br>' + self.tr("Tip: This could be due to an incorrect chord definition.") QMessageBox.critical(self, self.tr(self.app_name + " - Chordii problem"), message) return ps2pdf(output_file)
def openGame(self): path = QFileDialog.getOpenFileName(self.parent(), 'Open PGN', QDir.homePath(), filter='*.pgn') if path[0]: self.newGame(path[0]) self.fileHandle = path[0]
def openFile(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath()) if fileName != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(fileName))) self.playButton.setEnabled(True)
def on_add_torrent_browse_file(self): filenames = QFileDialog.getOpenFileNames(self, "Please select the .torrent file", QDir.homePath(), "Torrent files (*.torrent)") if len(filenames[0]) > 0: [self.pending_uri_requests.append(u"file:%s" % filename) for filename in filenames[0]] self.process_uri_request()
def saveGameAs(self): path = QFileDialog.getSaveFileName(self.parent(), 'Save PGN', QDir.homePath(), filter='*.pgn\n*.*') if path[0]: self.writeGame(path[0]) self.fileHandle = path[0]
def on_add_mdblob_browse_file(self): filenames = QFileDialog.getOpenFileNames(self, "Please select the .mdblob file", QDir.homePath(), "Tribler metadata files (*.mdblob)") if len(filenames[0]) > 0: for filename in filenames[0]: self.pending_uri_requests.append(u"file:%s" % filename) self.process_uri_request()
def screenShot(self): self.rootObject().hideControls() name = "%s-%s" % (self.title(), time.strftime("%y-%m-%d-%H-%M-%S", time.localtime())) path = QDir.homePath() +"/%s.jpg" % name p = QPixmap.fromImage(self.grabWindow()) p.save(path, "jpg") notify(u"截图成功", u"文件已保存到%s" % path)
def on_file_browse(self): settings = QSettings() # look for directory path = QgsProject.instance().homePath() if path == '': path = settings.value("mask/file_dir", '') if path == '': path = QDir.homePath() drivers = QgsVectorFileWriter.ogrDriverList() filterList = [] filterMap = {} for ln, n in drivers.items(): # grrr, driverMetadata is not really consistent if n == "ESRI Shapefile": ext = "shp" glob = "*.shp" else: md = QgsVectorFileWriter.MetaData() if QgsVectorFileWriter.driverMetadata(n, md): ext = md.ext glob = md.glob else: continue fn = "%s (%s)" % (ln, glob) filterMap[fn] = (n, ext, glob) filterList += [fn] fileFilters = ';;'.join(filterList) fd = QFileDialog(None, self.tr("Select a filename to save the mask layer to"), path, fileFilters) save_format_name = self.parameters.file_format self.save_format = None for k, v in filterMap.items(): if v[0] == save_format_name: self.save_format = v fd.selectNameFilter(k) break def on_filter_selected(ff): self.save_format = filterMap[ff] fd.filterSelected.connect(on_filter_selected) fd.setAcceptMode(QFileDialog.AcceptSave) r = fd.exec_() if r == 1: fn = fd.selectedFiles()[0] driver, ext, glob = self.save_format if not fn.endswith("." + ext): fn += "." + ext self.ui.filePath.setText(fn) self.ui.formatLbl.setText(self.save_format[0]) self.parameters.file_format = self.save_format[0] self.parameters.file_path = fn
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 write_app_settings(self): """Write app settings on exit.""" settings = QSettings(QDir.homePath() + '/.videomorph/config.ini', QSettings.IniFormat) settings.setValue("pos", self.pos()) settings.setValue("size", self.size()) settings.setValue("profile", self.cb_profiles.currentIndex()) settings.setValue("preset", self.cb_presets.currentIndex()) settings.setValue("output_dir", self.le_output.text()) settings.setValue('conversion_lib', self.conversion_lib)
def slotExport(self): name = self.scheme.currentText() filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files")) caption = app.caption(_("dialog title", "Export {name}").format(name=name)) path = os.path.join(QDir.homePath(), name+'.xml') filename = QFileDialog.getSaveFileName(self, caption, path, filetypes)[0] if filename: if os.path.splitext(filename)[1] != '.xml': filename += '.xml' self.parent().export(name, filename)
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 launch_save_as_dialog(self): working_directory = QDir.homePath() fileName, selectedFilter = QFileDialog.getSaveFileName( self, _("Save as"), working_directory, _("Databases (*.sqlite *.plume);;All files (*)"), _(".sqlite")) if fileName is None: return cfg.core.project.save_as(fileName, selectedFilter)
def output_directory(self): """Choose output directory.""" options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly directory = QFileDialog.getExistingDirectory( self, self.tr('Choose Output Directory'), QDir.homePath(), options=options) if directory: self.le_output.setText(directory)
def read_path_and_show_one_image(self): hyperlpr_dir_info_filepath = QDir.homePath() + "/hyperlpr_dir_file" if os.path.exists(hyperlpr_dir_info_filepath): with open(hyperlpr_dir_info_filepath, 'r') as f: self.hyperlpr_dir_path = f.read() if len(self.hyperlpr_dir_path) > 0: self.reset_info_gui() if len(self.image_filename_list) > 0: self.recognize_and_show_one_image(self.image_filename_list[0], 0)
def new_file(self): if not self.ok_to_continue(): return self.file_name = QFileDialog.getSaveFileName(self, self.tr("New file"), QDir.homePath(), self.tr(CHORDPRO_FILTER)) if not self.file_name[1]: return self.save_file() if self.ui.textEdit.isReadOnly(): self.ui.textEdit.setReadOnly(False) self.ui.textEdit.setText("{t:}\n{st:}") self.ui.textEdit.setFocus() self.statusBar().showMessage('New file', 5000)
def on_add_torrent_browse_dir(self): chosen_dir = QFileDialog.getExistingDirectory(self, "Please select the directory containing the .torrent files", QDir.homePath(), QFileDialog.ShowDirsOnly) if len(chosen_dir) != 0: self.selected_torrent_files = [torrent_file for torrent_file in glob.glob(chosen_dir + "/*.torrent")] self.dialog = ConfirmationDialog(self, "Add torrents from directory", "Are you sure you want to add %d torrents to Tribler?" % len(self.selected_torrent_files), [('ADD', BUTTON_TYPE_NORMAL), ('CANCEL', BUTTON_TYPE_CONFIRM)]) self.dialog.button_clicked.connect(self.on_confirm_add_directory_dialog) self.dialog.show()
def _loadHistogramsButtonPressed(self): fname, _filter = QFileDialog.getOpenFileName( self, caption='Open Histogram File', filter="HDF5 Files (*.h5 *.hdf5);;All Files (*)", directory=QDir.homePath()) if len(fname) > 0: # not cancelled #FIXME where do we get the real h5 path from??? h5path = 'volume/data' # no try-catch because we want to propagate errors to the GUI histos = vigra.impex.readHDF5(str(fname), h5path) self.topLevelOperatorView.setPrecomputedHistograms(histos) logger.debug("Loaded histograms from file '{}' (shape: {})".format( fname, histos.shape))
def close_project(self): self.save_project() self.close_all_files() self.compare_frame_controller.proto_analyzer.message_types.clear() self.compare_frame_controller.active_message_type.clear() self.compare_frame_controller.updateUI() self.project_manager.participants.clear() self.participant_legend_model.update() self.filemodel.setRootPath(QDir.homePath()) self.ui.fileTree.setRootIndex(self.file_proxy_model.mapFromSource(self.filemodel.index(QDir.homePath()))) self.hide_file_tree() self.project_manager.project_path = "" self.project_manager.project_file = None
def __init__(self, vcs, parent=None): """ Constructor @param vcs reference to the version control object @param parent parent widget (QWidget) """ super(HgNewProjectOptionsDialog, self).__init__(parent) self.setupUi(self) self.projectDirButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.vcsUrlButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.vcsDirectoryCompleter = E5DirCompleter(self.vcsUrlEdit) self.vcsProjectDirCompleter = E5DirCompleter(self.vcsProjectDirEdit) self.protocolCombo.addItems(ConfigHgProtocols) hd = Utilities.toNativeSeparators(QDir.homePath()) hd = os.path.join(hd, 'hgroot') self.vcsUrlEdit.setText(hd) self.vcs = vcs self.localPath = hd self.networkPath = "localhost/" self.localProtocol = True ipath = Preferences.getMultiProject("Workspace") or \ Utilities.getHomeDir() self.__initPaths = [ Utilities.fromNativeSeparators(ipath), Utilities.fromNativeSeparators(ipath) + "/", ] self.vcsProjectDirEdit.setText( Utilities.toNativeSeparators(self.__initPaths[0])) self.lfNoteLabel.setVisible(self.vcs.isExtensionActive("largefiles")) self.largeCheckBox.setVisible(self.vcs.isExtensionActive("largefiles")) self.resize(self.width(), self.minimumSizeHint().height()) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def on_add_torrents_browse_dir(self): chosen_dir = QFileDialog.getExistingDirectory(self, "Please select the directory containing the .torrent files", QDir.homePath(), QFileDialog.ShowDirsOnly) if not chosen_dir: return self.chosen_dir = chosen_dir self.dialog = ConfirmationDialog(self, "Add torrents from directory", "Add all torrent files from the following directory " "to your Tribler channel:\n\n%s" % chosen_dir, [('ADD', BUTTON_TYPE_NORMAL), ('CANCEL', BUTTON_TYPE_CONFIRM)], checkbox_text="Include subdirectories (recursive mode)") self.dialog.button_clicked.connect(self.on_confirm_add_directory_dialog) self.dialog.show()
def read_app_settings(self): """Read the app settings.""" settings = QSettings(QDir.homePath() + '/.videomorph/config.ini', QSettings.IniFormat) pos = settings.value("pos", QPoint(600, 200), type=QPoint) size = settings.value("size", QSize(1096, 510), type=QSize) self.resize(size) self.move(pos) if 'profile' and 'preset' in settings.allKeys(): prof = settings.value('profile') pres = settings.value('preset') self.cb_profiles.setCurrentIndex(int(prof)) self.cb_presets.setCurrentIndex(int(pres)) if 'output_dir' in settings.allKeys(): self.le_output.setText(str(settings.value('output_dir'))) if 'conversion_lib' in settings.allKeys(): self.conversion_lib = settings.value('conversion_lib')
def launch_open_dialog(self): working_directory = QDir.homePath() fileName, selectedFilter = QFileDialog.getOpenFileName( self, _("Open"), working_directory, _("Databases (*.sqlite *.plume);;All files (*)"), _(".sqlite")) if fileName is None: return if cfg.core.project.is_open() == True: if self.launch_close_dialog() == QMessageBox.Cancel: return cfg.core.project.open(fileName) self.setWindowTitle("Plume Creator - " + fileName)
def close_all(self): self.filemodel.setRootPath(QDir.homePath()) self.ui.fileTree.setRootIndex(self.file_proxy_model.mapFromSource(self.filemodel.index(QDir.homePath()))) self.project_manager.saveProject() self.signal_tab_controller.close_all() self.compare_frame_controller.reset() self.generator_tab_controller.table_model.protocol.clear() self.generator_tab_controller.refresh_tree() self.generator_tab_controller.refresh_table() self.generator_tab_controller.refresh_label_list() self.project_manager.project_path = "" self.project_manager.project_file = None self.signal_tab_controller.signal_undo_stack.clear() self.compare_frame_controller.protocol_undo_stack.clear() self.generator_tab_controller.generator_undo_stack.clear()
def currentDirectory(self): """Returns the current directory of the current document. If the document has no filename yet, returns the configured default directory, or the user's home directory. Is that is not set as well, returns the current directory of the application. """ import resultfiles curdir = (resultfiles.results(self.currentDocument()).currentDirectory() or app.basedir() or QDir.homePath()) if curdir: return curdir try: return os.getcwdu() except AttributeError: return os.getcwd()
def getConfigDir(): """ Module function to get the name of the directory storing the config data. @return directory name of the config dir (string) """ if configDir is not None and os.path.exists(configDir): hp = configDir else: if isWindowsPlatform(): cdn = "_eric6" else: cdn = ".eric6" hp = QDir.homePath() dn = QDir(hp) dn.mkdir(cdn) hp += "/" + cdn return QDir.toNativeSeparators(hp)
def getConfigDir(): """ Global function to get the name of the directory storing the config data. @return directory name of the config dir (string) """ if sys.platform.startswith("win"): cdn = "_eric6" else: cdn = ".eric6" hp = QDir.homePath() dn = QDir(hp) dn.mkdir(cdn) hp += "/" + cdn try: return QDir.toNativeSeparators(hp) except AttributeError: return QDir.toNativeSeparators(hp)
def settings(): s = QSettings(posixpath.join(QDir.homePath(), ".editor.py", "editor.ini"), QSettings.IniFormat) s.setIniCodec("UTF-8") return s
self.textWritten.emit(str(text)) def flush(self): pass # Main if __name__ == '__main__': app = QApplication(sys.argv) app.setAttribute(Qt.AA_EnableHighDpiScaling) # qInstallMessageHandler(qt_message_handler) # Set current directory to home path QDir.setCurrent(QDir.homePath()) print(PyQt5.__file__) # paths = [x for x in dir(QLibraryInfo) if x.endswith('Path')] # pprint({x: QLibraryInfo.location(getattr(QLibraryInfo, x)) for x in paths}) # WebEngine settings # QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.PluginsEnabled, True) # QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.JavascriptCanOpenWindows, True) # QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.JavascriptEnabled, True) # QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls,True) # QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.AllowRunningInsecureContent, True) window = MainWindow() # Never executed (exec already in main)...
def parse_message(self, topic, msg): parse_statuses = ["STATUS{}".format(s) for s in [1, 2, 3, 4, 5, 6, 7]] if self.prefix in ("stat", "tele"): try: payload = loads(msg) if self.reply == 'STATUS': payload = payload['Status'] for k, v in payload.items(): if k == "FriendlyName": for fnk, fnv in enumerate(v, start=1): self.update_property("FriendlyName{}".format(fnk), fnv) else: self.update_property(k, v) elif self.reply in parse_statuses: payload = payload[list(payload.keys())[0]] for k, v in payload.items(): self.update_property(k, v) elif self.reply in ('STATE', 'STATUS11'): if self.reply == 'STATUS11': payload = payload['StatusSTS'] for k, v in payload.items(): if isinstance(v, dict): for kk, vv in v.items(): self.update_property(kk, vv) else: self.update_property(k, v) elif self.reply in ('SENSOR', 'STATUS8', 'STATUS10'): if self.reply in ('STATUS8', 'STATUS10'): payload = payload['StatusSNS'] self.t = payload self.update_telemetry.emit() elif self.reply == 'RESULT': keys = list(payload.keys()) fk = keys[0] if fk.startswith("Modules"): for k, v in payload.items(): if isinstance(v, list): for mdl in v: self.modules.update(parse_payload(mdl)) elif isinstance(v, dict): self.modules.update(v) self.module_changed(self) elif fk == 'NAME': self.p['Template'] = payload if self.module_changed: self.module_changed(self) elif fk.startswith("GPIOs"): for k, v in payload.items(): if isinstance(v, list): for gp in v: self.gpios.update(parse_payload(gp)) elif isinstance(v, dict): self.gpios.update(v) elif fk.startswith("GPIO"): for gp, gp_val in payload.items(): if not gp == "GPIO": if isinstance(gp_val, str): gp_id = gp_val.split(" (")[0] self.gpio[gp] = gp_id elif isinstance(gp_val, dict): self.gpio[gp] = list(gp_val.keys())[0] else: for k, v in payload.items(): self.update_property(k, v) except JSONDecodeError as e: 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))
def set_Options_to_default(self): global CONDA_MD5_IN tab_index = self.tab_install.currentIndex() if tab_index == 0: # miniconda tab # set radioButtons to default self.rB_no_conda.setChecked(True) self.rB_yes_update_conda.setChecked(True) self.rB_no_checksum.setChecked(True) self.rB_CONDA_URL.setChecked(True) # set MD5 to its default value self.lineEdit_SHA256.setText(CONDA_MD5_IN) elif tab_index == 1: # prerequisites tab # set radioButtons to default self.rB_yes_update_env_prerequis.setChecked(True) ENV_NAME_PREFIX = 'openmc-py' self.lineEdit_Env_Name_prerequis.setText(ENV_NAME_PREFIX) self.rB_py37_prerequis.toggled.connect(lambda: self.PyVer_btnstate( self.rB_py37_prerequis, ENV_NAME_PREFIX, self. lineEdit_Env_Name_prerequis)) self.rB_py38_prerequis.toggled.connect(lambda: self.PyVer_btnstate( self.rB_py38_prerequis, ENV_NAME_PREFIX, self. lineEdit_Env_Name_prerequis)) self.rB_yes_all_prerequis.setChecked(True) self.rB_py37_prerequis.setChecked(True) self.rB_no_MPI_prerequis.setChecked(True) self.rB_no_compiler.setChecked(True) self.rB_no_cmake.setChecked(True) self.tools_conda_lE.setText(None) self.pB_extra_tools.setDisabled(True) # The toggled() signal of both the buttons is connected to update_compiler() function. # Use of lambda allows the source of signal to be passed to the function as an argument. self.rB_yes_compiler.toggled.connect( self.pB_Start_prerequis.setDisabled) self.rB_yes_cmake.toggled.connect( self.pB_Start_prerequis.setDisabled) self.rB_yes_compiler.toggled.connect( lambda: self.update_compiler(self.rB_yes_compiler, gcc)) self.rB_yes_cmake.toggled.connect( lambda: self.update_compiler(self.rB_yes_cmake, cmake)) # will activate run button if text changed self.tools_conda_lE.textChanged[str].connect( lambda: self.pB_extra_tools.setDisabled(self.tools_conda_lE. text() == "")) elif tab_index == 2: # openmc tab # set radioButtons to default self.rB_yes_in_conda.setChecked(True) self.rB_no_update_env.setChecked(True) self.rB_no_prerequis.setChecked(True) self.rB_no_Editable.setChecked(True) self.rB_no_MPI.setChecked(True) self.rB_no_del_src.setChecked(True) self.uncheck_rB() # Env. Name ENV_NAME_PREFIX = 'openmc-py' self.rB_py37.setChecked(True) self.lineEdit_Env_Name.setText(ENV_NAME_PREFIX + PYTHON_VERSION) self.rB_py37.toggled.connect(lambda: self.PyVer_btnstate( self.rB_py37, ENV_NAME_PREFIX, self.lineEdit_Env_Name)) self.rB_py38.toggled.connect(lambda: self.PyVer_btnstate( self.rB_py38, ENV_NAME_PREFIX, self.lineEdit_Env_Name)) # Working Directory and Install Prefix self.WORK_DIR.setText(QDir.homePath() + "/Py-OpenMC-" + str(datetime.date.today().year)) self.INSTALL_PREFIX_QLnE.setText( self.WORK_DIR.text() + "/opt/openmc/" + datetime.date.today().strftime("%m-%Y") ) # Where to install (if INSTALL_IN_CONDA and INSTALL_EDITABLE are disabled) self.INSTALL_PREFIX_QLnE.setDisabled(True) self.rB_yes_in_conda.toggled.connect( self.INSTALL_PREFIX_QLnE.setDisabled) elif tab_index == 3: self.WORKDIR_XS.setText(QDir.homePath() + "/Py-OpenMC-" + str(datetime.date.today().year)) self.Env_Name_XS.setText("openmc-py3.7")
def accept(self): filename, _ = QFileDialog.getSaveFileName(self, self.tr("Choose a file name to save current view as"), QDir.homePath(), "PNG files (*.png)") if not filename: return self.setEnabled(False) image = self.renderImage() image.save(filename) self.wnd.ui.statusbar.showMessage(self.tr("Image has been saved to file."), 5000) super().accept()
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
if not os.path.exists(TMP): qWarning("TMP does not exist") TMP = "/" del envTMP # ------------------------------------------------------------------------------------------------------------ # Set HOME envHOME = os.getenv("HOME") if envHOME is None: if LINUX or MACOS: qWarning("HOME variable not set") HOME = QDir.toNativeSeparators(QDir.homePath()) else: HOME = envHOME if not os.path.exists(HOME): qWarning("HOME does not exist") HOME = TMP del envHOME # ------------------------------------------------------------------------------------------------------------ # Set PATH envPATH = os.getenv("PATH") if envPATH is None:
def __init__(self): super().__init__() # Get the keys for the autocompletion. self.genreKeysList = [] self.characterKeysList = [] self.ratingKeysList = {} self.formatKeysList = [] self.otherKeysList = [] self.authorRoleList = [] for g in self.acbfGenreList.values(): self.genreKeysList.append(g) for r in self.acbfAuthorRolesList.values(): self.authorRoleList.append(r) mainP = Path(os.path.abspath(__file__)).parent self.get_auto_completion_keys(mainP) extraKeyP = Path(QDir.homePath()) / Application.readSetting(self.configGroup, "extraKeysLocation", str()) self.get_auto_completion_keys(extraKeyP) # Setup the dialog. self.setLayout(QVBoxLayout()) mainWidget = QTabWidget() self.layout().addWidget(mainWidget) self.setWindowTitle(i18n("Comic Metadata")) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.layout().addWidget(buttons) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) # Title, concept, summary, genre, characters, format, rating, language, series, other keywords metadataPage = QWidget() mformLayout = QFormLayout() metadataPage.setLayout(mformLayout) self.lnTitle = QLineEdit() self.lnTitle.setToolTip(i18n("The proper title of the comic.")) self.teSummary = QPlainTextEdit() self.teSummary.setToolTip(i18n("What will you tell others to entice them to read your comic?")) self.lnGenre = QLineEdit() genreCompletion = multi_entry_completer() genreCompletion.setModel(QStringListModel(self.genreKeysList)) self.lnGenre.setCompleter(genreCompletion) genreCompletion.setCaseSensitivity(False) self.lnGenre.setToolTip(i18n("The genre of the work. Prefilled values are from the ACBF, but you can fill in your own. Separate genres with commas. Try to limit the amount to about two or three")) self.lnCharacters = QLineEdit() characterCompletion = multi_entry_completer() characterCompletion.setModel(QStringListModel(self.characterKeysList)) characterCompletion.setCaseSensitivity(False) characterCompletion.setFilterMode(Qt.MatchContains) # So that if there is a list of names with last names, people can type in a last name. self.lnCharacters.setCompleter(characterCompletion) self.lnCharacters.setToolTip(i18n("The names of the characters that this comic revolves around. Comma-separated.")) self.lnFormat = QLineEdit() formatCompletion = multi_entry_completer() formatCompletion.setModel(QStringListModel(self.formatKeysList)) formatCompletion.setCaseSensitivity(False) self.lnFormat.setCompleter(formatCompletion) ratingLayout = QHBoxLayout() self.cmbRatingSystem = QComboBox() self.cmbRatingSystem.addItems(self.ratingKeysList.keys()) self.cmbRatingSystem.setEditable(True) self.cmbRating = QComboBox() self.cmbRating.setEditable(True) self.cmbRatingSystem.currentIndexChanged.connect(self.slot_refill_ratings) ratingLayout.addWidget(self.cmbRatingSystem) ratingLayout.addWidget(self.cmbRating) self.lnSeriesName = QLineEdit() self.lnSeriesName.setToolTip(i18n("If this is part of a series, enter the name of the series and the number.")) self.spnSeriesNumber = QSpinBox() self.spnSeriesNumber.setPrefix("No. ") self.spnSeriesVol = QSpinBox() self.spnSeriesVol.setPrefix("Vol. ") seriesLayout = QHBoxLayout() seriesLayout.addWidget(self.lnSeriesName) seriesLayout.addWidget(self.spnSeriesVol) seriesLayout.addWidget(self.spnSeriesNumber) otherCompletion = multi_entry_completer() otherCompletion.setModel(QStringListModel(self.otherKeysList)) otherCompletion.setCaseSensitivity(False) otherCompletion.setFilterMode(Qt.MatchContains) self.lnOtherKeywords = QLineEdit() self.lnOtherKeywords.setCompleter(otherCompletion) self.lnOtherKeywords.setToolTip(i18n("Other keywords that don't fit in the previously mentioned sets. As always, comma-separated")) self.cmbLanguage = language_combo_box() self.cmbCountry = country_combo_box() self.cmbLanguage.currentIndexChanged.connect(self.slot_update_countries) self.cmbReadingMode = QComboBox() self.cmbReadingMode.addItem(i18n("Left to Right")) self.cmbReadingMode.addItem(i18n("Right to Left")) self.cmbCoverPage = QComboBox() self.cmbCoverPage.setToolTip(i18n("Which page is the cover page? This will be empty if there's no pages.")) mformLayout.addRow(i18n("Title:"), self.lnTitle) mformLayout.addRow(i18n("Cover Page:"), self.cmbCoverPage) mformLayout.addRow(i18n("Summary:"), self.teSummary) mformLayout.addRow(i18n("Language:"), self.cmbLanguage) mformLayout.addRow("", self.cmbCountry) mformLayout.addRow(i18n("Reading Direction:"), self.cmbReadingMode) mformLayout.addRow(i18n("Genre:"), self.lnGenre) mformLayout.addRow(i18n("Characters:"), self.lnCharacters) mformLayout.addRow(i18n("Format:"), self.lnFormat) mformLayout.addRow(i18n("Rating:"), ratingLayout) mformLayout.addRow(i18n("Series:"), seriesLayout) mformLayout.addRow(i18n("Other:"), self.lnOtherKeywords) mainWidget.addTab(metadataPage, i18n("Work")) # The page for the authors. authorPage = QWidget() authorPage.setLayout(QVBoxLayout()) explanation = QLabel(i18n("The following is a table of the authors that contributed to this comic. You can set their nickname, proper names (first, middle, last), Role (Penciller, Inker, etc), email and homepage.")) explanation.setWordWrap(True) self.authorModel = QStandardItemModel(0, 8) labels = [i18n("Nick Name"), i18n("Given Name"), i18n("Middle Name"), i18n("Family Name"), i18n("Role"), i18n("Email"), i18n("Homepage"), i18n("Language")] self.authorModel.setHorizontalHeaderLabels(labels) self.authorTable = QTableView() self.authorTable.setModel(self.authorModel) self.authorTable.verticalHeader().setDragEnabled(True) self.authorTable.verticalHeader().setDropIndicatorShown(True) self.authorTable.verticalHeader().setSectionsMovable(True) self.authorTable.verticalHeader().sectionMoved.connect(self.slot_reset_author_row_visual) delegate = author_delegate() delegate.setCompleterData(self.authorRoleList, 4) delegate.setLanguageData(len(labels) - 1) self.authorTable.setItemDelegate(delegate) author_button_layout = QWidget() author_button_layout.setLayout(QHBoxLayout()) btn_add_author = QPushButton(i18n("Add Author")) btn_add_author.clicked.connect(self.slot_add_author) btn_remove_author = QPushButton(i18n("Remove Author")) btn_remove_author.clicked.connect(self.slot_remove_author) author_button_layout.layout().addWidget(btn_add_author) author_button_layout.layout().addWidget(btn_remove_author) authorPage.layout().addWidget(explanation) authorPage.layout().addWidget(self.authorTable) authorPage.layout().addWidget(author_button_layout) mainWidget.addTab(authorPage, i18n("Authors")) # The page with publisher information. publisherPage = QWidget() publisherLayout = QFormLayout() publisherPage.setLayout(publisherLayout) self.publisherName = QLineEdit() self.publisherName.setToolTip(i18n("The name of the company, group or person who is responsible for the final version the reader gets.")) publishDateLayout = QHBoxLayout() self.publishDate = QDateEdit() self.publishDate.setDisplayFormat(QLocale().system().dateFormat()) currentDate = QPushButton(i18n("Set Today")) currentDate.setToolTip(i18n("Sets the publish date to the current date.")) currentDate.clicked.connect(self.slot_set_date) publishDateLayout.addWidget(self.publishDate) publishDateLayout.addWidget(currentDate) self.publishCity = QLineEdit() self.publishCity.setToolTip(i18n("Traditional publishers are always mentioned in source with the city they are located.")) self.isbn = QLineEdit() self.license = license_combo_box() # Maybe ought to make this a QLineEdit... self.license.setEditable(True) self.license.completer().setCompletionMode(QCompleter.PopupCompletion) dataBaseReference = QVBoxLayout() self.ln_database_name = QLineEdit() self.ln_database_name.setToolTip(i18n("If there's an entry in a comics data base, that should be added here. It is unlikely to be a factor for comics from scratch, but useful when doing a conversion.")) self.cmb_entry_type = QComboBox() self.cmb_entry_type.addItems(["IssueID", "SeriesID", "URL"]) self.cmb_entry_type.setEditable(True) self.ln_database_entry = QLineEdit() dbHorizontal = QHBoxLayout() dbHorizontal.addWidget(self.ln_database_name) dbHorizontal.addWidget(self.cmb_entry_type) dataBaseReference.addLayout(dbHorizontal) dataBaseReference.addWidget(self.ln_database_entry) publisherLayout.addRow(i18n("Name:"), self.publisherName) publisherLayout.addRow(i18n("City:"), self.publishCity) publisherLayout.addRow(i18n("Date:"), publishDateLayout) publisherLayout.addRow(i18n("ISBN:"), self.isbn) publisherLayout.addRow(i18n("License:"), self.license) publisherLayout.addRow(i18n("Database:"), dataBaseReference) mainWidget.addTab(publisherPage, i18n("Publisher"))
def openFile(self) -> None: filename, _ = QFileDialog.getOpenFileName(self.parent, caption='Select video', directory=QDir.homePath()) if filename != '': self.loadFile(filename)
def _open_dir(self): home_path = QDir.homePath() options = QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks selected_dir = QFileDialog.getExistingDirectory(self, "选择目录", home_path, options) if selected_dir: self.controller.do_open_dir(selected_dir)
def _open_file(self): home_path = QDir.homePath() file = QFileDialog.getOpenFileName(self, "Select File", home_path, "All Files (*.*)") self.controller.do_open_file(file[0])
def __init__(self, parent, *args, **kwargs): super(ListWidget, self).__init__(*args, **kwargs) self.setWindowTitle("Devices list") self.setWindowState(Qt.WindowMaximized) self.setLayout(VLayout(margin=0, spacing=0)) self.mqtt = parent.mqtt self.env = parent.env self.device = None self.idx = None self.nam = QNetworkAccessManager() self.backup = bytes() self.settings = QSettings("{}/TDM/tdm.cfg".format(QDir.homePath()), QSettings.IniFormat) views_order = self.settings.value("views_order", []) self.views = {} self.settings.beginGroup("Views") views = self.settings.childKeys() if views and views_order: for view in views_order.split(";"): view_list = self.settings.value(view).split(";") self.views[view] = base_view + view_list else: self.views = default_views self.settings.endGroup() self.tb = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonTextBesideIcon) self.tb_relays = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonIconOnly) # self.tb_filter = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonTextBesideIcon) self.tb_views = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonTextBesideIcon) self.pwm_sliders = [] self.layout().addWidget(self.tb) self.layout().addWidget(self.tb_relays) # self.layout().addWidget(self.tb_filter) self.device_list = TableView() self.device_list.setIconSize(QSize(24, 24)) self.model = parent.device_model self.model.setupColumns(self.views["Home"]) self.sorted_device_model = QSortFilterProxyModel() self.sorted_device_model.setFilterCaseSensitivity(Qt.CaseInsensitive) self.sorted_device_model.setSourceModel(parent.device_model) self.sorted_device_model.setSortRole(Qt.InitialSortOrderRole) self.sorted_device_model.setSortLocaleAware(True) self.sorted_device_model.setFilterKeyColumn(-1) self.device_list.setModel(self.sorted_device_model) self.device_list.setupView(self.views["Home"]) self.device_list.setSortingEnabled(True) self.device_list.setWordWrap(True) self.device_list.setItemDelegate(DeviceDelegate()) self.device_list.sortByColumn(self.model.columnIndex("FriendlyName"), Qt.AscendingOrder) self.device_list.setContextMenuPolicy(Qt.CustomContextMenu) self.device_list.verticalHeader().setSectionResizeMode( QHeaderView.ResizeToContents) self.layout().addWidget(self.device_list) self.layout().addWidget(self.tb_views) self.device_list.clicked.connect(self.select_device) self.device_list.customContextMenuRequested.connect( self.show_list_ctx_menu) self.ctx_menu = QMenu() self.create_actions() self.create_view_buttons() # self.create_view_filter() self.device_list.doubleClicked.connect(lambda: self.openConsole.emit())
def __init__(self, *args): super().__init__(*args) self.ui = Ui_MainWindow() self.ui.setupUi(self) OptionsController.write_default_options() self.project_save_timer = QTimer() self.project_manager = ProjectManager(self) self.plugin_manager = PluginManager() self.signal_tab_controller = SignalTabController( self.project_manager, parent=self.ui.tab_interpretation) self.ui.tab_interpretation.layout().addWidget( self.signal_tab_controller) self.compare_frame_controller = CompareFrameController( parent=self.ui.tab_protocol, plugin_manager=self.plugin_manager, project_manager=self.project_manager) self.ui.tab_protocol.layout().addWidget(self.compare_frame_controller) self.generator_tab_controller = GeneratorTabController( self.compare_frame_controller, self.project_manager, parent=self.ui.tab_generator) self.undo_group = QUndoGroup() self.undo_group.addStack(self.signal_tab_controller.signal_undo_stack) self.undo_group.addStack( self.compare_frame_controller.protocol_undo_stack) self.undo_group.addStack( self.generator_tab_controller.generator_undo_stack) self.undo_group.setActiveStack( self.signal_tab_controller.signal_undo_stack) self.ui.progressBar.hide() self.participant_legend_model = ParticipantLegendListModel( self.project_manager.participants) self.ui.listViewParticipants.setModel(self.participant_legend_model) gtc = self.generator_tab_controller gtc.ui.splitter.setSizes([gtc.width() / 0.7, gtc.width() / 0.3]) self.ui.tab_generator.layout().addWidget(self.generator_tab_controller) self.signal_protocol_dict = {} """:type: dict[SignalFrameController,ProtocolAnalyzer]""" self.signal_tab_controller.ui.lLoadingFile.setText("") self.ui.lnEdtTreeFilter.setClearButtonEnabled(True) group = QActionGroup(self) self.ui.actionFSK.setActionGroup(group) self.ui.actionOOK.setActionGroup(group) self.ui.actionNone.setActionGroup(group) self.ui.actionPSK.setActionGroup(group) self.signal_tab_controller.ui.lShiftStatus.clear() self.recentFileActionList = [] self.create_connects() self.update_recent_action_list() self.filemodel = FileSystemModel(self) path = QDir.homePath() self.filemodel.setIconProvider(FileIconProvider()) self.filemodel.setRootPath(path) self.file_proxy_model = FileFilterProxyModel(self) self.file_proxy_model.setSourceModel(self.filemodel) self.ui.fileTree.setModel(self.file_proxy_model) self.ui.fileTree.setRootIndex( self.file_proxy_model.mapFromSource(self.filemodel.index(path))) self.ui.fileTree.setToolTip(path) self.ui.fileTree.header().setSectionResizeMode(0, QHeaderView.Stretch) self.ui.fileTree.header().setSectionResizeMode(1, QHeaderView.Interactive) self.ui.fileTree.setFocus() self.generator_tab_controller.table_model.cfc = self.compare_frame_controller self.ui.actionConvert_Folder_to_Project.setEnabled(False) undo_action = self.undo_group.createUndoAction(self) undo_action.setIcon(QIcon.fromTheme("edit-undo")) undo_action.setShortcut(QKeySequence.Undo) self.ui.menuEdit.insertAction(self.ui.actionMinimize_all, undo_action) redo_action = self.undo_group.createRedoAction(self) redo_action.setIcon(QIcon.fromTheme("edit-redo")) redo_action.setShortcut(QKeySequence.Redo) self.ui.splitter.setSizes([0, 1]) self.ui.menuEdit.insertAction(self.ui.actionMinimize_all, redo_action) self.refresh_main_menu() self.apply_default_view() self.project_save_timer.start( ProjectManager.AUTOSAVE_INTERVAL_MINUTES * 60 * 1000) self.ui.actionProject_settings.setVisible(False) self.ui.actionSave_project.setVisible(False) # Disabled because never used self.ui.actionMinimize_all.setVisible(False) self.ui.actionMaximize_all.setVisible(False)
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self._version = "0.2.0" self.setWindowIcon(QIcon("GUI/icons/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 = [] 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, 618)) # because golden ratio :) # 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.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() # load custom autodiscovery patterns self.settings.beginGroup("Patterns") for k in self.settings.childKeys(): custom_patterns.append(self.settings.value(k)) self.settings.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 = {}
def onSelectImage(self): fname = QFileDialog.getOpenFileName(self, 'Open file', QDir.homePath(), "Image files (*.jpg)") if len(fname[0]) > 0: self.showImage(fname[0])
def mqtt_message(self, topic, msg): # try to find a device by matching known FullTopics against the MQTT topic of the message device = self.env.find_device(topic) if device: if topic.endswith("LWT"): if not msg: msg = "Offline" device.update_property("LWT", msg) if msg == 'Online': # known device came online, query initial state self.initial_query(device, True) else: # forward the message for processing device.parse_message(topic, msg) else: # unknown device, start autodiscovery process if topic.endswith("LWT"): # STAGE 1 # load default and user-provided FullTopic patterns and for all the patterns, # try matching the LWT topic (it follows the device's FullTopic syntax for p in default_patterns + custom_patterns: match = re.fullmatch( p.replace("%topic%", "(?P<topic>.*?)").replace( "%prefix%", "(?P<prefix>.*?)") + ".*$", topic) if match: # assume that the matched topic is the one configured in device settings possible_topic = match.groupdict().get('topic') if possible_topic not in ('tele', 'stat'): # if the assumed topic is different from tele or stat, there is a chance that it's a valid topic # query the assumed device for its FullTopic. False positives won't reply. self.mqtt_queue.append([ p.replace("%prefix%", "cmnd").replace( "%topic%", possible_topic) + "FullTopic", "" ]) elif topic.endswith("RESULT"): # reply from an unknown device # STAGE 2 try: full_topic = loads(msg).get('FullTopic') if full_topic: # the device replies with its FullTopic # here the Topic is extracted using the returned FullTopic, identifying the device parsed = parse_topic(full_topic, topic) if parsed: # got a match, we query the device's MAC address in case it's a known device that had its topic changed d = self.env.find_device(topic=parsed['topic']) if d: d.update_property("FullTopic", full_topic) else: print("DISCOVERED", parsed['topic']) d = TasmotaDevice(parsed['topic'], full_topic) self.env.devices.append(d) self.device_model.addDevice(d) self.initial_query(d, True) d.update_property("LWT", "Online") except JSONDecodeError as e: 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))
def __init__(self, parent=None): super(Form, self).__init__(parent) self.mutex = QMutex() self.fileCount = 0 self.filenamesForWords = collections.defaultdict(set) self.commonWords = set() self.lock = QReadWriteLock() self.path = QDir.homePath() pathLabel = QLabel("Indexing path:") self.pathLabel = QLabel() self.pathLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.pathButton = QPushButton("Set &Path...") self.pathButton.setAutoDefault(False) findLabel = QLabel("&Find word:") self.findEdit = QLineEdit() findLabel.setBuddy(self.findEdit) commonWordsLabel = QLabel("&Common words:") self.commonWordsListWidget = QListWidget() commonWordsLabel.setBuddy(self.commonWordsListWidget) filesLabel = QLabel("Files containing the &word:") self.filesListWidget = QListWidget() filesLabel.setBuddy(self.filesListWidget) filesIndexedLabel = QLabel("Files indexed") self.filesIndexedLCD = QLCDNumber() self.filesIndexedLCD.setSegmentStyle(QLCDNumber.Flat) wordsIndexedLabel = QLabel("Words indexed") self.wordsIndexedLCD = QLCDNumber() self.wordsIndexedLCD.setSegmentStyle(QLCDNumber.Flat) commonWordsLCDLabel = QLabel("Common words") self.commonWordsLCD = QLCDNumber() self.commonWordsLCD.setSegmentStyle(QLCDNumber.Flat) self.statusLabel = QLabel("Click the 'Set Path' " "button to start indexing") self.statusLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) topLayout = QHBoxLayout() topLayout.addWidget(pathLabel) topLayout.addWidget(self.pathLabel, 1) topLayout.addWidget(self.pathButton) topLayout.addWidget(findLabel) topLayout.addWidget(self.findEdit, 1) leftLayout = QVBoxLayout() leftLayout.addWidget(filesLabel) leftLayout.addWidget(self.filesListWidget) rightLayout = QVBoxLayout() rightLayout.addWidget(commonWordsLabel) rightLayout.addWidget(self.commonWordsListWidget) middleLayout = QHBoxLayout() middleLayout.addLayout(leftLayout, 1) middleLayout.addLayout(rightLayout) bottomLayout = QHBoxLayout() bottomLayout.addWidget(filesIndexedLabel) bottomLayout.addWidget(self.filesIndexedLCD) bottomLayout.addWidget(wordsIndexedLabel) bottomLayout.addWidget(self.wordsIndexedLCD) bottomLayout.addWidget(commonWordsLCDLabel) bottomLayout.addWidget(self.commonWordsLCD) bottomLayout.addStretch() layout = QVBoxLayout() layout.addLayout(topLayout) layout.addLayout(middleLayout) layout.addLayout(bottomLayout) layout.addWidget(self.statusLabel) self.setLayout(layout) self.walkers = [] self.completed = [] self.pathButton.clicked.connect(self.setPath) self.findEdit.returnPressed.connect(self.find) self.setWindowTitle("Page Indexer")
class FillMissingSlicesGui(LayerViewerGui): _standardPatchSizes = [1, 2, 4, 8] + [16 * i for i in range(1, 6)] _standardHaloSizes = [8 * i for i in range(7)] _recentDetectorDir = QDir.homePath() _recentExportDir = QDir.homePath() def initAppletDrawerUi(self): """""" # Load the ui file (find it in our own directory) localDir = os.path.split(__file__)[0] self._drawer = PyQt5.uic.loadUi(localDir + "/drawer.ui") self._drawer.loadDetectorButton.clicked.connect( self._loadDetectorButtonPressed) if hasattr(self._drawer, "loadHistogramsButton"): self._drawer.loadHistogramsButton.clicked.connect( self._loadHistogramsButtonPressed) self._drawer.exportDetectorButton.clicked.connect( self._exportDetectorButtonPressed) if hasattr(self._drawer, "trainButton"): self._drawer.trainButton.clicked.connect(self._trainButtonPressed) self._drawer.patchSizeComboBox.activated.connect( self._patchSizeComboBoxActivated) for s in self._standardPatchSizes: self._drawer.patchSizeComboBox.addItem(str(s), userData=s) self._drawer.haloSizeComboBox.activated.connect( self._haloSizeComboBoxActivated) for s in self._standardHaloSizes: self._drawer.haloSizeComboBox.addItem(str(s), userData=s) self.patchSizeChanged(update=True) self.haloSizeChanged(update=True) self.topLevelOperatorView.PatchSize.notifyValueChanged( self.patchSizeChanged, update=True) self.topLevelOperatorView.HaloSize.notifyValueChanged( self.haloSizeChanged, update=True) def _loadDetectorButtonPressed(self): fname, _filter = QFileDialog.getOpenFileName( self, caption="Open Detector File", filter="Pickled Objects (*.pkl);;All Files (*)", directory=self._recentDetectorDir, ) if len(fname) > 0: # not cancelled with open(fname, "r") as f: pkl = f.read() # reset it first self.topLevelOperatorView.OverloadDetector.setValue("") self.topLevelOperatorView.OverloadDetector.setValue(pkl) logger.debug("Loaded detectors from file '{}'".format(fname)) self._recentDetectorDir = os.path.dirname(fname) def _loadHistogramsButtonPressed(self): fname, _filter = QFileDialog.getOpenFileName( self, caption="Open Histogram File", filter="HDF5 Files (*.h5 *.hdf5);;All Files (*)", directory=QDir.homePath(), ) if len(fname) > 0: # not cancelled # FIXME where do we get the real h5 path from??? h5path = "volume/data" # no try-catch because we want to propagate errors to the GUI histos = vigra.impex.readHDF5(str(fname), h5path) self.topLevelOperatorView.setPrecomputedHistograms(histos) logger.debug("Loaded histograms from file '{}' (shape: {})".format( fname, histos.shape)) def _exportDetectorButtonPressed(self): fname, _filter = QFileDialog.getSaveFileName( self, caption="Export Trained Detector", filter="Pickled Objects (*.pkl);;All Files (*)", directory=self._recentExportDir, ) if len(fname) > 0: # not cancelled with open(fname, "w") as f: f.write(self.topLevelOperatorView.Detector[:].wait()) logger.debug("Exported detectors to file '{}'".format(fname)) self._recentExportDir = os.path.dirname(fname) def _trainButtonPressed(self): self.topLevelOperatorView.train() def _patchSizeComboBoxActivated(self, i): desiredPatchSize = self._drawer.patchSizeComboBox.itemData(i) self.topLevelOperatorView.PatchSize.setValue(desiredPatchSize) def _haloSizeComboBoxActivated(self, i): desiredHaloSize = self._drawer.haloSizeComboBox.itemData(i) self.topLevelOperatorView.HaloSize.setValue(desiredHaloSize) @staticmethod def _insertIntoComboBox(cb, n): i = cb.findData(n) if i < 0: j = 0 for i in range(cb.count()): k = cb.itemData(i) if k == n: return i elif k > n: j = i break else: j += 1 cb.insertItem(j, str(n), userData=n) return j else: return i def patchSizeChanged(self, update=False): patchSize = self.topLevelOperatorView.PatchSize.value pos = self._insertIntoComboBox(self._drawer.patchSizeComboBox, patchSize) self._patchSizeComboBoxActivated(pos) if update: self._drawer.patchSizeComboBox.setCurrentIndex(pos) def haloSizeChanged(self, update=False): haloSize = self.topLevelOperatorView.HaloSize.value pos = self._insertIntoComboBox(self._drawer.haloSizeComboBox, haloSize) self._haloSizeComboBoxActivated(pos) if update: self._drawer.haloSizeComboBox.setCurrentIndex(pos)
def searchAllDriverMusic(self): self.scanFolder(QDir.homePath())
def choose_encoder(self): f, ok = QFileDialog.getOpenFileName(self, self.tr("Choose encoder program"), QDir.homePath()) if f and ok: self.ui.external_encoder.setText(f) self.handle_external()
def uploadFile(self): global fileName, path fileName, _ = QFileDialog.getOpenFileName( None, "QFileDialog.getOpenFileName()", "", "All Files (*);;Python Files (*.py)", QDir.homePath()) self.lineEdit.setText(fileName) if fileName != '': self.myVideo.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(fileName))) self.myVideo.playButton.setEnabled(True) # create project folder dic = QDir() path = QDir(fileName).dirName() path = path.replace(".", "-") # path = './output/' dic.mkdir(path) dic.setCurrent(path)
def setup_ui(self): self.ui.setupUi(self) settings = QSettings() self.ui.splitter.setSizes([600, 1000]) self.ui.splitter.setChildrenCollapsible(False) # Set up folder view lastDir = settings.value("mainwindow/workingDirectory", QDir.homePath()) log.debug('Current directory: {currentDir}'.format(currentDir=lastDir)) self.fileModel = QFileSystemModel(self) self.fileModel.setFilter(QDir.AllDirs | QDir.Dirs | QDir.Drives | QDir.NoDotAndDotDot | QDir.Readable | QDir.Executable | QDir.Writable) self.fileModel.iconProvider().setOptions( QFileIconProvider.DontUseCustomDirectoryIcons) self.fileModel.setRootPath(QDir.rootPath()) self.fileModel.directoryLoaded.connect(self.onFileModelDirectoryLoaded) self.proxyFileModel = QSortFilterProxyModel(self) self.proxyFileModel.setSortRole(Qt.DisplayRole) self.proxyFileModel.setSourceModel(self.fileModel) self.proxyFileModel.sort(0, Qt.AscendingOrder) self.proxyFileModel.setSortCaseSensitivity(Qt.CaseInsensitive) self.ui.folderView.setModel(self.proxyFileModel) self.ui.folderView.setHeaderHidden(True) self.ui.folderView.hideColumn(3) self.ui.folderView.hideColumn(2) self.ui.folderView.hideColumn(1) index = self.fileModel.index(lastDir) proxyIndex = self.proxyFileModel.mapFromSource(index) self.ui.folderView.scrollTo(proxyIndex) self.ui.folderView.expanded.connect(self.onFolderViewExpanded) self.ui.folderView.clicked.connect(self.onFolderTreeClicked) self.ui.buttonFind.clicked.connect(self.onButtonFind) self.ui.buttonRefresh.clicked.connect(self.onButtonRefresh) # Set up introduction self.showInstructions() # Set up video view self.ui.filterLanguageForVideo.set_unknown_text(_('All languages')) self.ui.filterLanguageForVideo.selected_language_changed.connect( self.on_language_combobox_filter_change) # self.ui.filterLanguageForVideo.selected_language_changed.connect(self.onFilterLanguageVideo) self.videoModel = VideoModel(self) self.ui.videoView.setHeaderHidden(True) self.ui.videoView.setModel(self.videoModel) self.ui.videoView.activated.connect(self.onClickVideoTreeView) self.ui.videoView.clicked.connect(self.onClickVideoTreeView) self.ui.videoView.customContextMenuRequested.connect(self.onContext) self.videoModel.dataChanged.connect(self.subtitlesCheckedChanged) self.language_filter_change.connect( self.videoModel.on_filter_languages_change) self.ui.buttonSearchSelectVideos.clicked.connect( self.onButtonSearchSelectVideos) self.ui.buttonSearchSelectFolder.clicked.connect( self.onButtonSearchSelectFolder) self.ui.buttonDownload.clicked.connect(self.onButtonDownload) self.ui.buttonPlay.clicked.connect(self.onButtonPlay) self.ui.buttonIMDB.clicked.connect(self.onViewOnlineInfo) self.ui.videoView.setContextMenuPolicy(Qt.CustomContextMenu) # Drag and Drop files to the videoView enabled self.ui.videoView.__class__.dragEnterEvent = self.dragEnterEvent self.ui.videoView.__class__.dragMoveEvent = self.dragEnterEvent self.ui.videoView.__class__.dropEvent = self.dropEvent self.ui.videoView.setAcceptDrops(1) # FIXME: ok to drop this connect? # self.ui.videoView.clicked.connect(self.onClickMovieTreeView) self.retranslate()
global INSTALL_PREREQUISITES, WITH_MPI, INSTALL_OPENMC, INSTALL_MINICONDA, DOWNLOAD_MINICONDA, UPDATE_CONDA,\ CHECKSUM, CONDA_MD5_IN, SH_SCRIPT, CONDA_URL, CONDA_DIR # tab_index = 0 # Miniconda3 MD5 and download url INSTALL_MINICONDA = 'no' DOWNLOAD_MINICONDA = 'no' UPDATE_CONDA = 'no' CHECKSUM = 'no' INSTALL_PYQT = 'no' SH_SCRIPT = 'Miniconda3-latest-Linux-x86_64.sh' CONDA_MD5 = "1314b90489f154602fd794accfc90446111514a5a72fe1f71ab83e07de9504a7" CONDA_MD5_IN = CONDA_MD5 url1 = 'https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh' url2 = 'http://196.200.152.180/ERSN-OpenMC/scripts/Miniconda3-latest-Linux-x86_64.sh' CONDA_URL = url1 miniconda = QDir.homePath() + '/miniconda3/bin/conda' cmd = '' gcc = 'gcc_linux-64 gxx_linux-64' cmake = 'cmake' INSTALL_PREREQUISITES = 'no' WITH_MPI = 'no' INSTALL_IN_CONDA = 'yes' INSTALL_EDITABLE = 'no' DELETE_SOURCES = 'no' UPDATE_ENV = 'no' WORK_DIR = QDir.homePath() WORK_DIR_XS = QDir.homePath() PYTHON_VERSION = '3.7' ENV_NAME = 'openmc-py'
def __init__(self, *args): super().__init__(*args) self.ui = Ui_MainWindow() self.ui.setupUi(self) OptionsDialog.write_default_options() self.project_save_timer = QTimer() self.project_manager = ProjectManager(self) self.plugin_manager = PluginManager() self.signal_tab_controller = SignalTabController(self.project_manager, parent=self.ui.tab_interpretation) self.ui.tab_interpretation.layout().addWidget(self.signal_tab_controller) self.compare_frame_controller = CompareFrameController(parent=self.ui.tab_protocol, plugin_manager=self.plugin_manager, project_manager=self.project_manager) self.compare_frame_controller.ui.splitter.setSizes([1, 1000000]) self.ui.tab_protocol.layout().addWidget(self.compare_frame_controller) self.generator_tab_controller = GeneratorTabController(self.compare_frame_controller, self.project_manager, parent=self.ui.tab_generator) self.simulator_tab_controller = SimulatorTabController(parent=self.ui.tab_simulator, compare_frame_controller=self.compare_frame_controller, generator_tab_controller=self.generator_tab_controller, project_manager=self.project_manager) self.ui.tab_simulator.layout().addWidget(self.simulator_tab_controller) self.undo_group = QUndoGroup() self.undo_group.addStack(self.signal_tab_controller.signal_undo_stack) self.undo_group.addStack(self.compare_frame_controller.protocol_undo_stack) self.undo_group.addStack(self.generator_tab_controller.generator_undo_stack) self.undo_group.setActiveStack(self.signal_tab_controller.signal_undo_stack) self.cancel_action = QAction(self.tr("Cancel"), self) self.cancel_action.setShortcut(QKeySequence.Cancel if hasattr(QKeySequence, "Cancel") else "Esc") self.cancel_action.triggered.connect(self.on_cancel_triggered) self.cancel_action.setShortcutContext(Qt.WidgetWithChildrenShortcut) self.cancel_action.setIcon(QIcon.fromTheme("dialog-cancel")) self.addAction(self.cancel_action) self.participant_legend_model = ParticipantLegendListModel(self.project_manager.participants) self.ui.listViewParticipants.setModel(self.participant_legend_model) gtc = self.generator_tab_controller gtc.ui.splitter.setSizes([gtc.width() / 0.7, gtc.width() / 0.3]) self.ui.tab_generator.layout().addWidget(self.generator_tab_controller) self.signal_protocol_dict = {} # type: dict[SignalFrame, ProtocolAnalyzer] self.ui.lnEdtTreeFilter.setClearButtonEnabled(True) group = QActionGroup(self) self.ui.actionFSK.setActionGroup(group) self.ui.actionOOK.setActionGroup(group) self.ui.actionNone.setActionGroup(group) self.ui.actionPSK.setActionGroup(group) self.recentFileActionList = [] self.create_connects() self.init_recent_file_action_list(constants.SETTINGS.value("recentFiles", [])) self.filemodel = FileSystemModel(self) path = QDir.homePath() self.filemodel.setIconProvider(FileIconProvider()) self.filemodel.setRootPath(path) self.file_proxy_model = FileFilterProxyModel(self) self.file_proxy_model.setSourceModel(self.filemodel) self.ui.fileTree.setModel(self.file_proxy_model) self.ui.fileTree.setRootIndex(self.file_proxy_model.mapFromSource(self.filemodel.index(path))) self.ui.fileTree.setToolTip(path) self.ui.fileTree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents) self.ui.fileTree.header().setSectionResizeMode(1, QHeaderView.Stretch) self.ui.fileTree.setFocus() self.generator_tab_controller.table_model.cfc = self.compare_frame_controller self.ui.actionConvert_Folder_to_Project.setEnabled(False) undo_action = self.undo_group.createUndoAction(self) undo_action.setIcon(QIcon.fromTheme("edit-undo")) undo_action.setShortcut(QKeySequence.Undo) self.ui.menuEdit.insertAction(self.ui.actionDecoding, undo_action) redo_action = self.undo_group.createRedoAction(self) redo_action.setIcon(QIcon.fromTheme("edit-redo")) redo_action.setShortcut(QKeySequence.Redo) self.ui.menuEdit.insertAction(self.ui.actionDecoding, redo_action) self.ui.menuEdit.insertSeparator(self.ui.actionDecoding) self.ui.actionAbout_Qt.setIcon(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png")) self.__set_non_project_warning_visibility() self.ui.splitter.setSizes([0, 1]) self.refresh_main_menu() self.apply_default_view(constants.SETTINGS.value('default_view', type=int)) self.project_save_timer.start(ProjectManager.AUTOSAVE_INTERVAL_MINUTES * 60 * 1000) self.ui.actionProject_settings.setVisible(False) self.ui.actionSave_project.setVisible(False) self.ui.tabWidget.removeTab(3)
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 saveImage(self, width, height, image): filename, _ = QFileDialog.getSaveFileName(self.wnd, self.tr("Save As"), QDir.homePath(), "PNG files (*.png)") if filename: image.save(filename)
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 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 buscarArchivo(self): file, _ = QFileDialog.getOpenFileName(self, 'Buscar Archivo', QDir.homePath(), "Text Files (*.txt)") return file
"Please specify existing location of the new file!") msg.exec_() elif not os.path.isdir(self.get_directory()): msg = QMessageBox(self) msg.setWindowTitle("Wrong Base Directory") msg.setText( "Please specify existing location of the new file!") msg.exec_() elif os.path.isfile(self.get_file_name()): msg = QMessageBox(self) msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msg.setWindowTitle("File exists") msg.setText( "Specified file already exists. Do you wish to override it" ) if msg.exec_() == msg.Ok: super().done(p_int) else: super().done(p_int) if __name__ == "__main__": import sys from PyQt5 import QtWidgets app = QtWidgets.QApplication(sys.argv) ui = NewFileDialog(default_directory=QDir.homePath()) sys.exit(ui.exec())