def on_diffButton_clicked(self): """ Private slot to handle the Compare button press. """ filename1 = Utilities.toNativeSeparators(self.file1Edit.text()) try: f1 = open(filename1, "r", encoding="utf-8") lines1 = f1.readlines() f1.close() except IOError: E5MessageBox.critical( self, self.tr("Compare Files"), self.tr( """<p>The file <b>{0}</b> could not be read.</p>""") .format(filename1)) return filename2 = Utilities.toNativeSeparators(self.file2Edit.text()) try: f2 = open(filename2, "r", encoding="utf-8") lines2 = f2.readlines() f2.close() except IOError: E5MessageBox.critical( self, self.tr("Compare Files"), self.tr( """<p>The file <b>{0}</b> could not be read.</p>""") .format(filename2)) return self.__compare(lines1, lines2)
def buildWidget(self): """ Public slot to load a UI file. """ if self.__widget: self.__widget.close() self.__layout.removeWidget(self.__widget) del self.__widget self.__widget = None try: self.__widget = uic.loadUi(self.__uiFileName) except Exception: pass if not self.__widget: E5MessageBox.warning( self, self.tr("Load UI File"), self.tr( """<p>The file <b>{0}</b> could not be loaded.</p>""") .format(self.__uiFileName)) self.__valid = False return self.__widget.setParent(self) self.__layout.addWidget(self.__widget) self.__widget.show() self.__valid = True self.adjustSize() self.__timer.stop()
def on_addButton_clicked(self): """ Private slot to add a new idntity. """ name, ok = QInputDialog.getText( self, self.tr("Add Identity"), self.tr("Identity Name:"), QLineEdit.Normal) if ok: if name: if name in self.__identities: E5MessageBox.critical( self, self.tr("Add Identity"), self.tr( """An identity named <b>{0}</b> already exists.""" """ You must provide a different name.""").format( name)) self.on_addButton_clicked() else: identity = IrcIdentity(name) identity.setIdent(Utilities.getUserName()) identity.setRealName(Utilities.getRealName()) self.__identities[name] = identity self.identitiesCombo.addItem(name) self.identitiesCombo.setCurrentIndex( self.identitiesCombo.count() - 1) else: E5MessageBox.critical( self, self.tr("Add Identity"), self.tr("""The identity has to have a name.""")) self.on_addButton_clicked()
def add(self, fileName, setTranslation=True): """ Public method to add a translation to the list. If the translation file (*.qm) has not been loaded yet, it will be loaded automatically. @param fileName name of the translation file to be added (string) @param setTranslation flag indicating, if this should be set as the active translation (boolean) """ if not self.__haveFileName(fileName): ntr = Translation() ntr.fileName = fileName ntr.name = self.__uniqueName(fileName) if ntr.name is None: E5MessageBox.warning( self.parent(), self.tr("Set Translator"), self.tr( """<p>The translation filename <b>{0}</b>""" """ is invalid.</p>""").format(fileName)) return ntr.translator = self.loadTransFile(fileName) if ntr.translator is None: return self.selector.addItem(ntr.name) self.translations.append(ntr) if setTranslation: tr = self.__findFileName(fileName) self.set(tr.name)
def exportBookmarks(self): """ Public method to export the bookmarks. """ fileName, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( None, self.tr("Export Bookmarks"), "eric6_bookmarks.xbel", self.tr("XBEL bookmarks (*.xbel);;" "XBEL bookmarks (*.xml);;" "HTML Bookmarks (*.html)")) if not fileName: return ext = QFileInfo(fileName).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fileName += ex ext = QFileInfo(fileName).suffix() if ext == "html": from .NsHtmlWriter import NsHtmlWriter writer = NsHtmlWriter() else: from .XbelWriter import XbelWriter writer = XbelWriter() if not writer.write(fileName, self.__bookmarkRootNode): E5MessageBox.critical( None, self.tr("Exporting Bookmarks"), self.tr("""Error exporting bookmarks to <b>{0}</b>.""") .format(fileName))
def on_renameButton_clicked(self): """ Private slot to rename the selected identity. """ currentIdentity = self.identitiesCombo.currentText() name, ok = QInputDialog.getText( self, self.tr("Rename Identity"), self.tr("Identity Name:"), QLineEdit.Normal, currentIdentity) if ok and name != currentIdentity: if name: if name in self.__identities: E5MessageBox.critical( self, self.tr("Rename Identity"), self.tr( """An identity named <b>{0}</b> already exists.""" """ You must provide a different name.""").format( name)) self.on_renameButton_clicked() else: del self.__identities[currentIdentity] self.__currentIdentity.setName(name) self.__identities[name] = self.__currentIdentity self.identitiesCombo.setItemText( self.identitiesCombo.currentIndex(), name) else: E5MessageBox.critical( self, self.tr("Copy Identity"), self.tr("""The identity has to have a name.""")) self.on_renameButton_clicked()
def on_caImportButton_clicked(self): """ Private slot to import server certificates. """ certs = self.__importCertificate() if certs: caCerts = self.__getSystemCaCertificates() for cert in certs: if cert in caCerts: if qVersion() >= "5.0.0": commonStr = ", ".join(cert.subjectInfo(QSslCertificate.CommonName)) else: commonStr = cert.subjectInfo(QSslCertificate.CommonName) E5MessageBox.warning( self, self.tr("Import Certificate"), self.tr("""<p>The certificate <b>{0}</b> already exists.""" """ Skipping.</p>""").format( Utilities.decodeString(commonStr) ), ) else: caCerts.append(cert) pems = QByteArray() for cert in caCerts: pems.append(cert.toPem() + "\n") Preferences.Prefs.settings.setValue("Help/SystemCertificates", pems) self.caCertificatesTree.clear() self.__populateCaCertificatesTree() self.__updateDefaultConfiguration()
def writeTemplates(self, filename=None): """ Public method to write the templates data to an XML file (.e4c). @param filename name of a templates file to read (string) @return flag indicating success (boolean) """ if filename is None: filename = os.path.join( Utilities.getConfigDir(), "eric6templates.e4c") f = QFile(filename) ok = f.open(QIODevice.WriteOnly) if not ok: E5MessageBox.critical( self, self.tr("Save templates"), self.tr( "<p>The templates file <b>{0}</b> could not be" " written.</p>") .format(filename)) return False from E5XML.TemplatesWriter import TemplatesWriter TemplatesWriter(f, self).writeXML() f.close() return True
def importShortcuts(fn): """ Module function to import the keyboard shortcuts for the defined E5Actions. @param fn filename of the import file (string) """ # let the plugin manager create on demand plugin objects pm = e5App().getObject("PluginManager") pm.initOnDemandPlugins() f = QFile(fn) if f.open(QIODevice.ReadOnly): from E5XML.ShortcutsReader import ShortcutsReader reader = ShortcutsReader(f) reader.readXML() f.close() if not reader.hasError(): shortcuts = reader.getShortcuts() setActions(shortcuts) saveShortcuts() syncPreferences() else: E5MessageBox.critical( None, QCoreApplication.translate( "Shortcuts", "Import Keyboard Shortcuts"), QCoreApplication.translate( "Shortcuts", "<p>The keyboard shortcuts could not be read from file" " <b>{0}</b>.</p>") .format(fn)) return
def __checkFileFilter(self, filter): """ Private method to check a file filter for validity. @param filter file filter pattern to check (string) @return flag indicating validity (boolean) """ if not self.__showsOpenFilters and \ filter.count("*") != 1: E5MessageBox.critical( self, self.tr("Add File Filter"), self.tr("""A Save File Filter must contain exactly one""" """ wildcard pattern. Yours contains {0}.""") .format(filter.count("*"))) return False if filter.count("*") == 0: E5MessageBox.critical( self, self.tr("Add File Filter"), self.tr("""A File Filter must contain at least one""" """ wildcard pattern.""")) return False return True
def save(self): """ Public method to save the bookmarks. """ if not self.__loaded: return from .XbelWriter import XbelWriter writer = XbelWriter() bookmarkFile = self.getFileName() # save root folder titles in English (i.e. not localized) self.__menu.title = BOOKMARKMENU self.__toolbar.title = BOOKMARKBAR if not writer.write(bookmarkFile, self.__bookmarkRootNode): E5MessageBox.warning( None, self.tr("Saving Bookmarks"), self.tr("""Error saving bookmarks to <b>{0}</b>.""") .format(bookmarkFile)) # restore localized titles self.__menu.title = self.tr(BOOKMARKMENU) self.__toolbar.title = self.tr(BOOKMARKBAR) self.bookmarksSaved.emit()
def readTemplates(self, filename=None): """ Public method to read in the templates file (.e4c). @param filename name of a templates file to read (string) """ if filename is None: filename = os.path.join( Utilities.getConfigDir(), "eric6templates.e4c") if not os.path.exists(filename): return f = QFile(filename) if f.open(QIODevice.ReadOnly): from E5XML.TemplatesReader import TemplatesReader reader = TemplatesReader(f, viewer=self) reader.readXML() f.close() else: E5MessageBox.critical( self, self.tr("Read templates"), self.tr( "<p>The templates file <b>{0}</b> could not be read.</p>") .format(filename))
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(SqlBrowserWidget, self).__init__(parent) self.setupUi(self) self.table.addAction(self.insertRowAction) self.table.addAction(self.deleteRowAction) if len(QSqlDatabase.drivers()) == 0: E5MessageBox.information( self, self.tr("No database drivers found"), self.tr( """This tool requires at least one Qt database driver. """ """Please check the Qt documentation how to build the """ """Qt SQL plugins.""" ), ) self.connections.tableActivated.connect(self.on_connections_tableActivated) self.connections.schemaRequested.connect(self.on_connections_schemaRequested) self.connections.cleared.connect(self.on_connections_cleared) self.statusMessage.emit(self.tr("Ready"))
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 __startProc(self, applName, *applArgs): """ Private method to start an eric6 application. @param applName name of the eric6 application script (string) @param *applArgs variable list of application arguments """ proc = QProcess() applPath = os.path.join(getConfig("ericDir"), applName) args = [] args.append(applPath) for arg in applArgs: args.append(arg) if not os.path.isfile(applPath) or \ not proc.startDetached(sys.executable, args): E5MessageBox.critical( self, self.tr('Process Generation Error'), self.tr( '<p>Could not start the process.<br>' 'Ensure that it is available as <b>{0}</b>.</p>' ).format(applPath), self.tr('OK'))
def findPrev(self): """ Public slot to find the next previous of text. """ if not self.havefound or not self.ui.findtextCombo.currentText(): self.show(self.viewmanager.textForFind()) return self.__findBackwards = True txt = self.ui.findtextCombo.currentText() # This moves any previous occurrence of this statement to the head # of the list and updates the combobox if txt in self.findHistory: self.findHistory.remove(txt) self.findHistory.insert(0, txt) self.ui.findtextCombo.clear() self.ui.findtextCombo.addItems(self.findHistory) self.searchListChanged.emit() ok = self.__findNextPrev(txt, True) if ok: if self.replace: self.ui.replaceButton.setEnabled(True) self.ui.replaceSearchButton.setEnabled(True) else: E5MessageBox.information( self, self.windowTitle(), self.tr("'{0}' was not found.").format(txt))
def exportShortcuts(fn): """ Module function to export the keyboard shortcuts for the defined QActions. @param fn filename of the export file (string) """ # let the plugin manager create on demand plugin objects pm = e5App().getObject("PluginManager") pm.initOnDemandPlugins() f = QFile(fn) if f.open(QIODevice.WriteOnly): from E5XML.ShortcutsWriter import ShortcutsWriter ShortcutsWriter(f).writeXML() f.close() else: E5MessageBox.critical( None, QCoreApplication.translate( "Shortcuts", "Export Keyboard Shortcuts"), QCoreApplication.translate( "Shortcuts", "<p>The keyboard shortcuts could not be written to file" " <b>{0}</b>.</p>") .format(fn))
def hgQueueDeletePatch(self, name): """ Public method to delete a selected unapplied patch. @param name file/directory name (string) """ # find the root of the repo repodir = self.vcs.splitPath(name)[0] 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 args = self.vcs.initCommand("qdelete") patchnames = sorted(self.__getPatchesList(repodir, Queues.UNAPPLIED_LIST)) if patchnames: patch, ok = QInputDialog.getItem( None, self.tr("Select Patch"), self.tr("Select the patch to be deleted:"), patchnames, 0, False) if ok and patch: args.append(patch) dia = HgDialog(self.tr("Delete Patch"), self.vcs) res = dia.startProcess(args, repodir) if res: dia.exec_() else: E5MessageBox.information( None, self.tr("Select Patch"), self.tr("""No patches to select from."""))
def hgQueueGuardsDefine(self, name): """ Public method to define guards for the current or a named patch. @param name file/directory name (string) """ # find the root of the repo repodir = self.vcs.splitPath(name)[0] 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 patchnames = sorted( self.__getPatchesList(repodir, Queues.SERIES_LIST)) if patchnames: from .HgQueuesDefineGuardsDialog import HgQueuesDefineGuardsDialog self.queuesDefineGuardsDialog = HgQueuesDefineGuardsDialog( self.vcs, self, patchnames) self.queuesDefineGuardsDialog.show() self.queuesDefineGuardsDialog.start(name) else: E5MessageBox.information( None, self.tr("Define Guards"), self.tr("""No patches available to define guards for."""))
def addEntry(self, name, description, template, quiet=False): """ Public method to add a template entry to this group. @param name name of the entry (string) @param description description of the entry to add (string) @param template template text of the entry (string) @param quiet flag indicating quiet operation (boolean) """ if name in self.entries: if not quiet: E5MessageBox.critical( None, QCoreApplication.translate("TemplateGroup", "Add Template"), QCoreApplication.translate( "TemplateGroup", """<p>The group <b>{0}</b> already contains a""" """ template named <b>{1}</b>.</p>""") .format(self.name, name)) return self.entries[name] = TemplateEntry(self, name, description, template) if Preferences.getTemplates("AutoOpenGroups") and \ not self.isExpanded(): self.setExpanded(True)
def on_renameButton_clicked(self): """ Private slot to rename a custom toolbar. """ oldName = self.toolbarComboBox.currentText() newName, ok = QInputDialog.getText( self, self.tr("Rename Toolbar"), self.tr("New Toolbar Name:"), QLineEdit.Normal, oldName) if ok and newName: if oldName == newName: return if self.toolbarComboBox.findText(newName) != -1: # toolbar with this name already exists E5MessageBox.critical( self, self.tr("Rename Toolbar"), self.tr( """A toolbar with the name <b>{0}</b> already""" """ exists.""") .format(newName)) return index = self.toolbarComboBox.currentIndex() self.toolbarComboBox.setItemText(index, newName) tbItem = \ self.__toolbarItems[self.toolbarComboBox.itemData(index)] tbItem.title = newName tbItem.isChanged = True
def __printPreviewImage(self): """ Private slot to handle the Print Preview menu action. """ from PyQt5.QtPrintSupport import QPrintPreviewDialog if self.mainWidget is None: E5MessageBox.critical( self, self.tr("Print Preview"), self.tr("""There is no UI file loaded.""")) return settings = Preferences.Prefs.settings printer = QPrinter(QPrinter.HighResolution) printer.setFullPage(True) printerName = Preferences.getPrinter("UIPreviewer/printername") if printerName: printer.setPrinterName(printerName) printer.setPageSize( QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))) printer.setPageOrder( QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))) printer.setOrientation(QPrinter.Orientation( int(settings.value("UIPreviewer/orientation")))) printer.setColorMode( QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))) preview = QPrintPreviewDialog(printer, self) preview.paintRequested.connect(self.__print) preview.exec_()
def on_newButton_clicked(self): """ Private slot to create a new toolbar. """ name, ok = QInputDialog.getText( self, self.tr("New Toolbar"), self.tr("Toolbar Name:"), QLineEdit.Normal) if ok and name: if self.toolbarComboBox.findText(name) != -1: # toolbar with this name already exists E5MessageBox.critical( self, self.tr("New Toolbar"), self.tr( """A toolbar with the name <b>{0}</b> already""" """ exists.""") .format(name)) return tbItem = E5ToolBarItem(None, [], False) tbItem.title = name tbItem.isChanged = True self.__toolbarItems[id(tbItem)] = tbItem self.__toolBarItemToWidgetActionID[id(tbItem)] = [] self.toolbarComboBox.addItem(name, int(id(tbItem))) self.toolbarComboBox.model().sort(0) self.toolbarComboBox.setCurrentIndex( self.toolbarComboBox.findText(name))
def on_namedReferenceButton_clicked(self): """ Private slot to handle the named reference toolbutton. """ # determine cursor position as length into text length = self.regexpTextEdit.textCursor().position() # only present group names that occur before the # current cursor position regex = self.regexpTextEdit.toPlainText()[:length] names = self.namedGroups(regex) if not names: E5MessageBox.information( self, self.tr("Named reference"), self.tr("""No named groups have been defined yet.""")) return groupName, ok = QInputDialog.getItem( self, self.tr("Named reference"), self.tr("Select group name:"), names, 0, True) if ok and groupName: self.__insertString("(?P={0})".format(groupName))
def __importCertificate(self): """ Private method to read a certificate. @return certificates read (list of QSslCertificate) """ fname = E5FileDialog.getOpenFileName( self, self.tr("Import Certificate"), "", self.tr("Certificate Files (*.pem *.crt *.der *.cer *.ca);;" "All Files (*)"), ) if fname: f = QFile(fname) if not f.open(QIODevice.ReadOnly): E5MessageBox.critical( self, self.tr("Export Certificate"), self.tr( """<p>The certificate could not be read from file""" """ <b>{0}</b></p><p>Error: {1}</p>""" ).format(fname, f.errorString()), ) return [] crt = f.readAll() f.close() cert = QSslCertificate.fromData(crt, QSsl.Pem) if not cert: cert = QSslCertificate.fromData(crt, QSsl.Der) return cert return []
def on_changeButton_clicked(self): """ Private slot to change an entry. """ row = self.groupsList.currentRow() if row < 0: return groupName = self.nameEdit.text() if not groupName: E5MessageBox.critical( self, self.tr("Add tool group entry"), self.tr("You have to give a name for the group to add.")) return if len(self.groupsList.findItems( groupName, Qt.MatchFlags(Qt.MatchExactly))): E5MessageBox.critical( self, self.tr("Add tool group entry"), self.tr("An entry for the group name {0} already exists.") .format(groupName)) return self.toolGroups[row][0] = groupName self.groupsList.currentItem().setText(groupName)
def on_bTest_clicked(self): """ Private method to test the selected options. """ if self.rColor.isChecked(): if not self.eColor.currentText(): QColorDialog.getColor() else: coStr = self.eColor.currentText() if coStr.startswith("#"): coStr = "QColor('{0}')".format(coStr) else: coStr = "QColor({0})".format(coStr) try: exec( "from PyQt5.QtCore import Qt;" ' QColorDialog.getColor({0}, None, "{1}")'.format(coStr, self.eTitle.text()) ) except: E5MessageBox.critical( self, self.tr("QColorDialog Wizard Error"), self.tr("""<p>The colour <b>{0}</b> is not valid.</p>""").format(coStr), ) elif self.rRGBA.isChecked(): QColorDialog.getColor( QColor(self.sRed.value(), self.sGreen.value(), self.sBlue.value(), self.sAlpha.value()), None, self.eTitle.text(), QColorDialog.ColorDialogOptions(QColorDialog.ShowAlphaChannel), )
def _selectEntries(self, local=True, filter=None): """ Protected method to select entries based on their VCS status. @param local flag indicating local (i.e. non VCS controlled) file/directory entries should be selected (boolean) @param filter list of classes to check against """ if self.project.vcs is None: return if local: compareString = \ QCoreApplication.translate('ProjectBaseBrowser', "local") else: compareString = self.project.vcs.vcsName() # expand all directories in order to iterate over all entries self._expandAllDirs() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.selectionModel().clear() QApplication.processEvents() # now iterate over all entries startIndex = None endIndex = None selectedEntries = 0 index = self.model().index(0, 0) while index.isValid(): itm = self.model().item(index) if self.wantedItem(itm, filter) and \ compareString == itm.data(1): if startIndex is not None and \ startIndex.parent() != index.parent(): self._setItemRangeSelected(startIndex, endIndex, True) startIndex = None selectedEntries += 1 if startIndex is None: startIndex = index endIndex = index else: if startIndex is not None: self._setItemRangeSelected(startIndex, endIndex, True) startIndex = None index = self.indexBelow(index) if startIndex is not None: self._setItemRangeSelected(startIndex, endIndex, True) QApplication.restoreOverrideCursor() QApplication.processEvents() if selectedEntries == 0: E5MessageBox.information( self, QCoreApplication.translate( 'ProjectBaseBrowser', "Select entries"), QCoreApplication.translate( 'ProjectBaseBrowser', """There were no matching entries found."""))
def set(self, name): """ Public slot to set a translator by name. @param name name (language) of the translator to set (string) """ nTranslator = None if name != noTranslationName: trans = self.__findName(name) if trans is None: E5MessageBox.warning( self.parent(), self.tr("Set Translator"), self.tr( """<p>The translator <b>{0}</b> is not known.</p>""") .format(name)) return nTranslator = trans.translator if nTranslator == self.currentTranslator: return if self.currentTranslator is not None: QApplication.removeTranslator(self.currentTranslator) if nTranslator is not None: QApplication.installTranslator(nTranslator) self.currentTranslator = nTranslator self.selector.blockSignals(True) self.selector.setCurrentIndex(self.selector.findText(name)) self.selector.blockSignals(False) self.translationChanged.emit()
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 __saveStackTrace(self): """ Private slot to save the stack trace info to a file. """ if self.topLevelItemCount() > 0: fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save Call Stack 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 Stack 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.topLevelItem(0) while itm is not None: f.write("{0}\n".format(itm.text(0))) f.write(78 * "=" + "\n") itm = self.itemBelow(itm) f.close() except IOError as err: E5MessageBox.critical( self, self.tr("Error saving Call Stack Info"), self.tr("""<p>The call stack info could not be""" """ written to <b>{0}</b></p>""" """<p>Reason: {1}</p>""").format( fname, str(err)))
def hgQueueFoldUnappliedPatches(self, name): """ Public method to fold patches into the current patch. @param name file/directory name (string) """ # find the root of the repo repodir = self.vcs.splitPath(name)[0] 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 args = self.vcs.initCommand("qfold") patchnames = sorted( self.__getPatchesList(repodir, Queues.UNAPPLIED_LIST, withSummary=True)) if patchnames: from .HgQueuesFoldDialog import HgQueuesFoldDialog dlg = HgQueuesFoldDialog(patchnames) if dlg.exec_() == QDialog.Accepted: message, patchesList = dlg.getData() if message: args.append("--message") args.append(message) if patchesList: args.extend(patchesList) dia = HgDialog(self.tr("Fold Patches"), self.vcs) res = dia.startProcess(args, repodir) if res: dia.exec_() else: E5MessageBox.information( None, self.tr("Fold Patches"), self.tr("""No patches selected.""")) else: E5MessageBox.information( None, self.tr("Fold Patches"), self.tr("""No patches available to be folded."""))
def start(self, fn, versions=None, bundle=None, qdiff=False, refreshable=False): """ Public slot to start the hg diff command. @param fn filename to be diffed (string) @keyparam versions list of versions to be diffed (list of up to 2 strings or None) @keyparam bundle name of a bundle file (string) @keyparam qdiff flag indicating qdiff command shall be used (boolean) @keyparam refreshable flag indicating a refreshable diff (boolean) """ self.refreshButton.setVisible(refreshable) self.errorGroup.hide() self.filename = fn self.contents.clear() self.filesCombo.clear() self.highlighter.regenerateRules() if qdiff: self.setWindowTitle(self.tr("Patch Contents")) self.raise_() self.activateWindow() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) procStarted = self.__diffGenerator.start(fn, versions=versions, bundle=bundle, qdiff=qdiff) if not procStarted: E5MessageBox.critical( self, self.tr('Process Generation Error'), self.tr('The process {0} could not be started. ' 'Ensure, that it is in the search path.').format('hg'))
def on_saveButton_clicked(self): """ Private slot to save the regexp to a file. """ fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Save regular expression"), "", self.tr("RegExp Files (*.rx);;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 regular expression"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fname), icon=E5MessageBox.Warning) if not res: return syntax = self.syntaxCombo.itemData(self.syntaxCombo.currentIndex()) try: f = open( Utilities.toNativeSeparators(fname), "w", encoding="utf-8") f.write("syntax={0}\n".format(syntax)) f.write(self.regexpLineEdit.text()) f.close() except IOError as err: E5MessageBox.information( self, self.tr("Save regular expression"), self.tr("""<p>The regular expression could not""" """ be saved.</p><p>Reason: {0}</p>""") .format(str(err)))
def on_serversImportButton_clicked(self): """ Private slot to import server certificates. """ certs = self.__importCertificate() if certs: server = "*" certificateDict = Globals.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) if server in certificateDict: sCerts = QSslCertificate.fromData(certificateDict[server]) else: sCerts = [] pems = QByteArray() for cert in certs: if cert in sCerts: if qVersion() >= "5.0.0": commonStr = ", ".join( cert.subjectInfo(QSslCertificate.CommonName)) else: commonStr = cert.subjectInfo( QSslCertificate.CommonName) E5MessageBox.warning( self, self.tr("Import Certificate"), self.tr( """<p>The certificate <b>{0}</b> already exists.""" """ Skipping.</p>""").format( Utilities.decodeString(commonStr))) else: pems.append(cert.toPem() + '\n') if server not in certificateDict: certificateDict[server] = QByteArray() certificateDict[server].append(pems) Preferences.Prefs.settings.setValue("Ssl/CaCertificatesDict", certificateDict) self.serversCertificatesTree.clear() self.__populateServerCertificatesTree() self.__updateDefaultConfiguration()
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 startSynchronizedProcess(self, proc, program, arguments, workingDir=None): """ Public method to start a synchroneous process. This method starts a process and waits for its end while still serving the Qt event loop. @param proc process to start (QProcess) @param program path of the executable to start (string) @param arguments list of arguments for the process (list of strings) @param workingDir working directory for the process (string) @return flag indicating normal exit (boolean) """ if proc is None: return False if workingDir: proc.setWorkingDirectory(workingDir) proc.start(program, arguments) procStarted = proc.waitForStarted(5000) if not procStarted: E5MessageBox.critical( None, QCoreApplication.translate( "VersionControl", 'Process Generation Error'), QCoreApplication.translate( "VersionControl", 'The process {0} could not be started. ' 'Ensure, that it is in the search path.' ).format(program)) return False else: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() return ( (proc.exitStatus() == QProcess.NormalExit) and (proc.exitCode() == 0) )
def start(self, arguments): """ Public slot to start the conda command. @param arguments commandline arguments for conda program @type list of str """ self.errorGroup.hide() self.progressLabel.hide() self.progressBar.hide() self.contents.clear() self.errors.clear() self.progressLabel.clear() self.progressBar.setValue(0) self.__bufferedStdout = None self.__json = "--json" in arguments self.__firstProgress = True self.__lastFetchFile = "" self.__statusOk = False self.__result = None self.__logOutput(self.__condaExe + " " + " ".join(arguments) + "\n\n") self.__process = QProcess() self.__process.readyReadStandardOutput.connect(self.__readStdout) self.__process.readyReadStandardError.connect(self.__readStderr) self.__process.finished.connect(self.__finish) self.__process.start(self.__condaExe, arguments) procStarted = self.__process.waitForStarted(5000) if not procStarted: E5MessageBox.critical( self, self.tr("Conda Execution"), self.tr("""The conda executable could not be started. Is it""" """ configured correctly?""")) self.__finish(1, 0) else: self.__logOutput(self.tr("Operation started.\n"))
def on_pathButton_clicked(self): """ Private slot to handle the path selection via a directory selection dialog. """ path = E5FileDialog.getExistingDirectory( self, self.tr("Add Sub-repository"), os.path.join(self.__projectPath, self.pathEdit.text()), E5FileDialog.Options(E5FileDialog.Option(0))) if path: path = Utilities.toNativeSeparators(path) if path.startswith(self.__projectPath + os.sep): path = path.replace(self.__projectPath + os.sep, "") self.pathEdit.setText(path) else: E5MessageBox.critical( self, self.tr("Add Sub-repository"), self.tr("""The sub-repository path must be inside""" """ the project.""")) return
def __importConfigurationPage(self, name): """ Private method to import a configuration page module. @param name name of the configuration page module (string) @return reference to the configuration page module """ modName = "Preferences.ConfigurationPages.{0}".format(name) try: mod = __import__(modName) components = modName.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod except ImportError: E5MessageBox.critical( self, self.tr("Configuration Page Error"), self.tr("""<p>The configuration page <b>{0}</b>""" """ could not be loaded.</p>""").format(name)) return None
def saveRules(self): """ Public method to save the subscription rules. """ fileName = self.rulesFileName() if not fileName: return f = QFile(fileName) if not f.open(QIODevice.ReadWrite | QIODevice.Truncate): E5MessageBox.warning( None, self.tr("Saving subscription rules"), self.tr("""Unable to open adblock file '{0}' for writing."""). format(fileName)) return textStream = QTextStream(f) if not self.__rules or not self.__rules[0].isHeader(): textStream << "[Adblock Plus 1.1.1]\n" for rule in self.__rules: textStream << rule.filter() << "\n"
def on_showUpdateTimeButton_clicked(self): """ Private slot to show the time of the next automatic threat list update. """ nextUpdateDateTime = Preferences.getWebBrowser( "SafeBrowsingUpdateDateTime") if ( not nextUpdateDateTime.isValid() or nextUpdateDateTime <= QDateTime.currentDateTime() ): message = self.tr("The next automatic threat list update will be" " done now.") else: message = self.tr("<p>The next automatic threat list update will" " be done at <b>{0}</b>.</p>").format( nextUpdateDateTime.toString("yyyy-MM-dd, HH:mm:ss")) E5MessageBox.information( self, self.tr("Update Time"), message)
def __commit(self, amend=False): """ Private slot to handle the Commit context menu entry. @param amend flag indicating to perform an amend operation (boolean) """ names = [os.path.join(self.dname, itm.text(self.__pathColumn)) for itm in self.__getCommitableItems()] if not names: E5MessageBox.information( self, self.tr("Commit"), self.tr("""There are no entries selected to be""" """ committed.""")) return if Preferences.getVCS("AutoSaveFiles"): vm = e5App().getObject("ViewManager") for name in names: vm.saveEditor(name) self.vcs.vcsCommit(names, commitAll=False, amend=amend)
def __receiveResponse(self): """ Private method to receive a response from the PyQt5 server. @return response dictionary (dict) """ responseDict = {} if self.__pyqt5Server.waitForReadyRead(10000): data = bytes(self.__pyqt5Server.readAllStandardOutput()) responseStr = data.decode("utf-8") responseDict = json.loads(responseStr) if responseDict["error"]: E5MessageBox.critical( self, self.tr("Communication Error"), self.tr("""<p>The PyQt5 backend reported""" """ an error.</p><p>{0}</p>""") .format(responseDict["error"])) responseDict = {} return responseDict
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 res: self.reject()
def __load(self): """ Private method to load the saved login credentials. """ loginFile = self.getFileName() if not os.path.exists(loginFile): self.__loadNonXml(os.path.splitext(loginFile)[0]) else: from .PasswordReader import PasswordReader reader = PasswordReader() self.__logins, self.__loginForms, self.__never = \ reader.read(loginFile) if reader.error() != QXmlStreamReader.NoError: E5MessageBox.warning( None, self.tr("Loading login data"), self.tr("""Error when loading login data on""" """ line {0}, column {1}:\n{2}""").format( reader.lineNumber(), reader.columnNumber(), reader.errorString())) self.__loaded = True
def __UTPrepared(self, nrTests, exc_type, exc_value): """ Private slot to handle the utPrepared signal. If the unittest suite was loaded successfully, we ask the client to run the test suite. @param nrTests number of tests contained in the test suite (integer) @param exc_type type of exception occured during preparation (string) @param exc_value value of exception occured during preparation (string) """ if nrTests == 0: E5MessageBox.critical( self, self.tr("Unittest"), self.tr("<p>Unable to run test <b>{0}</b>.<br>{1}<br>{2}</p>"). format(self.testName, exc_type, exc_value)) return self.totalTests = nrTests self.__setRunningMode() self.dbs.remoteUTRun()
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 __add(self): """ Private slot to handle the Add context menu entry. """ names = [os.path.join(self.dname, itm.text(self.__pathColumn)) for itm in self.__getUnversionedItems()] if not names: E5MessageBox.information( self, self.tr("Add"), self.tr("""There are no unversioned entries""" """ available/selected.""")) return self.vcs.vcsAdd(names) self.on_refreshButton_clicked() project = e5App().getObject("Project") for name in names: project.getModel().updateVCSStatus(name) self.vcs.checkVCSStatus()
def on_loadButton_clicked(self): """ Private slot to load a regexp from a file. """ fname = E5FileDialog.getOpenFileName( self, self.tr("Load regular expression"), "", self.tr("RegExp Files (*.rx);;All Files (*)")) if fname: try: f = open(Utilities.toNativeSeparators(fname), "r", encoding="utf-8") regexp = f.read() f.close() self.regexpTextEdit.setPlainText(regexp) except IOError as err: E5MessageBox.information( self, self.tr("Save regular expression"), self.tr("""<p>The regular expression could not""" """ be saved.</p><p>Reason: {0}</p>""").format( str(err)))
def __startPluginInstall(self): """ Private slot to start the eric6 plugin installation dialog. """ proc = QProcess() applPath = os.path.join(getConfig("ericDir"), "eric6_plugininstall.py") args = [] args.append(applPath) args += self.cw.getDownloadedPlugins() if not os.path.isfile(applPath) or \ not proc.startDetached(sys.executable, args): E5MessageBox.critical( self, self.tr('Process Generation Error'), self.tr( '<p>Could not start the process.<br>' 'Ensure that it is available as <b>{0}</b>.</p>').format( applPath), self.tr('OK')) self.close()
def __diff(self): """ Private slot to handle the Diff context menu entry. """ names = [ os.path.join(self.dname, itm.text(self.__pathColumn)) for itm in self.__getModifiedItems() ] if not names: E5MessageBox.information( self, self.tr("Differences"), self.tr("""There are no uncommitted changes""" """ available/selected.""")) return if self.diff is None: from .SvnDiffDialog import SvnDiffDialog self.diff = SvnDiffDialog(self.vcs) self.diff.show() QApplication.processEvents() self.diff.start(names, refreshable=True)
def __exportStyles(self, lexers): """ Private method to export the styles of the given lexers. @param lexers list of lexer objects for which to export the styles """ from eric6config import getConfig stylesDir = getConfig("ericStylesDir") fn, selectedFilter = E5FileDialog.getSaveFileNameAndFilter( self, self.tr("Export Highlighting Styles"), stylesDir, self.tr("Highlighting styles file (*.e6h)"), "", E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) if not fn: return ext = QFileInfo(fn).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fn += ex f = QFile(fn) if f.open(QIODevice.WriteOnly): from E5XML.HighlightingStylesWriter import HighlightingStylesWriter HighlightingStylesWriter(f, lexers).writeXML() f.close() else: E5MessageBox.critical( self, self.tr("Export Highlighting Styles"), self.tr( """<p>The highlighting styles could not be exported""" """ to file <b>{0}</b>.</p><p>Reason: {1}</p>""") .format(fn, f.errorString()) )
def start(self, path): """ Public slot to start the list command. @param path name of directory to be listed (string) """ self.activateWindow() dname, fname = self.vcs.splitPath(path) # find the root of the repo repodir = dname 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 args = self.vcs.initCommand("qheader") if self.__hgClient: out, err = self.__hgClient.runcommand(args, output=self.__showOutput, error=self.__showError) if err: self.__showError(err) if out: self.__showOutPut(out) self.__finish() else: self.process.kill() self.process.setWorkingDirectory(repodir) self.process.start('hg', args) procStarted = self.process.waitForStarted(5000) if not procStarted: E5MessageBox.critical( self, self.tr('Process Generation Error'), self.tr( 'The process {0} could not be started. ' 'Ensure, that it is in the search path.').format('hg'))
def on_updateCacheButton_clicked(self): """ Private slot to update the local cache database. """ E5MessageBox.information( self, self.tr("Update Safe Browsing Cache"), self.tr("""Updating the Safe Browsing cache might be a lengthy""" """ operation. Please be patient!""")) QApplication.setOverrideCursor(Qt.WaitCursor) ok, error = self.__manager.updateHashPrefixCache() self.__resetProgress() QApplication.restoreOverrideCursor() if not ok: if error: E5MessageBox.critical( self, self.tr("Update Safe Browsing Cache"), self.tr("""<p>Updating the Safe Browsing cache failed.""" """</p><p>Reason: {0}</p>""").format(error)) else: E5MessageBox.critical( self, self.tr("Update Safe Browsing Cache"), self.tr("""<p>Updating the Safe Browsing cache failed.""" """</p>"""))
def __writeMultiProject(self, fn=None): """ Private method to save the multi project infos to a multi project file. @param fn optional filename of the multi project file to be written. If fn is None, the filename stored in the multi project object is used. This is the 'save' action. If fn is given, this filename is used instead of the one in the multi project object. This is the 'save as' action. @return flag indicating success """ if fn is None: fn = self.pfile f = QFile(fn) if f.open(QIODevice.WriteOnly): from E5XML.MultiProjectWriter import MultiProjectWriter MultiProjectWriter( f, self, os.path.splitext(os.path.basename(fn))[0])\ .writeXML() res = True else: E5MessageBox.critical( self.ui, self.tr("Save multiproject file"), self.tr( "<p>The multiproject file <b>{0}</b> could not be " "written.</p>").format(fn)) res = False if res: self.pfile = os.path.abspath(fn) self.ppath = os.path.abspath(os.path.dirname(fn)) self.name = os.path.splitext(os.path.basename(fn))[0] self.setDirty(False) # insert filename into list of recently opened projects self.__syncRecent() return res
def __printImage(self): """ Private slot to handle the Print Image menu action. """ if self.mainWidget is None: E5MessageBox.critical( self, self.tr("Print Image"), self.tr("""There is no UI file loaded.""")) return settings = Preferences.Prefs.settings printer = QPrinter(QPrinter.HighResolution) printer.setFullPage(True) printerName = Preferences.getPrinter("UIPreviewer/printername") if printerName: printer.setPrinterName(printerName) printer.setPageSize( QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))) printer.setPageOrder( QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))) printer.setOrientation(QPrinter.Orientation( int(settings.value("UIPreviewer/orientation")))) printer.setColorMode( QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QDialog.Accepted: self.statusBar().showMessage(self.tr("Printing the image...")) self.__print(printer) settings.setValue("UIPreviewer/printername", printer.printerName()) settings.setValue("UIPreviewer/pagesize", printer.pageSize()) settings.setValue("UIPreviewer/pageorder", printer.pageOrder()) settings.setValue("UIPreviewer/orientation", printer.orientation()) settings.setValue("UIPreviewer/colormode", printer.colorMode()) self.statusBar().showMessage( self.tr("Image sent to printer..."), 2000)
def on_addButton_clicked(self): """ Private slot to add a new entry. """ menutext = self.menuEdit.text() icon = self.iconPicker.text() executable = self.executablePicker.text() arguments = self.argumentsEdit.text() redirect = self.redirectionModes[self.redirectCombo.currentIndex()][0] if not executable: E5MessageBox.critical( self, self.tr("Add tool entry"), self.tr("You have to set an executable to add to the" " Tools-Menu first.")) return if not menutext: E5MessageBox.critical( self, self.tr("Add tool entry"), self.tr("You have to insert a menuentry text to add the" " selected program to the Tools-Menu first.")) return if not Utilities.isinpath(executable): E5MessageBox.critical( self, self.tr("Add tool entry"), self.tr("The selected file could not be found or" " is not an executable." " Please choose an executable filename.")) return if len( self.toolsList.findItems(menutext, Qt.MatchFlags(Qt.MatchExactly))): E5MessageBox.critical( self, self.tr("Add tool entry"), self.tr("An entry for the menu text {0} already exists."). format(menutext)) return self.toolsList.addItem(menutext) tool = { 'menutext': menutext, 'icon': icon, 'executable': executable, 'arguments': arguments, 'redirect': redirect, } self.toollist.append(tool)
def __compileUIDone(self, exitCode, exitStatus): """ Private slot to handle the finished signal of the pyuic/rbuic process. @param exitCode exit code of the process (integer) @param exitStatus exit status of the process (QProcess.ExitStatus) """ self.compileRunning = False e5App().getObject("ViewManager").enableEditorsCheckFocusIn(True) ui = e5App().getObject("UserInterface") if exitStatus == QProcess.NormalExit and exitCode == 0 and self.buf: ofn = os.path.join(self.project.ppath, self.compiledFile) try: if self.project.useSystemEol(): newline = None else: newline = self.project.getEolString() f = open(ofn, "w", encoding="utf-8", newline=newline) for line in self.buf.splitlines(): f.write(line + "\n") f.close() if self.compiledFile not in self.project.pdata["SOURCES"]: self.project.appendFile(ofn) if not self.noDialog and not ui.notificationsEnabled(): E5MessageBox.information( self, self.tr("Form Compilation"), self.tr("The compilation of the form file" " was successful.")) else: ui.showNotification( UI.PixmapCache.getPixmap("designer48.png"), self.tr("Form Compilation"), self.tr("The compilation of the form file" " was successful.")) self.project.projectFormCompiled.emit(self.compiledFile) except IOError as msg: if not self.noDialog: E5MessageBox.information( self, self.tr("Form Compilation"), self.tr( "<p>The compilation of the form file failed.</p>" "<p>Reason: {0}</p>").format(str(msg))) else: ui.showNotification( UI.PixmapCache.getPixmap("designer48.png"), self.tr("Form Compilation"), self.tr( "<p>The compilation of the form file failed.</p>" "<p>Reason: {0}</p>").format(str(msg))) else: if not self.noDialog: E5MessageBox.information( self, self.tr("Form Compilation"), self.tr("The compilation of the form file failed.")) else: ui.showNotification( UI.PixmapCache.getPixmap("designer48.png"), self.tr("Form Compilation"), self.tr("The compilation of the form file failed.")) self.compileProc = None
def __checkCurrentIdentity(self): """ Private method to check the data for the current identity. @return flag indicating a successful check (boolean) """ if self.nicknamesList.count() == 0: E5MessageBox.critical( self, self.tr("Edit Identity"), self.tr( """The identity must contain at least one nick name.""")) block = self.identitiesCombo.blockSignals(True) identity = self.__currentIdentity.getName() if identity == IrcIdentity.DefaultIdentityName: identity = IrcIdentity.DefaultIdentityDisplay self.identitiesCombo.setCurrentIndex( self.identitiesCombo.findText(identity)) self.identitiesCombo.blockSignals(block) self.identityTabWidget.setCurrentIndex(0) self.nicknameEdit.setFocus() return False if not self.realnameEdit.text(): E5MessageBox.critical( self, self.tr("Edit Identity"), self.tr("""The identity must have a real name.""")) block = self.identitiesCombo.blockSignals(True) identity = self.__currentIdentity.getName() if identity == IrcIdentity.DefaultIdentityName: identity = IrcIdentity.DefaultIdentityDisplay self.identitiesCombo.setCurrentIndex( self.identitiesCombo.findText(identity)) self.identitiesCombo.blockSignals(block) self.identityTabWidget.setCurrentIndex(0) self.realnameEdit.setFocus() return False return True