def __deleteProject(self): """ Private method to handle the Delete context menu entry. """ itm = self.currentItem() if itm is not None and itm.parent() is not None: projectFile = itm.data(0, MultiProjectBrowser.ProjectFileNameRole) projectPath = os.path.dirname(projectFile) if self.project.getProjectPath() == projectPath: E5MessageBox.warning( self, self.tr("Delete Project"), self.tr("""The current project cannot be deleted.""" """ Please close it first.""")) else: projectFiles = glob.glob(os.path.join(projectPath, "*.e4p")) if not projectFiles: # Oops, that should not happen; play it save res = False elif len(projectFiles) == 1: res = E5MessageBox.yesNo( self, self.tr("Delete Project"), self.tr("""<p>Shall the project <b>{0}</b> (Path:""" """ {1}) really be deleted?</p>""").format( itm.text(0), projectPath)) else: res = E5MessageBox.yesNo( self, self.tr("Delete Project"), self.tr("""<p>Shall the project <b>{0}</b> (Path:""" """ {1}) really be deleted?</p>""" """<p><b>Warning:</b> It contains <b>{2}</b>""" """ sub-projects.</p>""").format( itm.text(0), projectPath, len(projectFiles))) if res: for subprojectFile in projectFiles: # remove all sub-projects before deleting the directory if subprojectFile != projectFile: projectData = { 'name': "", 'file': subprojectFile, 'master': False, 'description': "", 'category': "", 'uid': "", } pitm = self.__findProjectItem(projectData) if pitm: uid = pitm.data( 0, MultiProjectBrowser.ProjectUidRole) if uid: self.multiProject.removeProject(uid) uid = itm.data(0, MultiProjectBrowser.ProjectUidRole) if uid: self.multiProject.deleteProject(uid)
def addSubscriptionFromUrl(self, url): """ Public method to ad an AdBlock subscription given the abp URL. @param url URL to subscribe an AdBlock subscription @type QUrl @return flag indicating success @rtype bool """ if url.path() != "subscribe": return False title = QUrl.fromPercentEncoding( QByteArray(QUrlQuery(url).queryItemValue("title").encode())) if not title: return False res = E5MessageBox.yesNo( None, self.tr("Subscribe?"), self.tr("""<p>Subscribe to this AdBlock subscription?</p>""" """<p>{0}</p>""").format(title)) if res: from .AdBlockSubscription import AdBlockSubscription from WebBrowser.WebBrowserWindow import WebBrowserWindow dlg = WebBrowserWindow.adBlockManager().showDialog() subscription = AdBlockSubscription( url, False, WebBrowserWindow.adBlockManager()) WebBrowserWindow.adBlockManager().addSubscription(subscription) dlg.addSubscription(subscription, False) dlg.setFocus() dlg.raise_() return res
def hgCleanupShelves(self, name): """ Public method to delete all shelves. @param name name of the project directory (string) """ # find the root of the repo repodir = name while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)): repodir = os.path.dirname(repodir) if os.path.splitdrive(repodir)[1] == os.sep: return res = E5MessageBox.yesNo( None, self.tr("Delete all shelves"), self.tr("""Do you really want to delete all shelved changes?""")) if res: args = self.vcs.initCommand("shelve") args.append("--cleanup") dia = HgDialog(self.tr('Delete all shelves'), self.vcs) res = dia.startProcess(args, repodir) if res: dia.exec_()
def __selectPipExecutable(self): """ Private method to select the pip executable to be used. """ pipExecutables = sorted(self.__plugin.getPreferences("PipExecutables")) if pipExecutables: currentExecutable = self.__plugin.getPreferences( "CurrentPipExecutable") try: index = pipExecutables.index(currentExecutable) except ValueError: index = 0 executable, ok = QInputDialog.getItem( None, self.tr("pip Executable"), self.tr("Select pip Executable to be used:"), pipExecutables, index, False) if ok and executable: self.__plugin.setPreferences("CurrentPipExecutable", executable) else: res = E5MessageBox.yesNo( None, self.tr("pip Executable"), self.tr("""No pip executables have been configured yet.""" """ Shall this be done now?"""), yesDefault=True) if res: e5App().getObject("UserInterface").showPreferences("pipPage")
def __showMimeType(self): """ Private slot to show the mime type of the selected entry. """ itmList = self.getSelectedItems() if itmList: mimetype = Utilities.MimeTypes.mimeType(itmList[0].fileName()) if mimetype is None: E5MessageBox.warning( self, self.tr("Show Mime-Type"), self.tr("""The mime type of the file could not be""" """ determined.""")) elif mimetype.split("/")[0] == "text": E5MessageBox.information( self, self.tr("Show Mime-Type"), self.tr("""The file has the mime type <b>{0}</b>."""). format(mimetype)) else: textMimeTypesList = Preferences.getUI("TextMimeTypes") if mimetype in textMimeTypesList: E5MessageBox.information( self, self.tr("Show Mime-Type"), self.tr("""The file has the mime type <b>{0}</b>."""). format(mimetype)) else: ok = E5MessageBox.yesNo( self, self.tr("Show Mime-Type"), self.tr("""The file has the mime type <b>{0}</b>.""" """<br/> Shall it be added to the list of""" """ text mime types?""").format(mimetype)) if ok: textMimeTypesList.append(mimetype) Preferences.setUI("TextMimeTypes", textMimeTypesList)
def on_deleteButton_clicked(self): """ Private slot to delete the selected feed. """ itm = self.feedsTree.selectedItems()[0] title = itm.text(0) res = E5MessageBox.yesNo( self, self.tr("Delete Feed"), self.tr("""<p>Do you really want to delete the feed""" """ <b>{0}</b>?</p>""".format(title))) if res: urlString = itm.data(0, FeedsManager.UrlStringRole) if urlString: feedToDelete = None for feed in self.__feeds: if feed[0] == urlString: feedToDelete = feed break if feedToDelete: self.__feeds.remove(feedToDelete) self.__save() index = self.feedsTree.indexOfTopLevelItem(itm) if index != -1: self.feedsTree.takeTopLevelItem(index) del itm
def on_disconnectSocket(self, lang): """ Private slot called when connection to a client is lost. @param lang client language which connection is lost (str) """ conn = self.connections.pop(lang, None) if conn: conn.close() fx, lng, fn, data = self.runningJob if fx != 'INIT' and lng == lang: self.services[(fx, lng)][3]( fx, lng, fn, self.tr( "Eric's background client disconnected because of an" " unknown reason.")) self.isWorking = None res = E5MessageBox.yesNo( None, self.tr('Background client disconnected.'), self.tr( 'The background client for <b>{0}</b> disconnected because' ' of an unknown reason.<br>Should it be restarted?'). format(lang), yesDefault=True) if res: self.restartService(lang)
def __saveImage(self, fileName): """ Private method to save the snapshot. @param fileName name of the file to save to (string) @return flag indicating success (boolean) """ if QFileInfo(fileName).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Snapshot"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fileName), icon=E5MessageBox.Warning) if not res: return False file = QFile(fileName) if not file.open(QFile.WriteOnly): E5MessageBox.warning( self, self.tr("Save Snapshot"), self.tr("Cannot write file '{0}:\n{1}.").format( fileName, file.errorString())) return False ok = self.__snapshot.save(file) file.close() if not ok: E5MessageBox.warning( self, self.tr("Save Snapshot"), self.tr("Cannot write file '{0}:\n{1}.").format( fileName, file.errorString())) return ok
def __hgQueuePushPopPatches(self, name, operation, all=False, named=False, force=False): """ Private method to push patches onto the stack or pop patches off the stack. @param name file/directory name (string) @param operation operation type to be performed (Queues.POP, Queues.PUSH, Queues.GOTO) @keyparam all flag indicating to push/pop all (boolean) @keyparam named flag indicating to push/pop until a named patch is at the top of the stack (boolean) @keyparam force flag indicating a forceful pop (boolean) """ shouldReopen = self.vcs.getExtensionObject("mq").hgQueuePushPopPatches( name, operation=operation, all=all, named=named, force=force ) if shouldReopen: res = E5MessageBox.yesNo( None, self.tr("Changing Applied Patches"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True, ) if res: self.project.reopenProject()
def on_deleteButton_clicked(self): """ Private slot to delete the selected feed. """ itm = self.feedsTree.selectedItems()[0] title = itm.text(0) res = E5MessageBox.yesNo( self, self.tr("Delete Feed"), self.tr( """<p>Do you really want to delete the feed""" """ <b>{0}</b>?</p>""".format(title))) if res: urlString = itm.data(0, FeedsManager.UrlStringRole) if urlString: feedToDelete = None for feed in self.__feeds: if feed[0] == urlString: feedToDelete = feed break if feedToDelete: self.__feeds.remove(feedToDelete) self.__save() index = self.feedsTree.indexOfTopLevelItem(itm) if index != -1: self.feedsTree.takeTopLevelItem(index) del itm
def __removeSubscription(self): """ Private slot to remove the selected subscription. """ requiresTitles = [] requiresSubscriptions = \ self.__manager.getRequiresSubscriptions(self.__currentSubscription) for subscription in requiresSubscriptions: requiresTitles.append(subscription.title()) if requiresTitles: message = self.tr( "<p>Do you really want to remove subscription" " <b>{0}</b> and all subscriptions requiring it?</p>" "<ul><li>{1}</li></ul>").format( self.__currentSubscription.title(), "</li><li>".join(requiresTitles)) else: message = self.tr("<p>Do you really want to remove subscription" " <b>{0}</b>?</p>").format( self.__currentSubscription.title()) res = E5MessageBox.yesNo(self, self.tr("Remove Subscription"), message) if res: removeSubscription = self.__currentSubscription removeTrees = [self.__currentTreeWidget] for index in range(self.subscriptionsTabWidget.count()): tree = self.subscriptionsTabWidget.widget(index) if tree.subscription() in requiresSubscriptions: removeTrees.append(tree) for tree in removeTrees: self.subscriptionsTabWidget.removeTab( self.subscriptionsTabWidget.indexOf(tree)) self.__manager.removeSubscription(removeSubscription)
def __revertHunkOrLines(self): """ Private method to revert the selected lines or hunk. """ cursor = self.lDiffEdit.textCursor() startIndex, endIndex = self.__selectedLinesIndexes(self.lDiffEdit) if cursor.hasSelection(): title = self.tr("Revert selected lines") else: title = self.tr("Revert hunk") res = E5MessageBox.yesNo( self, title, self.tr("""Are you sure you want to revert the selected""" """ changes?""")) if res: if cursor.hasSelection(): patch = self.lDiffParser.createLinesPatch(startIndex, endIndex, reverse=True) else: patch = self.lDiffParser.createHunkPatch(startIndex) if patch: patchFile = self.__tmpPatchFileName() try: f = open(patchFile, "w") f.write(patch) f.close() self.vcs.gitApply(self.dname, patchFile, reverse=True, noDialog=True) self.on_refreshButton_clicked() finally: os.remove(patchFile)
def on_removeAttributeButton_clicked(self): """ Private slot to remove the selected filter attributes. """ ok = E5MessageBox.yesNo( self, self.tr("Remove Attributes"), self.tr("""Do you really want to remove the selected attributes """ """from the database?""")) if not ok: return items = self.attributesList.selectedItems() for item in items: itm = self.attributesList.takeTopLevelItem( self.attributesList.indexOfTopLevelItem(item)) if itm is None: continue attr = itm.text(0) self.__removedAttributes.append(attr) for filter in self.__filterMap: if attr in self.__filterMap[filter]: self.__filterMap[filter].remove(attr) del itm
def on_defaultSubstylesButton_clicked(self): """ Private slot to reset all substyles to default values. """ style, substyle = self.__currentStyles() ok = E5MessageBox.yesNo( self, self.tr("Reset Sub-Styles to Default"), self.tr("<p>Do you really want to reset all defined sub-styles of" " <b>{0}</b> to the default values?</p>""") .format(self.lexer.description(style, substyle)) ) if ok: # 1. reset sub-styles self.lexer.loadDefaultSubStyles(style) # 2. delete all existing sub-style items parent = self.styleElementList.currentItem() while parent.childCount() > 0: itm = parent.takeChild(0) # __IGNORE_WARNING__ del itm # 3. create the new list of sub-style items for description, _, substyle in self.lexer.getSubStyles(style): itm = QTreeWidgetItem(parent, [description]) itm.setData(0, self.StyleRole, style) itm.setData(0, self.SubstyleRole, substyle) self.__styleOneItem(itm, style, substyle)
def on_saveButton_clicked(self): """ Private slot to handle the Save button press. It saves the diff shown in the dialog to a file in the local filesystem. """ if isinstance(self.filename, list): if len(self.filename) > 1: fname = self.vcs.splitPathList(self.filename)[0] else: dname, fname = self.vcs.splitPath(self.filename[0]) if fname != ".": fname = "{0}.diff".format(self.filename[0]) else: fname = dname else: fname = self.vcs.splitPath(self.filename)[0] fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Diff"), fname, self.tr("Patch Files (*.diff)"), None, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite), ) if not fname: return # user aborted ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Diff"), self.tr("<p>The patch file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning, ) if not res: return fname = Utilities.toNativeSeparators(fname) eol = e5App().getObject("Project").getEolString() try: f = open(fname, "w", encoding="utf-8", newline="") f.write(eol.join(self.contents.toPlainText().splitlines())) f.close() except IOError as why: E5MessageBox.critical( self, self.tr("Save Diff"), self.tr("<p>The patch file <b>{0}</b> could not be saved." "<br>Reason: {1}</p>").format( fname, str(why) ), )
def saveImage(self): """ Public method to handle the save context menu entry. """ fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Diagram"), "", self.tr("Portable Network Graphics (*.png);;" "Scalable Vector Graphics (*.svg)"), "", E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if fname: ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Diagram"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return success = super(UMLGraphicsView, self).saveImage(fname, QFileInfo(fname).suffix().upper()) if not success: E5MessageBox.critical( self, self.tr("Save Diagram"), self.tr( """<p>The file <b>{0}</b> could not be saved.</p>"""). format(fname))
def on_removeAttributeButton_clicked(self): """ Private slot to remove the selected filter attributes. """ ok = E5MessageBox.yesNo( self, self.tr("Remove Attributes"), self.tr( """Do you really want to remove the selected attributes """ """from the database?""")) if not ok: return items = self.attributesList.selectedItems() for item in items: itm = self.attributesList.takeTopLevelItem( self.attributesList.indexOfTopLevelItem(item)) if itm is None: continue attr = itm.text(0) self.__removedAttributes.append(attr) for filter in self.__filterMap: if attr in self.__filterMap[filter]: self.__filterMap[filter].remove(attr) del itm
def __versionCheckResult(self, versions): """ Private method to show the result of the version check action. @param versions contents of the downloaded versions file (list of strings) """ url = "" ui = self.__ui try: # check release version if calc_int_version(versions[0]) > calc_int_version(Version): res = E5MessageBox.yesNo( ui, ui.tr("Update available"), ui.tr("""Pymakr version <b>{0}</b> is now""" """ available at <b>{1}</b>. Would you like""" """ to get it?""").format(versions[0], versions[1]), yesDefault=True) url = res and versions[1] or '' else: if ui.manualUpdatesCheck: E5MessageBox.information( ui, ui.tr("Pymakr is up to date"), ui.tr("""You are using the latest version of""" """ Pymakr""")) except IndexError: E5MessageBox.warning(ui, ui.tr("Error during updates check"), ui.tr("""Could not perform updates check.""")) if url: QDesktopServices.openUrl(QUrl(url))
def shutdown(self): """ Public method to shut down the widget. @return flag indicating successful shutdown (boolean) """ if self.__server: if Preferences.getIrc("AskOnShutdown"): ok = E5MessageBox.yesNo( self, self.tr("Disconnect from Server"), self.tr( """<p>Do you really want to disconnect from""" """ <b>{0}</b>?</p><p>All channels will be closed.""" """</p>""").format(self.__server.getName())) else: ok = True if ok: self.__connectNetwork("", False, True) else: ok = True if ok: self.__ircNetworkManager.close() return ok
def _getFileName(self, filter): """ Protected method to get the file name of the export file from the user. @param filter the filter string to be used (string). The filter for "All Files (*)" is appended by this method. @return file name entered by the user (string) """ filter_ = filter filter_ += ";;" filter_ += QCoreApplication.translate('Exporter', "All Files (*)") fn, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self.editor, self.tr("Export source"), "", filter_, "", E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if fn: ext = QFileInfo(fn).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fn += ex if QFileInfo(fn).exists(): res = E5MessageBox.yesNo( self.editor, self.tr("Export source"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fn), icon=E5MessageBox.Warning) if not res: return "" fn = Utilities.toNativeSeparators(fn) return fn
def __checkUpgradePyQt(self, packages): """ Private method to check, if an upgrade of PyQt packages is attempted. @param packages list of packages to upgrade @type list of str @return flag indicating to abort the upgrade attempt @rtype bool """ pyqtPackages = [ p for p in packages if p.lower() in ["pyqt5", "pyqt5-sip", "pyqtwebengine", "qscintilla", "sip"] ] if bool(pyqtPackages): abort = not E5MessageBox.yesNo( None, self.tr("Upgrade Packages"), self.tr( """You are trying to upgrade PyQt packages. This might""" """ not work for the current instance of Python ({0}).""" """ Do you want to continue?""").format(sys.executable), icon=E5MessageBox.Critical) else: abort = False return abort
def on_deleteButton_clicked(self): """ Private slot to rename the selected identity. """ currentIdentity = self.identitiesCombo.currentText() if currentIdentity == IrcIdentity.DefaultIdentityDisplay: return inUse = False for networkName in self.__manager.getNetworkNames(): inUse = ( self.__manager.getNetwork(networkName).getIdentityName() == currentIdentity) if inUse: break if inUse: msg = self.tr( """This identity is in use. If you remove it, the network""" """ settings using it will fall back to the default""" """ identity. Should it be deleted anyway?""") else: msg = self.tr( """Do you really want to delete all information for""" """ this identity?""") res = E5MessageBox.yesNo( self, self.tr("Delete Identity"), msg, icon=E5MessageBox.Warning) if res: del self.__identities[currentIdentity] self.identitiesCombo.removeItem( self.identitiesCombo.findText(currentIdentity))
def __saveImage(self, fileName): """ Private method to save the snapshot. @param fileName name of the file to save to (string) @return flag indicating success (boolean) """ if QFileInfo(fileName).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Snapshot"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fileName), icon=E5MessageBox.Warning) if not res: return False file = QFile(fileName) if not file.open(QFile.WriteOnly): E5MessageBox.warning( self, self.tr("Save Snapshot"), self.tr("Cannot write file '{0}:\n{1}.") .format(fileName, file.errorString())) return False ok = self.__snapshot.save(file) file.close() if not ok: E5MessageBox.warning( self, self.tr("Save Snapshot"), self.tr("Cannot write file '{0}:\n{1}.") .format(fileName, file.errorString())) return ok
def on_deleteButton_clicked(self): """ Private slot to delete the selected documentation sets. """ yes = E5MessageBox.yesNo( self, self.tr("Delete Documentation Sets"), self.tr("""Shall the selected documentation sets really be""" """ deleted?""")) if yes: for itm in self.documentationList.selectedItems(): if itm.parent is None: # it is a category item, skip it continue category = itm.parent() fileName = itm.data(0, Qt.UserRole) try: os.remove(fileName) except OSError as err: E5MessageBox.warning( self, self.tr("Delete Documentation Sets"), self.tr("""<p>The documentation set <b>{0}</b> could""" """ not be deleted.</p><p>Reason: {1}</p>"""). format(fileName, str(err))) continue category.removeChild(itm) del itm if category.childCount() == 0: self.__deleteCategory(category)
def on_removeButton_clicked(self): """ Private slot to remove the selected filters. """ ok = E5MessageBox.yesNo( self, self.tr("Remove Filters"), self.tr( """Do you really want to remove the selected filters """ """from the database?""")) if not ok: return items = self.filtersList.selectedItems() for item in items: itm = self.filtersList.takeItem(self.filtersList.row(item)) if itm is None: continue del self.__filterMap[itm.text()] self.__removedFilters.append(itm.text()) del itm if self.filtersList.count(): self.filtersList.setCurrentRow( 0, QItemSelectionModel.ClearAndSelect)
def shutdown(self): """ Public method to shut down the widget. @return flag indicating successful shutdown (boolean) """ if self.__server: if Preferences.getIrc("AskOnShutdown"): ok = E5MessageBox.yesNo( self, self.tr("Disconnect from Server"), self.tr( """<p>Do you really want to disconnect from""" """ <b>{0}</b>?</p><p>All channels will be closed.""" """</p>""").format(self.__server.getName())) else: ok = True if ok: self.__socket.blockSignals(True) self.__send("QUIT :" + self.__quitMessage) self.__socket.flush() self.__socket.close() self.__socket.deleteLater() self.__socket = None else: ok = True if ok: self.__ircNetworkManager.close() return ok
def __hgQueuePushPopPatches(self, name, operation, all=False, named=False, force=False): """ Private method to push patches onto the stack or pop patches off the stack. @param name file/directory name (string) @param operation operation type to be performed (Queues.POP, Queues.PUSH, Queues.GOTO) @keyparam all flag indicating to push/pop all (boolean) @keyparam named flag indicating to push/pop until a named patch is at the top of the stack (boolean) @keyparam force flag indicating a forceful pop (boolean) """ shouldReopen = self.vcs.getExtensionObject("mq")\ .hgQueuePushPopPatches(name, operation=operation, all=all, named=named, force=force) if shouldReopen: res = E5MessageBox.yesNo( None, self.tr("Changing Applied Patches"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()
def parsePersistenceData(self, version, data): """ Public method to parse persisted data. @param version version of the data (string) @param data persisted data to be parsed (string) @return flag indicating success (boolean) """ parts = data.split(", ") if len(parts) != 2 or \ not parts[0].startswith("project=") or \ not parts[1].startswith("no_modules="): return False projectFile = parts[0].split("=", 1)[1].strip() if projectFile != self.project.getProjectFile(): res = E5MessageBox.yesNo( None, self.tr("Load Diagram"), self.tr( """<p>The diagram belongs to the project <b>{0}</b>.""" """ Shall this project be opened?</p>""").format( projectFile)) if res: self.project.openProject(projectFile) self.noModules = Utilities.toBool(parts[1].split("=", 1)[1].strip()) self.initialize() return True
def on_deleteButton_clicked(self): """ Private slot to delete the selected entry. """ row = self.groupsList.currentRow() if row < 0: return res = E5MessageBox.yesNo( self, self.tr("Delete tool group entry"), self.tr("""<p>Do you really want to delete the tool group""" """ <b>"{0}"</b>?</p>""") .format(self.groupsList.currentItem().text()), icon=E5MessageBox.Warning) if not res: return if row == self.currentGroup: # set to default group if current group gets deleted self.currentGroup = -1 del self.toolGroups[row] itm = self.groupsList.takeItem(row) del itm if row >= len(self.toolGroups): row -= 1 self.groupsList.setCurrentRow(row) self.on_groupsList_currentRowChanged(row)
def parsePersistenceData(self, version, data): """ Public method to parse persisted data. @param version version of the data (string) @param data persisted data to be parsed (string) @return flag indicating success (boolean) """ parts = data.split(", ") if len(parts) != 2 or \ not parts[0].startswith("project=") or \ not parts[1].startswith("no_modules="): return False projectFile = parts[0].split("=", 1)[1].strip() if projectFile != self.project.getProjectFile(): res = E5MessageBox.yesNo( None, self.tr("Load Diagram"), self.tr("""<p>The diagram belongs to the project <b>{0}</b>.""" """ Shall this project be opened?</p>""").format( projectFile)) if res: self.project.openProject(projectFile) self.noModules = Utilities.toBool(parts[1].split("=", 1)[1].strip()) self.initialize() return True
def on_disconnectSocket(self, lang): """ Private slot called when connection to a client is lost. @param lang client language which connection is lost (str) """ conn = self.connections.pop(lang, None) if conn: conn.close() fx, lng, fn, data = self.runningJob if fx != 'INIT' and lng == lang: self.services[(fx, lng)][3](fx, lng, fn, self.tr( 'Erics background client disconnected because of an' ' unknown reason.') ) self.isWorking = None res = E5MessageBox.yesNo( None, self.tr('Background client disconnected.'), self.tr( 'The background client for <b>{0}</b> disconnect because' ' of an unknown reason.<br>Should it be restarted?' ).format(lang), yesDefault=True) if res: self.restartService(lang)
def setVirtualEnv(self, venvName, venvDirectory, venvInterpreter, venvVariant, isGlobal, isConda, isRemote, execPath): """ Public method to change a virtual environment. @param venvName logical name of the virtual environment @type str @param venvDirectory directory of the virtual environment @type str @param venvInterpreter interpreter of the virtual environment @type str @param venvVariant Python variant of the virtual environment @type int @param isGlobal flag indicating a global environment @type bool @param isConda flag indicating an Anaconda virtual environment @type bool @param isRemote flag indicating a remotely accessed environment @type bool @param execPath search path string to be prepended to the PATH environment variable @type str """ if venvName not in self.__virtualEnvironments: E5MessageBox.yesNo( None, self.tr("Change Virtual Environment"), self.tr("""A virtual environment named <b>{0}</b> does not""" """ exist. Aborting!""").format(venvName), icon=E5MessageBox.Warning) return self.__virtualEnvironments[venvName] = { "path": venvDirectory, "interpreter": venvInterpreter, "variant": venvVariant, "is_global": isGlobal, "is_conda": isConda, "is_remote": isRemote, "exec_path": execPath, } self.__saveSettings() self.virtualEnvironmentChanged.emit(venvName) if self.__virtualenvManagerDialog: self.__virtualenvManagerDialog.refresh()
def __saveScriptToDevice(self, scriptName=""): """ Private method to save the current script onto the connected device. @param scriptName name of the file on the device @type str """ aw = e5App().getObject("ViewManager").activeWindow() if not aw: return if scriptName: title = self.tr("Save Script as '{0}'").format(scriptName) else: title = self.tr("Save Script") if not (aw.isPyFile() or aw.isMicroPythonFile()): yes = E5MessageBox.yesNo( self.microPython, title, self.tr("""The current editor does not contain a Python""" """ script. Write it anyway?""")) if not yes: return script = aw.text().strip() if not script: E5MessageBox.warning(self.microPython, title, self.tr("""The script is empty. Aborting.""")) return if not scriptName: scriptName = os.path.basename(aw.getFileName()) scriptName, ok = QInputDialog.getText( self.microPython, title, self.tr("Enter a file name on the device:"), QLineEdit.Normal, scriptName) if not ok or not bool(scriptName): return title = self.tr("Save Script as '{0}'").format(scriptName) commands = [ "fd = open('{0}', 'wb')".format(scriptName), "f = fd.write", ] for line in script.splitlines(): commands.append("f(" + repr(line + "\n") + ")") commands.append("fd.close()") out, err = self.microPython.commandsInterface().execute(commands) if err: E5MessageBox.critical( self.microPython, title, self.tr("""<p>The script could not be saved to the""" """ device.</p><p>Reason: {0}</p>""").format( err.decode("utf-8"))) # reset the device self.__resetDevice()
def on_saveButton_clicked(self): """ Private slot to handle the Save button press. It saves the diff shown in the dialog to a file in the local filesystem. """ if isinstance(self.__filename, list): if len(self.__filename) > 1: fname = self.vcs.splitPathList(self.__filename)[0] else: dname, fname = self.vcs.splitPath(self.__filename[0]) if fname != '.': fname = "{0}.diff".format(self.__filename[0]) else: fname = dname else: fname = self.vcs.splitPath(self.__filename)[0] fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Diff"), fname, self.tr("Patch Files (*.diff)"), None, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if not fname: return # user aborted ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Diff"), self.tr("<p>The patch file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return fname = Utilities.toNativeSeparators(fname) eol = e5App().getObject("Project").getEolString() try: f = open(fname, "w", encoding="utf-8", newline="") f.write(eol.join(self.contents2.toPlainText().splitlines())) f.write(eol) f.close() except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'), self.tr( '<p>The patch file <b>{0}</b> could not be saved.' '<br>Reason: {1}</p>') .format(fname, str(why)))
def __clearHistoryDialog(self): """ Private slot to clear the history. """ if self.__historyManager is not None and E5MessageBox.yesNo( self, self.tr("Clear History"), self.tr("""Do you want to clear the history?""")): self.__historyManager.clear()
def __saveAs(self, filename=""): """ Private slot to save the diagram. @param filename name of the file to write to (string) """ if not filename: fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Diagram"), "", self.tr("Eric Graphics File (*.e5g);;All Files (*)"), "", E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if not fname: return ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Diagram"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return filename = fname lines = [ "version: 1.0", "diagram_type: {0} ({1})".format( self.__diagramType, self.__diagramTypeString()), "scene_size: {0};{1}".format(self.scene.width(), self.scene.height()), ] persistenceData = self.builder.getPersistenceData() if persistenceData: lines.append("builder_data: {0}".format(persistenceData)) lines.extend(self.umlView.getPersistenceData()) try: f = open(filename, "w", encoding="utf-8") f.write("\n".join(lines)) f.close() except (IOError, OSError) as err: E5MessageBox.critical( self, self.tr("Save Diagram"), self.tr( """<p>The file <b>{0}</b> could not be saved.</p>""" """<p>Reason: {1}</p>""").format(filename, str(err))) return self.__fileName = filename
def on_buttonBox_rejected(self): """ Private slot to handle the rejected signal of the button box. """ res = E5MessageBox.yesNo( self, self.tr("Close dialog"), self.tr("""Do you really want to close the dialog?""")) if res: self.reject()
def __newUiForm(self, path): """ Private slot to handle the New Form menu action for Qt-related projects. @param path full directory path for the new form file (string) """ selectedForm, ok = QInputDialog.getItem(None, self.tr("New Form"), self.tr("Select a form type:"), self.templateTypes4, 0, False) if not ok or not selectedForm: # user pressed cancel return templateIndex = self.templateTypes4.index(selectedForm) templateFile = os.path.join(getConfig('ericTemplatesDir'), self.templates4[templateIndex]) fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("New Form"), path, self.tr("Qt User-Interface Files (*.ui);;All Files (*)"), "", E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if not fname: # user aborted or didn't enter a filename return ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if os.path.exists(fname): res = E5MessageBox.yesNo( self, self.tr("New Form"), self.tr("The file already exists! Overwrite it?"), icon=E5MessageBox.Warning) if not res: # user selected to not overwrite return try: shutil.copy(templateFile, fname) except IOError as e: E5MessageBox.critical( self, self.tr("New Form"), self.tr( "<p>The new form file <b>{0}</b> could not be created.<br>" "Problem: {1}</p>").format(fname, str(e))) return self.project.appendFile(fname) self.designerFile.emit(fname)
def on_removeButton_clicked(self): """ Private slot to remove a document from the help database. """ res = E5MessageBox.yesNo( self, self.tr("Remove Documentation"), self.tr( """Do you really want to remove the selected documentation """ """sets from the database?""")) if not res: return openedDocs = self.__mw.getSourceFileList() items = self.documentsList.selectedItems() for item in items: ns = item.text() if ns in list(openedDocs.values()): res = E5MessageBox.yesNo( self, self.tr("Remove Documentation"), self.tr( """Some documents currently opened reference the """ """documentation you are attempting to remove. """ """Removing the documentation will close those """ """documents. Remove anyway?"""), icon=E5MessageBox.Warning) if not res: return self.__unregisteredDocs.append(ns) for id in openedDocs: if openedDocs[id] == ns and id not in self.__tabsToClose: self.__tabsToClose.append(id) itm = self.documentsList.takeItem(self.documentsList.row(item)) del itm self.__engine.unregisterDocumentation(ns) if self.documentsList.count(): self.documentsList.setCurrentRow( 0, QItemSelectionModel.ClearAndSelect)
def on_saveButton_clicked(self): """ Private slot to handle the Save button press. It saves the diff shown in the dialog to a file in the local filesystem. """ dname, fname = Utilities.splitPath(self.filename2) if fname != '.': fname = "{0}.diff".format(self.filename2) else: fname = dname fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Diff"), fname, self.tr("Patch Files (*.diff)"), None, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if not fname: return ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Diff"), self.tr("<p>The patch file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return fname = Utilities.toNativeSeparators(fname) try: f = open(fname, "w", encoding="utf-8") txt = self.contents.toPlainText() try: f.write(txt) except UnicodeError: pass f.close() except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'), self.tr( '<p>The patch file <b>{0}</b> could not be saved.<br />' 'Reason: {1}</p>').format(fname, str(why)))
def __showApplicationDiagram(self): """ Private method to handle the application diagram context menu action. """ res = E5MessageBox.yesNo( self, self.tr("Application Diagram"), self.tr("""Include module names?"""), yesDefault=True ) from Graphics.UMLDialog import UMLDialog self.applicationDiagram = UMLDialog(UMLDialog.ApplicationDiagram, self.project, self, noModules=not res) self.applicationDiagram.show()
def on_resetButton_clicked(self): """ Private slot to set the default list of mime types. """ ok = E5MessageBox.yesNo( self, self.tr("Reset Mime Types"), self.tr("""Do you really want to reset the configured list of""" """ mime types?"""), ) if ok: self.textMimeTypesList.setList(Preferences.Prefs.uiDefaults["TextMimeTypes"])
def __saveMessages(self): """ Private slot to save the contents of the messages display. """ hasText = not self.messages.document().isEmpty() if hasText: if Utilities.isWindowsPlatform(): htmlExtension = "htm" else: htmlExtension = "html" fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Messages"), "", self.tr( "HTML Files (*.{0});;Text Files (*.txt);;All Files (*)") .format(htmlExtension), None, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if fname: ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex ext = QFileInfo(fname).suffix() if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Messages"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return fname = Utilities.toNativeSeparators(fname) try: if ext.lower() in ["htm", "html"]: txt = self.messages.toHtml() else: txt = self.messages.toPlainText() f = open(fname, "w", encoding="utf-8") f.write(txt) f.close() except IOError as err: E5MessageBox.critical( self, self.tr("Error saving Messages"), self.tr( """<p>The messages contents could not be written""" """ to <b>{0}</b></p><p>Reason: {1}</p>""") .format(fname, str(err)))
def keyPressEvent(self, ev): """ Protected method to handle the user pressing the escape key. @param ev key event (QKeyEvent) """ if ev.key() == Qt.Key_Escape: res = E5MessageBox.yesNo( self, self.tr("Close dialog"), self.tr("""Do you really want to close the dialog?""") ) if not res: self.reject()
def _vcsSwitch(self): """ Protected slot used to switch the local project to another tag/branch. """ shouldReopen = self.vcs.vcsSwitch(self.project.ppath) if shouldReopen: res = E5MessageBox.yesNo( self.parent(), self.tr("Switch"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()
def _vcsUpdate(self): """ Protected slot used to update the local project from the repository. """ shouldReopen = self.vcs.vcsUpdate(self.project.ppath) if shouldReopen: res = E5MessageBox.yesNo( self.parent(), self.tr("Update"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()
def on_saveButton_clicked(self): """ Private slot to save the call trace info to a file. """ if self.callTrace.topLevelItemCount() > 0: fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Call Trace Info"), "", self.tr("Text Files (*.txt);;All Files (*)"), None, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if fname: ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Save Call Trace Info"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return fname = Utilities.toNativeSeparators(fname) try: f = open(fname, "w", encoding="utf-8") itm = self.callTrace.topLevelItem(0) while itm is not None: isCall = itm.data(0, Qt.UserRole) if isCall: call = "->" else: call = "<-" f.write("{0} {1} || {2}\n".format( call, itm.text(1), itm.text(2))) itm = self.callTrace.itemBelow(itm) f.close() except IOError as err: E5MessageBox.critical( self, self.tr("Error saving Call Trace Info"), self.tr("""<p>The call trace info could not""" """ be written to <b>{0}</b></p>""" """<p>Reason: {1}</p>""") .format(fname, str(err)))
def createRequest(self, op, request, outgoingData=None): """ Public method to create a request. @param op the operation to be performed (QNetworkAccessManager.Operation) @param request reference to the request object (QNetworkRequest) @param outgoingData reference to an IODevice containing data to be sent (QIODevice) @return reference to the created reply object (QNetworkReply) """ if op != QNetworkAccessManager.GetOperation: return None url = request.url() if url.path() != "subscribe": return None if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery, QUrl title = QUrl.fromPercentEncoding( QByteArray(QUrlQuery(url).queryItemValue("title").encode())) else: from PyQt5.QtCore import QUrl title = QUrl.fromPercentEncoding( url.encodedQueryItemValue(b"title")) if not title: return None res = E5MessageBox.yesNo( None, self.tr("Subscribe?"), self.tr( """<p>Subscribe to this AdBlock subscription?</p>""" """<p>{0}</p>""").format(title)) if res: from .AdBlockSubscription import AdBlockSubscription import Helpviewer.HelpWindow dlg = Helpviewer.HelpWindow.HelpWindow.adBlockManager()\ .showDialog() subscription = AdBlockSubscription( url, False, Helpviewer.HelpWindow.HelpWindow.adBlockManager()) Helpviewer.HelpWindow.HelpWindow.adBlockManager()\ .addSubscription(subscription) dlg.addSubscription(subscription, False) dlg.setFocus() dlg.raise_() return EmptyNetworkReply(self.parent())
def __hgTransplant(self): """ Private slot used to transplant changesets from another branch. """ shouldReopen = self.vcs.getExtensionObject("transplant")\ .hgTransplant(self.project.getProjectPath()) if shouldReopen: res = E5MessageBox.yesNo( None, self.tr("Transplant Changesets"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()
def __hgTransplantContinue(self): """ Private slot used to continue the last transplant session after repair. """ shouldReopen = self.vcs.getExtensionObject("transplant")\ .hgTransplantContinue(self.project.getProjectPath()) if shouldReopen: res = E5MessageBox.yesNo( None, self.tr("Transplant Changesets (Continue)"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()
def __hgFetch(self): """ Private slot used to fetch changes from a remote repository. """ shouldReopen = self.vcs.getExtensionObject("fetch")\ .hgFetch(self.project.getProjectPath()) if shouldReopen: res = E5MessageBox.yesNo( None, self.tr("Fetch"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()
def __exportCertificate(self, name, cert): """ Private slot to export a certificate. @param name default file name without extension (string) @param cert certificate to be exported (QSslCertificate) """ if cert is not None: fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Export Certificate"), name, self.tr("Certificate File (PEM) (*.pem);;" "Certificate File (DER) (*.der)"), None, E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite), ) if fname: ext = QFileInfo(fname).suffix() if not ext or ext not in ["pem", "der"]: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex if QFileInfo(fname).exists(): res = E5MessageBox.yesNo( self, self.tr("Export Certificate"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning, ) if not res: return f = QFile(fname) if not f.open(QIODevice.WriteOnly): E5MessageBox.critical( self, self.tr("Export Certificate"), self.tr( """<p>The certificate could not be written""" """ to file <b>{0}</b></p><p>Error: {1}</p>""" ).format(fname, f.errorString()), ) return if fname.endswith(".pem"): crt = cert.toPem() else: crt = cert.toDer() f.write(crt) f.close()
def __hgRebaseAbort(self): """ Private slot used to abort the last rebase session. """ shouldReopen = self.vcs.getExtensionObject("rebase")\ .hgRebaseAbort(self.project.getProjectPath()) if shouldReopen: res = E5MessageBox.yesNo( None, self.tr("Rebase Changesets (Abort)"), self.tr("""The project should be reread. Do this now?"""), yesDefault=True) if res: self.project.reopenProject()