def editorEvent(self, event, model, option, index): #paket seçim olayında hata var seçim olayı gerçekleşiyor ama packageList sonraki seçimde görüyor #geçici çözümle giderildi tamamen çözülmeli if event.type() == QEvent.MouseButtonRelease and index.column() == 0 and index.flags() & Qt.ItemIsUserCheckable: toggled = Qt.Checked if model.data(index, Qt.CheckStateRole) == QVariant(Qt.Unchecked) else Qt.Unchecked self.packageSelected.emit(bool(toggled)) return model.setData(index, toggled, Qt.CheckStateRole) __event = QItemDelegate(self).editorEvent(event, model, option, index) animate_requested = False if event.type() == QEvent.MouseButtonRelease and self.animatable: if self.rowAnimator.row == index.row(): epos = event.pos() if self.rowAnimator.hoverLinkFilter.link_rect.contains(QPoint(epos.x(), epos.y() + 32)): url = QUrl(QVariant.value(model.data(index, HomepageRole))) QDesktopServices.openUrl(url) return __event elif self.rowAnimator.hoverLinkFilter.button_rect.contains(epos, True): self.showPackageDetails(model, index) return __event animate_requested = True elif event.type() == QEvent.KeyPress and self.animatable: # KeyCode 32 : Space key if event.key() == 32 and index.column() == index.model().columnCount() - 1: animate_requested = True if not QVariant.value(model.data(index, DescriptionRole)) == '' and animate_requested: self.rowAnimator.animate(index.row()) return __event
def showHelp(self): help_path = op.abspath(op.join(HELP_PATH, 'index.html')) if op.exists(help_path): url = QUrl.fromLocalFile(help_path) else: url = QUrl("https://www.hardcoded.net/moneyguru/help/en") QDesktopServices.openUrl(url)
def open_file(self, cmdline=None): """Open the downloaded file. Args: cmdline: The command to use as string. A `{}` is expanded to the filename. None means to use the system's default application. If no `{}` is found, the filename is appended to the cmdline. """ assert self.successful filename = self._get_open_filename() if filename is None: # pragma: no cover log.downloads.error("No filename to open the download!") return if cmdline is None: log.downloads.debug("Opening {} with the system application" .format(filename)) url = QUrl.fromLocalFile(filename) QDesktopServices.openUrl(url) return cmd, *args = shlex.split(cmdline) args = [arg.replace('{}', filename) for arg in args] if '{}' not in cmdline: args.append(filename) log.downloads.debug("Opening {} with {}" .format(filename, [cmd] + args)) proc = guiprocess.GUIProcess(what='download') proc.start_detached(cmd, args)
def __open(self): """ Private slot to open the downloaded file. """ info = QFileInfo(self.__output) url = QUrl.fromLocalFile(info.absoluteFilePath()) QDesktopServices.openUrl(url)
def contextMenuEvent(self, event): menu = QMenu(self) local_filename = self.currentItem().text() # Get the file extension ext = os.path.splitext(local_filename)[1].lower() open_internal_action = None # Mu micro:bit mode only handles .py & .hex if ext == '.py' or ext == '.hex': open_internal_action = menu.addAction(_("Open in Mu")) # Open outside Mu (things get meta if Mu is the default application) open_action = menu.addAction(_("Open")) action = menu.exec_(self.mapToGlobal(event.pos())) if action == open_action: # Get the file's path path = os.path.join(self.home, local_filename) logger.info("Opening {}".format(path)) msg = _("Opening '{}'").format(local_filename) logger.info(msg) self.set_message.emit(msg) # Let Qt work out how to open it QDesktopServices.openUrl(QUrl.fromLocalFile(path)) elif action == open_internal_action: logger.info("Open {} internally".format(local_filename)) # Get the file's path path = os.path.join(self.home, local_filename) # Send the signal bubbling up the tree self.open_file.emit(path)
def make_cypherseed(self, img, rawnoise, calibration=False, is_seed = True): img = img.convertToFormat(QImage.Format_Mono) p = QPainter() p.begin(img) p.setCompositionMode(26) #xor p.drawImage(0, 0, rawnoise) p.end() cypherseed = self.pixelcode_2x2(img) cypherseed = QBitmap.fromImage(cypherseed) cypherseed = cypherseed.scaled(self.f_size, Qt.KeepAspectRatio) cypherseed = self.overlay_marks(cypherseed, True, calibration) if not is_seed: self.filename_prefix = 'custom_secret_' self.was = _('Custom secret') else: self.filename_prefix = self.wallet_name + '_seed_' self.was = self.wallet_name + ' ' + _('seed') if self.extension: self.ext_warning(self.c_dialog) if not calibration: self.toPdf(QImage(cypherseed)) QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf'))) cypherseed.save(self.get_path_to_revealer_file('.png')) self.bcrypt(self.c_dialog) return cypherseed
def tableClicked(self, r, c): if c == 2 or c == 3: cell = self.table.item(r, c) if cell: url = cell.text() if url: QDesktopServices.openUrl(QUrl(url))
def openFolder(self): """ Public slot to open the folder containing the downloaded file. """ info = QFileInfo(self.__fileName) url = QUrl.fromLocalFile(info.absolutePath()) QDesktopServices.openUrl(url)
def OnUrlMessage(self): from PyQt5.QtGui import QDesktopServices from PyQt5.QtCore import QUrl reply = QMessageBox.information(self, "www", _('Open web')+'\n'+self.url) if reply == QMessageBox.Ok: QDesktopServices.openUrl(QUrl(self.url))
def _openItem(self): """ Protected slot to handle the open popup menu entry. """ itmList = self.getSelectedItems( [BrowserFileItem, BrowserClassItem, BrowserMethodItem, BrowserClassAttributeItem, BrowserImportItem]) if not self._activating: self._activating = True for itm in itmList: if isinstance(itm, BrowserFileItem): if itm.isPython2File(): self.sourceFile[str].emit(itm.fileName()) elif itm.isPython3File(): self.sourceFile[str].emit(itm.fileName()) elif itm.isRubyFile(): self.sourceFile[str, int, str].emit( itm.fileName(), -1, "Ruby") elif itm.isDFile(): self.sourceFile[str, int, str].emit( itm.fileName(), -1, "D") elif itm.isDesignerFile(): self.designerFile.emit(itm.fileName()) elif itm.isLinguistFile(): if itm.fileExt() == '.ts': self.linguistFile.emit(itm.fileName()) else: self.trpreview.emit([itm.fileName()]) elif itm.isProjectFile(): self.projectFile.emit(itm.fileName()) elif itm.isMultiProjectFile(): self.multiProjectFile.emit(itm.fileName()) elif itm.isIdlFile(): self.sourceFile[str].emit(itm.fileName()) elif itm.isResourcesFile(): self.sourceFile[str].emit(itm.fileName()) elif itm.isSvgFile(): self.svgFile.emit(itm.fileName()) elif itm.isPixmapFile(): self.pixmapFile.emit(itm.fileName()) else: if Utilities.MimeTypes.isTextFile(itm.fileName()): self.sourceFile[str].emit(itm.fileName()) else: QDesktopServices.openUrl(QUrl(itm.fileName())) elif isinstance(itm, BrowserClassItem): self.sourceFile[str, int].emit( itm.fileName(), itm.classObject().lineno) elif isinstance(itm, BrowserMethodItem): self.sourceFile[str, int].emit( itm.fileName(), itm.functionObject().lineno) elif isinstance(itm, BrowserClassAttributeItem): self.sourceFile[str, int].emit( itm.fileName(), itm.attributeObject().lineno) elif isinstance(itm, BrowserImportItem): self.sourceFile[str, list].emit( itm.fileName(), itm.linenos()) self._activating = False
def open_help(self): url = QUrl() url.setScheme(DefaultConfig.Help.url_scheme) url.setHost(DefaultConfig.Help.host) url.setPath(DefaultConfig.Help.url_path_pattern) # % str(Version.babel)) QDesktopServices.openUrl(url)
def setupUrlHandles(self): # Make sure we don't run a root browser. # NOTE: Qt native API can set an openUrl handler from a QObject # function, pyqt in theory also allows an arbitrary callable. Latter # has been observed to be non-functional so rely on the native handling QDesktopServices.setUrlHandler('http', self, 'openUrl') QDesktopServices.setUrlHandler('https', self, 'openUrl')
def on_messages_anchorClicked(self, url): """ Private slot to open links in the default browser. @param url URL to be opened (QUrl) """ QDesktopServices.openUrl(url)
def showHelpTriggered(self): base_path = platform.HELP_PATH help_path = op.abspath(op.join(base_path, 'index.html')) if op.exists(help_path): url = QUrl.fromLocalFile(help_path) else: url = QUrl('https://www.hardcoded.net/dupeguru/help/en/') QDesktopServices.openUrl(url)
def acceptNavigationRequest(self, url, _type, isMainFrame): query = QUrlQuery(url) if query.hasQueryItem("requrl"): orig_url = query.queryItemValue("requrl", QUrl.FullyDecoded) url = QUrl(orig_url) QDesktopServices.openUrl(url) return False return super().acceptNavigationRequest(url, _type, isMainFrame)
def _onCloudFlowStarted(self, messageId: str, actionId: str) -> None: address = self._application.getMachineManager().activeMachineAddress # type: str if address: QDesktopServices.openUrl(QUrl("http://" + address + "/cloud_connect")) if self._start_cloud_flow_message: self._start_cloud_flow_message.hide() self._start_cloud_flow_message = None return
def open_node_in_browser(self): node = self.sender().data() bma_endpoints = [e for e in node.endpoints if isinstance(e, BMAEndpoint)] if bma_endpoints: conn_handler = next(bma_endpoints[0].conn_handler()) peering_url = bma.API(conn_handler, bma.network.URL_PATH).reverse_url(conn_handler.http_scheme, '/peering') url = QUrl(peering_url) QDesktopServices.openUrl(url)
def _edit_ui_file(self): item = self.currentItem() if item.parent() is None: pathForFile = item.path else: pathForFile = os.path.join(item.path, item.text(0)) pathForFile = "file://%s" % pathForFile #open the correct program to edit Qt UI files! QDesktopServices.openUrl(QUrl(pathForFile, QUrl.TolerantMode))
def _examine_backup(self): error = None try: filename = get_rename_plan_backup_filename() QDesktopServices.openUrl(QUrl.fromLocalFile(filename)) except Exception as err: error = err finally: self._show_backup_decision(error)
def calibration(self): img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono) bitmap = QBitmap.fromImage(img, Qt.MonoOnly) bitmap.fill(Qt.black) self.make_calnoise() img = self.overlay_marks(self.calnoise.scaledToHeight(self.f_size.height()), False, True) self.calibration_pdf(img) QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_calibration_file())) return img
def setupMenuBar(self, menuBar=None): if menuBar is None: try: menuBar = self._menuBar except: return menuBar.resetState() activeWindow = self.activeWindow() fileMenu = menuBar.fetchMenu(Entries.File) # HACK: scripting window has its own New/Open; # figure out how to do this without explicit blacklist. if not isinstance(activeWindow, ScriptingWindow): fileMenu.fetchAction(Entries.File_New, self.newFile) fileMenu.fetchAction(Entries.File_Open, self.openFile) recentFilesMenu = fileMenu.fetchMenu(Entries.File_Open_Recent) self.updateRecentFiles(recentFilesMenu) if not platformSpecific.mergeOpenAndImport(): fileMenu.fetchAction(Entries.File_Import, self.importFile) fileMenu.fetchAction(Entries.File_Save_All, self.saveAll) fileMenu.fetchAction(Entries.File_Exit, self.closeAll) editMenu = menuBar.fetchMenu(Entries.Edit) editMenu.fetchAction(Entries.Edit_Settings, self.settings) scriptsMenu = menuBar.fetchMenu(Entries.Scripts) self.updateExtensions(scriptsMenu) windowMenu = menuBar.fetchMenu(Entries.Window) if platformSpecific.windowCommandsInMenu( ) and activeWindow is not None: windowMenu.fetchAction( Entries.Window_Minimize, activeWindow.showMinimized) windowMenu.fetchAction( Entries.Window_Minimize_All, self.minimizeAll) windowMenu.fetchAction( Entries.Window_Zoom, lambda: self.zoom(activeWindow)) windowMenu.fetchAction(Entries.Window_Inspector, self.inspector) windowMenu.fetchAction(Entries.Window_Scripting, self.scripting) if self.outputWindow is not None: windowMenu.fetchAction( Entries.Window_Output, self.output) # TODO: add a list of open windows in window menu, check active window # maybe add helper function that filters topLevelWidgets into windows # bc we need this in a few places helpMenu = menuBar.fetchMenu(Entries.Help) helpMenu.fetchAction( Entries.Help_Documentation, lambda: QDesktopServices.openUrl( QUrl("http://trufont.github.io/"))) helpMenu.fetchAction( Entries.Help_Report_An_Issue, lambda: QDesktopServices.openUrl( QUrl("https://github.com/trufont/trufont/issues/new"))) helpMenu.addSeparator() helpMenu.fetchAction(Entries.Help_About, self.about)
def open_file(self): """Open the downloaded file.""" assert self.successful filename = self._filename if filename is None: filename = getattr(self.fileobj, 'name', None) if filename is None: log.downloads.error("No filename to open the download!") return url = QUrl.fromLocalFile(filename) QDesktopServices.openUrl(url)
def make_revealer(self): revealer = self.pixelcode_2x2(self.rawnoise) revealer.invertPixels() revealer = QBitmap.fromImage(revealer) revealer = revealer.scaled(self.f_size, Qt.KeepAspectRatio) revealer = self.overlay_marks(revealer) self.filename_prefix = 'revealer_' revealer.save(self.get_path_to_revealer_file('.png')) self.toPdf(QImage(revealer)) QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf')))
def openInternal(self, link): url = link.url() if JEKYLL_BASE_URL in url: fileToOpen = url.replace(JEKYLL_BASE_URL, self.tab.p.jekyll_path) if fileToOpen.endswith('/'): fileToOpen = fileToOpen[:-1] if fileToOpen == self.tab.p.jekyll_path: fileToOpen += '/index' self.tab.p.openFileWrapper(fileToOpen + '.' + QFileInfo(self.tab.fileName).completeSuffix()) else: QDesktopServices.openUrl(link)
def _onMessageActionTriggered(self, message, action): if action == "open_browser": QDesktopServices.openUrl(QUrl(self.getPrintJobsUrl())) if action == "Abort": Logger.log("d", "User aborted sending print to remote.") self._progress_message.hide() self._compressing_print = False if self._reply: self._reply.abort() self._stage = OutputStage.ready Application.getInstance().getController().setActiveStage("PrepareStage")
def acceptNavigationRequest(self, url, type, isMainFrame): if url.isLocalFile(): localFile = url.toLocalFile() if localFile == self.tab.fileName: self.tab.startPendingConversion() return False if self.tab.openSourceFile(localFile): return False if globalSettings.handleWebLinks: return True QDesktopServices.openUrl(url) return False
def saveImage(self): fileName = QFileDialog.getSaveFileName(self, self.tr("Select save location"), "", self.tr("Images (*.png *.jpg *.bmp *.xpm)")) if "" != fileName[0] and os.path.isdir(os.path.dirname(fileName[0])): imgSize = QSize(self.plot.scene().width() * 4, self.plot.scene().height() * 4) img = QImage(imgSize, QImage.Format_ARGB32) img.fill(Qt.transparent) painter = QPainter(img) self.plot.render(painter) img.save(fileName[0]) del painter QDesktopServices.openUrl(QUrl("file:///" + fileName[0], QUrl.TolerantMode))
def _handleLinkClicked(self, url): if url.isLocalFile(): localFile = url.toLocalFile() if localFile == self.tab.fileName and url.hasFragment(): self.page().mainFrame().scrollToAnchor(url.fragment()) return if self.tab.openSourceFile(localFile): return if globalSettings.handleWebLinks: self.load(url) else: QDesktopServices.openUrl(url)
def setupMenuBar(self, menuBar=None): if menuBar is None: try: menuBar = self._menuBar except: return menuBar.resetState() activeWindow = self.activeWindow() # XXX: on local menu bar, entries shouldnt be activated if they werent # fetched by local # in that case, maybe return a parentless action, that isnt added to # the menu fileMenu = menuBar.fetchMenu(Entries.File) fileMenu.fetchAction(Entries.File_New, self.newFile) fileMenu.fetchAction(Entries.File_Open, self.openFile) # TODO: maybe move save in there and add save all and close recentFilesMenu = fileMenu.fetchMenu(Entries.File_Open_Recent) self.updateRecentFiles(recentFilesMenu) fileMenu.fetchAction(Entries.File_Exit, self.exit) scriptsMenu = menuBar.fetchMenu(Entries.Scripts) self.updateExtensions(scriptsMenu) windowMenu = menuBar.fetchMenu(Entries.Window) if platformSpecific.windowCommandsInMenu( ) and activeWindow is not None: windowMenu.fetchAction( Entries.Window_Minimize, activeWindow.showMinimized) windowMenu.fetchAction( Entries.Window_Minimize_All, self.minimizeAll) windowMenu.fetchAction( Entries.Window_Zoom, lambda: self.zoom(activeWindow)) windowMenu.fetchAction(Entries.Window_Inspector, self.inspector) windowMenu.fetchAction(Entries.Window_Scripting, self.scripting) if self.outputWindow is not None: windowMenu.fetchAction( Entries.Window_Output, self.output) # TODO: add a list of open windows in window menu, check active window # maybe add helper function that filters topLevelWidgets into windows # bc we need this in a few places helpMenu = menuBar.fetchMenu(Entries.Help) helpMenu.fetchAction( Entries.Help_Documentation, lambda: QDesktopServices.openUrl( QUrl("http://trufont.github.io/"))) helpMenu.fetchAction( Entries.Help_Report_An_Issue, lambda: QDesktopServices.openUrl( QUrl("https://github.com/trufont/trufont/issues/new"))) helpMenu.addSeparator() helpMenu.fetchAction(Entries.Help_About, self.about)
def help_button_triggered(self): index = self.pluginTree.currentIndex() plugin_info = self.pluginTree.model().data(index, Qt.UserRole) if plugin_info is not None: path = plugin_info.path plugin_type = path.split('/')[-3] suffix = "." + '.'.join(path.split('/')[-2:]) target_url = pc.PAPI_DOC_URL + pc.PAPI_DOC_PREFIX_PLUGIN + "." + plugin_type.lower() + suffix + ".html" QDesktopServices.openUrl(QUrl(target_url, QUrl.TolerantMode))
def open_author_website(self): QDesktopServices.openUrl(QUrl("http://benbridle.com"))
def __init__(self, args): """Constructor. Args: Argument namespace from argparse. """ # pylint: disable=too-many-statements self._quit_status = { 'crash': True, 'tabs': False, 'main': False, } self.geometry = None self._shutting_down = False self._crashdlg = None self._crashlogfile = None if args.debug: # We don't enable this earlier because some imports trigger # warnings (which are not our fault). warnings.simplefilter('default') qt_args = qtutils.get_args(args) log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args)) super().__init__(qt_args) sys.excepthook = self._exception_hook self._args = args objreg.register('args', args) objreg.register('app', self) if self._args.version: print(version.version()) print() print() print(qutebrowser.__copyright__) print() print(version.GPL_BOILERPLATE.strip()) sys.exit(0) sent = ipc.send_to_running_instance(self._args.command) if sent: sys.exit(0) log.init.debug("Starting init...") self.setQuitOnLastWindowClosed(False) self.setOrganizationName("qutebrowser") self.setApplicationName("qutebrowser") self.setApplicationVersion(qutebrowser.__version__) utils.actute_warning() try: self._init_modules() except OSError as e: msgbox = QMessageBox( QMessageBox.Critical, "Error while initializing!", "Error while initializing: {}".format(e)) msgbox.exec_() sys.exit(1) QTimer.singleShot(0, self._open_pages) log.init.debug("Initializing eventfilter...") self._event_filter = modeman.EventFilter(self) self.installEventFilter(self._event_filter) log.init.debug("Connecting signals...") self._connect_signals() log.init.debug("Applying python hacks...") self._python_hacks() log.init.debug("Starting IPC server...") ipc.init() QDesktopServices.setUrlHandler('http', self.open_desktopservices_url) QDesktopServices.setUrlHandler('https', self.open_desktopservices_url) QDesktopServices.setUrlHandler('qute', self.open_desktopservices_url) log.init.debug("Init done!") if self._crashdlg is not None: self._crashdlg.raise_()
def simple_link_handler(url): """Play the file.""" if url.startswith("ankiplay"): play(url[8:]) else: QDesktopServices.openUrl(QUrl(url))
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # save from garbage collection self.windows.append(self) # state self.filename = None self.result = None self.modelDescription = None self.variables = dict() self.selectedVariables = set() self.startValues = dict() self.simulationThread = None # self.progressDialog = None self.plotUpdateTimer = QTimer(self) self.plotUpdateTimer.timeout.connect(self.updatePlotData) self.curves = [] # UI self.ui = Ui_MainWindow() self.ui.setupUi(self) # use a smaller default font size on Mac and Linux if sys.platform in ['darwin', 'linux']: defaultFont = QFont() defaultFont.setPixelSize(11) QApplication.setFont(defaultFont) self.setStyleSheet("QWidget { font-size: 11px; }") self.ui.treeView.setAttribute(Qt.WA_MacShowFocusRect, False) self.ui.tableView.setAttribute(Qt.WA_MacShowFocusRect, False) self.ui.logTreeView.setAttribute(Qt.WA_MacShowFocusRect, False) # set the window size to 85% of the available space geo = QApplication.desktop().availableGeometry() width = min(geo.width() * 0.85, 1100.0) height = min(geo.height() * 0.85, 900.0) self.resize(width, height) # hide the variables self.ui.dockWidget.hide() # toolbar self.stopTimeLineEdit = QLineEdit("1") self.stopTimeLineEdit.setToolTip("Stop time") self.stopTimeLineEdit.setFixedWidth(50) self.stopTimeValidator = QDoubleValidator(self) self.stopTimeValidator.setBottom(0) self.stopTimeLineEdit.setValidator(self.stopTimeValidator) self.ui.toolBar.addWidget(self.stopTimeLineEdit) spacer = QWidget(self) spacer.setFixedWidth(10) self.ui.toolBar.addWidget(spacer) self.fmiTypeComboBox = QComboBox(self) self.fmiTypeComboBox.addItem("Co-Simulation") self.fmiTypeComboBox.setToolTip("FMI type") self.fmiTypeComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.ui.toolBar.addWidget(self.fmiTypeComboBox) # disable widgets self.ui.actionLoadStartValues.setEnabled(False) self.ui.actionReload.setEnabled(False) self.ui.actionSettings.setEnabled(False) self.ui.actionShowLog.setEnabled(False) self.ui.actionShowResults.setEnabled(False) self.ui.actionSimulate.setEnabled(False) self.ui.actionSaveResult.setEnabled(False) self.ui.actionSavePlottedResult.setEnabled(False) self.stopTimeLineEdit.setEnabled(False) self.fmiTypeComboBox.setEnabled(False) # hide the dock's title bar self.ui.dockWidget.setTitleBarWidget(QWidget()) self.ui.dockWidgetContents.setMinimumWidth(500) self.tableModel = VariablesTableModel(self.selectedVariables, self.startValues) self.tableFilterModel = VariablesFilterModel() self.tableFilterModel.setSourceModel(self.tableModel) self.tableFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.tableView.setModel(self.tableFilterModel) self.treeModel = VariablesTreeModel(self.selectedVariables, self.startValues) self.treeFilterModel = VariablesFilterModel() self.treeFilterModel.setSourceModel(self.treeModel) self.treeFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.treeView.setModel(self.treeFilterModel) for i, (w, n) in enumerate(zip(VariablesModel.COLUMN_WIDTHS, VariablesModel.COLUMN_NAMES)): self.ui.treeView.setColumnWidth(i, w) self.ui.tableView.setColumnWidth(i, w) if n in ['Value Reference', 'Initial', 'Causality', 'Variability']: self.ui.treeView.setColumnHidden(i, True) self.ui.tableView.setColumnHidden(i, True) # populate the recent files list settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) recent_files = self.removeDuplicates(recent_files) vbox = QVBoxLayout() if recent_files: added = set() for file in recent_files[:5]: link = QLabel('<a href="%s" style="text-decoration: none">%s</a>' % (file, os.path.basename(file))) link.setToolTip(file) link.linkActivated.connect(self.load) vbox.addWidget(link) added.add(file) self.ui.recentFilesGroupBox.setLayout(vbox) self.ui.recentFilesGroupBox.setVisible(len(recent_files) > 0) # settings page self.inputFileMenu = QMenu() self.inputFileMenu.addAction("New input file...", self.createInputFile) self.inputFileMenu.addSeparator() self.inputFileMenu.addAction("Show in Explorer", self.showInputFileInExplorer) self.inputFileMenu.addAction("Open in default application", self.openInputFile) self.ui.selectInputButton.setMenu(self.inputFileMenu) # log page self.log = Log(self) self.logFilterModel = LogMessagesFilterProxyModel(self) self.logFilterModel.setSourceModel(self.log) self.logFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.logTreeView.setModel(self.logFilterModel) self.ui.clearLogButton.clicked.connect(self.log.clear) self.log.numberOfDebugMessagesChanged.connect(lambda n: self.ui.showDebugMessagesButton.setText(str(n))) self.log.numberOfInfoMessagesChanged.connect(lambda n: self.ui.showInfoMessagesButton.setText(str(n))) self.log.numberOfWarningMessagesChanged.connect(lambda n: self.ui.showWarningMessagesButton.setText(str(n))) self.log.numberOfErrorMessagesChanged.connect(lambda n: self.ui.showErrorMessagesButton.setText(str(n))) self.ui.logFilterLineEdit.textChanged.connect(self.logFilterModel.setFilterFixedString) self.ui.showDebugMessagesButton.toggled.connect(self.logFilterModel.setShowDebugMessages) self.ui.showInfoMessagesButton.toggled.connect(self.logFilterModel.setShowInfoMessages) self.ui.showWarningMessagesButton.toggled.connect(self.logFilterModel.setShowWarningMessages) self.ui.showErrorMessagesButton.toggled.connect(self.logFilterModel.setShowErrorMessages) # context menu self.contextMenu = QMenu() self.actionExpandAll = self.contextMenu.addAction("Expand all") self.actionExpandAll.triggered.connect(self.ui.treeView.expandAll) self.actionCollapseAll = self.contextMenu.addAction("Collapse all") self.actionCollapseAll.triggered.connect(self.ui.treeView.collapseAll) self.contextMenu.addSeparator() self.actionCopyVariableName = self.contextMenu.addAction("Copy Variable Name", self.copyVariableName) self.actionCopyValueReference = self.contextMenu.addAction("Copy Value Reference", self.copyValueReference) self.contextMenu.addSeparator() self.actionEditTable = self.contextMenu.addAction("Edit Table", self.editTable) self.contextMenu.addSeparator() self.columnsMenu = self.contextMenu.addMenu('Columns') for column in ['Value Reference', 'Initial', 'Causality', 'Variability']: action = self.columnsMenu.addAction(column) action.setCheckable(True) action.toggled.connect(lambda show, col=column: self.showColumn(col, show)) # file menu self.ui.actionExit.triggered.connect(QApplication.closeAllWindows) self.ui.actionLoadStartValues.triggered.connect(self.loadStartValues) self.ui.actionReload.triggered.connect(lambda: self.load(self.filename)) self.ui.actionSaveChanges.triggered.connect(self.saveChanges) # help menu self.ui.actionOpenFMI1SpecCS.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v1.0/FMI_for_CoSimulation_v1.0.1.pdf'))) self.ui.actionOpenFMI1SpecME.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v1.0/FMI_for_ModelExchange_v1.0.1.pdf'))) self.ui.actionOpenFMI2Spec.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v2.0/FMI_for_ModelExchange_and_CoSimulation_v2.0.pdf'))) self.ui.actionOpenTestFMUs.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/modelica/fmi-cross-check/tree/master/fmus'))) self.ui.actionOpenWebsite.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/CATIA-Systems/FMPy'))) self.ui.actionShowReleaseNotes.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmpy.readthedocs.io/en/latest/changelog/'))) self.ui.actionCompilePlatformBinary.triggered.connect(self.compilePlatformBinary) self.ui.actionCreateCMakeProject.triggered.connect(self.createCMakeProject) # filter menu self.filterMenu = QMenu() self.filterMenu.addAction(self.ui.actionFilterInputs) self.filterMenu.addAction(self.ui.actionFilterOutputs) self.filterMenu.addAction(self.ui.actionFilterParameters) self.filterMenu.addAction(self.ui.actionFilterCalculatedParameters) self.filterMenu.addAction(self.ui.actionFilterIndependentVariables) self.filterMenu.addAction(self.ui.actionFilterLocalVariables) self.ui.filterToolButton.setMenu(self.filterMenu) # status bar self.statusIconLabel = ClickableLabel(self) self.statusIconLabel.setStyleSheet("QLabel { margin-left: 5px; }") self.statusIconLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.statusBar.addPermanentWidget(self.statusIconLabel) self.statusTextLabel = ClickableLabel(self) self.statusTextLabel.setMinimumWidth(10) self.statusTextLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.statusBar.addPermanentWidget(self.statusTextLabel) self.ui.statusBar.addPermanentWidget(QWidget(self), 1) # spacer self.simulationProgressBar = QProgressBar(self) self.simulationProgressBar.setFixedHeight(18) self.ui.statusBar.addPermanentWidget(self.simulationProgressBar) self.simulationProgressBar.setVisible(False) # connect signals and slots self.ui.actionNewWindow.triggered.connect(self.newWindow) self.ui.openButton.clicked.connect(self.open) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionSaveResult.triggered.connect(self.saveResult) self.ui.actionSavePlottedResult.triggered.connect(lambda: self.saveResult(plotted=True)) self.ui.actionSimulate.triggered.connect(self.startSimulation) self.ui.actionSettings.triggered.connect(lambda: self.setCurrentPage(self.ui.settingsPage)) self.ui.actionShowLog.triggered.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.actionShowResults.triggered.connect(lambda: self.setCurrentPage(self.ui.resultPage)) self.fmiTypeComboBox.currentTextChanged.connect(self.updateSimulationSettings) self.ui.solverComboBox.currentTextChanged.connect(self.updateSimulationSettings) self.variableSelected.connect(self.updatePlotLayout) self.variableDeselected.connect(self.updatePlotLayout) self.tableModel.variableSelected.connect(self.selectVariable) self.tableModel.variableDeselected.connect(self.deselectVariable) self.treeModel.variableSelected.connect(self.selectVariable) self.treeModel.variableDeselected.connect(self.deselectVariable) self.ui.filterLineEdit.textChanged.connect(self.treeFilterModel.setFilterFixedString) self.ui.filterLineEdit.textChanged.connect(self.tableFilterModel.setFilterFixedString) self.ui.filterToolButton.toggled.connect(self.treeFilterModel.setFilterByCausality) self.ui.filterToolButton.toggled.connect(self.tableFilterModel.setFilterByCausality) self.log.currentMessageChanged.connect(self.setStatusMessage) self.ui.selectInputButton.clicked.connect(self.selectInputFile) self.ui.actionShowAboutDialog.triggered.connect(self.showAboutDialog) if os.name == 'nt': self.ui.actionCreateDesktopShortcut.triggered.connect(self.createDesktopShortcut) self.ui.actionAddFileAssociation.triggered.connect(self.addFileAssociation) else: self.ui.actionCreateDesktopShortcut.setEnabled(False) self.ui.actionAddFileAssociation.setEnabled(False) self.ui.tableViewToolButton.toggled.connect(lambda show: self.ui.variablesStackedWidget.setCurrentWidget(self.ui.tablePage if show else self.ui.treePage)) for model in [self.treeFilterModel, self.tableFilterModel]: self.ui.actionFilterInputs.triggered.connect(model.setFilterInputs) self.ui.actionFilterOutputs.triggered.connect(model.setFilterOutputs) self.ui.actionFilterParameters.triggered.connect(model.setFilterParameters) self.ui.actionFilterCalculatedParameters.triggered.connect(model.setFilterCalculatedParameters) self.ui.actionFilterIndependentVariables.triggered.connect(model.setFilterIndependentVariables) self.ui.actionFilterLocalVariables.triggered.connect(model.setFilterLocalVariables) self.ui.treeView.customContextMenuRequested.connect(self.showContextMenu) self.ui.tableView.customContextMenuRequested.connect(self.showContextMenu)
def on_action_add_esi_character(self, checked: bool = False): self._logger.debug('Add ESI Character!') url = QUrl('https://login.eveonline.com/oauth/authorize/?' + esi_get_oauth_request_parameters()) QDesktopServices.openUrl(url)
def releaseInfoConnect(self): QDesktopServices.openUrl(QUrl("http://limelinux.com/limelinux-indir.html"))
def getPageWidget(self, options): page = QWidget(self) layout = QGridLayout(page) for index, option in enumerate(options): displayname, name = option[:2] fileselector = option[2] if len(option) > 2 else False if name is None: header = QLabel('<h3>%s</h3>' % displayname, self) layout.addWidget(header, index, 0, 1, 2, Qt.AlignHCenter) continue if displayname: label = ClickableLabel(displayname + ':', self) if name == 'markdownExtensions': if displayname: url = QUrl( 'https://github.com/retext-project/retext/wiki/Markdown-extensions' ) helpButton = QPushButton(self.tr('Help'), self) helpButton.clicked.connect( lambda: QDesktopServices.openUrl(url)) layout.addWidget(label, index, 0) layout.addWidget(helpButton, index, 1) continue try: extsFile = open(MKD_EXTS_FILE) value = extsFile.read().rstrip().replace( extsFile.newlines, ', ') extsFile.close() except Exception: value = '' self.configurators[name] = QLineEdit(self) self.configurators[name].setText(value) layout.addWidget(self.configurators[name], index, 0, 1, 2) continue value = getattr(globalSettings, name) if name == 'defaultPreviewState': self.configurators[name] = QComboBox(self) self.configurators[name].addItem(self.tr('Editor'), 'editor') self.configurators[name].addItem(self.tr('Live preview'), 'live-preview') self.configurators[name].addItem(self.tr('Normal preview'), 'normal-preview') comboBoxIndex = self.configurators[name].findData(value) self.configurators[name].setCurrentIndex(comboBoxIndex) elif name == 'highlightCurrentLine': self.configurators[name] = QComboBox(self) self.configurators[name].addItem(self.tr('Disabled'), 'disabled') self.configurators[name].addItem(self.tr('Cursor Line'), 'cursor-line') self.configurators[name].addItem(self.tr('Wrapped Line'), 'wrapped-line') comboBoxIndex = self.configurators[name].findData(value) self.configurators[name].setCurrentIndex(comboBoxIndex) elif name == 'orderedListMode': self.configurators[name] = QComboBox(self) self.configurators[name].addItem(self.tr('Increment'), 'increment') self.configurators[name].addItem(self.tr('Repeat'), 'repeat') comboBoxIndex = self.configurators[name].findData(value) self.configurators[name].setCurrentIndex(comboBoxIndex) elif isinstance(value, bool): self.configurators[name] = QCheckBox(self) self.configurators[name].setChecked(value) label.clicked.connect(self.configurators[name].nextCheckState) elif isinstance(value, int): self.configurators[name] = QSpinBox(self) if name == 'tabWidth': self.configurators[name].setRange(1, 10) elif name == 'recentDocumentsCount': self.configurators[name].setRange(5, 20) else: self.configurators[name].setMaximum(200) self.configurators[name].setValue(value) elif isinstance(value, str) and fileselector: self.configurators[name] = FileSelectButton(self, value) elif isinstance(value, str): self.configurators[name] = QLineEdit(self) self.configurators[name].setText(value) layout.addWidget(label, index, 0) layout.addWidget(self.configurators[name], index, 1, Qt.AlignRight) return page
def _export(self, format, ext, open_file=True): filename = escaped_filename(self.titre, ext) new_file = soffice_convert(self.id, format, filename) if open_file: QDesktopServices.openUrl(QUrl.fromLocalFile(str(new_file)))
def _showConfigurationFolder(self): path = Resources.getConfigStoragePath() QDesktopServices.openUrl(QUrl.fromLocalFile( path ))
def on_explore_files(self): for selected_item in self.selected_items: path = os.path.normpath(os.path.join(self.window().tribler_settings['download_defaults']['saveas'], selected_item.download_info["destination"])) QDesktopServices.openUrl(QUrl.fromLocalFile(path))
def openLink(self, link): QDesktopServices.openUrl(QUrl.fromLocalFile(link))
def bugAdressConnect(self): QDesktopServices.openUrl(QUrl("https://github.com/mthnzbk/lilii/issues"))
def open_file(path): return QDesktopServices.openUrl( QUrl.fromLocalFile(QFileInfo(path).absoluteFilePath()))
def _onMessageActionTriggered(self, message, action): if action == "open_folder" and hasattr(message, "_folder"): QDesktopServices.openUrl(QUrl.fromLocalFile(message._folder))
def openPrinterControlPanel(self) -> None: Logger.log("d", "Opening printer control panel...") QDesktopServices.openUrl(QUrl("http://" + self._address + "/printers"))
def _onMessageActionTriggered(self, message, action): if action == "open_browser": QDesktopServices.openUrl(QUrl("http://" + self._address))
def acceptNavigationRequest(self, url, _type, isMainFrame): if _type == QWebEnginePage.NavigationTypeLinkClicked: QDesktopServices.openUrl(url) return False return True
def _open_config_folder(self): QDesktopServices.openUrl( QUrl("file:///" + QDir.toNativeSeparators(cfclient.config_path)))
def open_browser(self, url): page = self.sender() QDesktopServices.openUrl(url) page.deleteLater()
def open_pdf_file_as_shell(self, filePath): QDesktopServices.openUrl(QUrl("file:///" + filePath, QUrl.TolerantMode))
def open_releases_page(self) -> None: QDesktopServices.openUrl(self.updater.latest_release_page)
def _onMessageActionTriggered(self, message, action): if action == "open_browser": QDesktopServices.openUrl(QUrl(self._base_url))
def _onActionTriggered(self, message, action): if action == "download": if self._download_url is not None: QDesktopServices.openUrl(QUrl(self._download_url))
def go_to_wiki(self): """Actions when user clicks on github button. """ url = QUrl('https://github.com/egara/buttermanager/wiki') QDesktopServices.openUrl(url)
def report_issue(self): url = QUrl.fromUserInput( "https://github.com/saf-dmitry/mdviewer/issues") QDesktopServices.openUrl(url)
def openPrinterControlPanel(self) -> None: QDesktopServices.openUrl(QUrl(self.clusterCloudUrl))
def __getFileName(self): """ Private method to get the file name to save to from the user. """ if self.__gettingFileName: return import Helpviewer.HelpWindow downloadDirectory = Helpviewer.HelpWindow.HelpWindow\ .downloadManager().downloadDirectory() if self.__fileName: fileName = self.__fileName originalFileName = self.__originalFileName self.__toDownload = True ask = False else: defaultFileName, originalFileName = \ self.__saveFileName(downloadDirectory) fileName = defaultFileName self.__originalFileName = originalFileName ask = True self.__autoOpen = False if not self.__toDownload: from .DownloadAskActionDialog import DownloadAskActionDialog url = self.__reply.url() dlg = DownloadAskActionDialog( QFileInfo(originalFileName).fileName(), self.__reply.header(QNetworkRequest.ContentTypeHeader), "{0}://{1}".format(url.scheme(), url.authority()), self) if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return if dlg.getAction() == "scan": self.__mainWindow.requestVirusTotalScan(url) self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("VirusTotal scan scheduled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return self.__autoOpen = dlg.getAction() == "open" if PYQT_VERSION_STR >= "5.0.0": from PyQt5.QtCore import QStandardPaths tempLocation = QStandardPaths.storageLocation( QStandardPaths.TempLocation) else: from PyQt5.QtGui import QDesktopServices tempLocation = QDesktopServices.storageLocation( QDesktopServices.TempLocation) fileName = tempLocation + '/' + \ QFileInfo(fileName).completeBaseName() if ask and not self.__autoOpen and self.__requestFilename: self.__gettingFileName = True fileName = E5FileDialog.getSaveFileName(None, self.tr("Save File"), defaultFileName, "") self.__gettingFileName = False if not fileName: self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return fileInfo = QFileInfo(fileName) Helpviewer.HelpWindow.HelpWindow.downloadManager()\ .setDownloadDirectory(fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__output.setFileName(fileName + ".part") self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText( self.tr("Download directory ({0}) couldn't be created."). format(saveDirPath.absolutePath())) return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) if self.__requestFilename: self.__readyRead()
def open_url(url): return QDesktopServices.openUrl(QUrl(url))
def open_url(url): QDesktopServices.openUrl(QUrl(url))
def _openOctoPrint(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None: QDesktopServices.openUrl(QUrl(self._base_url))