def __findDuplicates(self, cond, special, showMessage = False, index = QModelIndex()): """ Private method to check, if an entry already exists. @param cond condition to check (string or QString) @param special special condition to check (string or QString) @param showMessage flag indicating a message should be shown, if a duplicate entry is found (boolean) @param index index that should not be considered duplicate (QModelIndex) @return flag indicating a duplicate entry (boolean) """ cond = unicode(cond) special = unicode(special) idx = self.__model.getWatchPointIndex(cond, special) duplicate = idx.isValid() and idx.internalPointer() != index.internalPointer() if showMessage and duplicate: if not special: msg = self.trUtf8("""<p>A watch expression '<b>%1</b>'""" """ already exists.</p>""")\ .arg(Utilities.html_encode(unicode(cond))) else: msg = self.trUtf8("""<p>A watch expression '<b>%1</b>'""" """ for the variable <b>%2</b> already exists.</p>""")\ .arg(special)\ .arg(Utilities.html_encode(unicode(cond))) KQMessageBox.warning(None, self.trUtf8("Watch expression already exists"), msg) return duplicate
def add(self, transFileName, 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 transFileName name of the translation file to be added (string or QString) @param setTranslation flag indicating, if this should be set as the active translation (boolean) """ fileName = QString(transFileName) if not self.__haveFileName(fileName): ntr = Translation() ntr.fileName = fileName ntr.name = self.__uniqueName(fileName) if ntr.name.isNull(): KQMessageBox.warning(None, self.trUtf8("Set Translator"), self.trUtf8("""<p>The translation filename <b>%1</b>""" """ is invalid.</p>""").arg(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 set(self, name): """ Public slot to set a translator by name. @param name name (language) of the translator to set (string or QString) """ name = QString(name) nTranslator = None if name.compare(noTranslationName) != 0: trans = self.__findName(name) if trans is None: KQMessageBox.warning(None, self.trUtf8("Set Translator"), self.trUtf8("""<p>The translator <b>%1</b> is not known.</p>""")\ .arg(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.emit(SIGNAL('translationChanged'))
def start(self, pfn, fn=None): """ Public slot to start the calculation of the profile data. @param pfn basename of the profiling file (string) @param fn file to display the profiling data for (string) """ self.basename = os.path.splitext(pfn)[0] fname = "%s.profile" % self.basename if not os.path.exists(fname): KQMessageBox.warning(None, self.trUtf8("Profile Results"), self.trUtf8("""<p>There is no profiling data""" """ available for <b>%1</b>.</p>""") .arg(pfn)) self.close() return try: f = open(fname, 'rb') self.stats = pickle.load(f) f.close() except (EnvironmentError, pickle.PickleError, EOFError): KQMessageBox.critical(None, self.trUtf8("Loading Profiling Data"), self.trUtf8("""<p>The profiling data could not be""" """ read from file <b>%1</b>.</p>""") .arg(fname)) self.close() return self.file = fn self.__populateLists() self.__finish()
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: pass if not self.__widget: KQMessageBox.warning(None, self.trUtf8("Load UI File"), self.trUtf8("""<p>The file <b>%1</b> could not be loaded.</p>""")\ .arg(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_addInstalledApiFileButton_clicked(self): """ Private slot to add an API file from the list of installed API files for the selected lexer language. """ installedAPIFiles = self.__currentAPI.installedAPIFiles() if len(installedAPIFiles) > 0: installedAPIFilesPath = QFileInfo(installedAPIFiles[0]).path() installedAPIFilesShort = QStringList() for installedAPIFile in installedAPIFiles: installedAPIFilesShort.append(QFileInfo(installedAPIFile).fileName()) file, ok = KQInputDialog.getItem( self, self.trUtf8("Add from installed APIs"), self.trUtf8("Select from the list of installed API files"), installedAPIFilesShort, 0, False, ) if ok: self.apiList.addItem( Utilities.toNativeSeparators(QFileInfo(QDir(installedAPIFilesPath), file).absoluteFilePath()) ) else: KQMessageBox.warning( self, self.trUtf8("Add from installed APIs"), self.trUtf8("""There are no APIs installed yet.""" """ Selection is not available."""), ) self.addInstalledApiFileButton.setEnabled(False)
def __loadRules(self): """ Private method to load the rules of the subscription. """ fileName = self.rulesFileName() f = QFile(fileName) if f.exists(): if not f.open(QIODevice.ReadOnly): KQMessageBox.warning( None, self.trUtf8("Load subscription rules"), self.trUtf8("""Unable to open adblock file '%1' for reading.""").arg(fileName), ) else: textStream = QTextStream(f) header = textStream.readLine(1024) if not header.startsWith("[Adblock"): KQMessageBox.warning( None, self.trUtf8("Load subscription rules"), self.trUtf8("""Adblock file '%1' does not start with [Adblock.""").arg(fileName), ) f.close() f.remove() self.__lastUpdate = QDateTime() else: self.__rules = [] while not textStream.atEnd(): line = textStream.readLine() self.__rules.append(AdBlockRule(line)) self.__populateCache() self.emit(SIGNAL("changed()")) if not self.__lastUpdate.isValid() or self.__lastUpdate.addDays(7) < QDateTime.currentDateTime(): self.updateNow()
def __loadFile(self, fn): """ Private slot to load a ui file. @param fn name of the ui file to be laoded (string or QString) """ if self.mainWidget: self.mainWidget.close() self.previewSV.takeWidget() del self.mainWidget self.mainWidget = None # load the file try: self.mainWidget = uic.loadUi(fn) except: pass if self.mainWidget: self.currentFile = fn self.__updateChildren(self.styleCombo.currentText()) if isinstance(self.mainWidget, QDialog) or \ isinstance(self.mainWidget, QMainWindow): self.mainWidget.show() self.mainWidget.installEventFilter(self) else: self.previewSV.setWidget(self.mainWidget) self.mainWidget.show() else: KQMessageBox.warning(None, self.trUtf8("Load UI File"), self.trUtf8("""<p>The file <b>%1</b> could not be loaded.</p>""")\ .arg(fn)) self.__updateActions()
def __uiStartUp(self): """ Private slot to do some actions after the UI has started and the main loop is up. """ for warning in self.__warnings: KQMessageBox.warning(self, self.trUtf8("SQL Browser startup problem"), warning) if QSqlDatabase.connectionNames().isEmpty(): self.__browser.addConnectionByDialog()
def importBookmarks(self): """ Public method to import bookmarks. """ supportedFormats = QStringList() \ << self.trUtf8("XBEL bookmarks").append(" (*.xbel *.xml)") \ << self.trUtf8("HTML Netscape bookmarks").append(" (*.html *.htm)") fileName = KQFileDialog.getOpenFileName(\ None, self.trUtf8("Import Bookmarks"), QString(), supportedFormats.join(";;"), None) if fileName.isEmpty(): return reader = XbelReader() importRootNode = None if fileName.endsWith(".html"): inFile = QFile(fileName) inFile.open(QIODevice.ReadOnly) if inFile.openMode == QIODevice.NotOpen: KQMessageBox.warning(None, self.trUtf8("Import Bookmarks"), self.trUtf8("""Error opening bookmarks file <b>%1</b>.""")\ .arg(fileName)) return webpage = QWebPage() webpage.mainFrame().setHtml(QString(inFile.readAll())) result = webpage.mainFrame().evaluateJavaScript(extract_js).toByteArray() buffer_ = QBuffer(result) buffer_.open(QIODevice.ReadOnly) importRootNode = reader.read(buffer_) else: importRootNode = reader.read(fileName) if reader.error() != QXmlStreamReader.NoError: KQMessageBox.warning(None, self.trUtf8("Import Bookmarks"), self.trUtf8("""Error when importing bookmarks on line %1, column %2:\n""" """%3""")\ .arg(reader.lineNumber())\ .arg(reader.columnNumber())\ .arg(reader.errorString())) return importRootNode.setType(BookmarkNode.Folder) importRootNode.title = self.trUtf8("Imported %1")\ .arg(QDate.currentDate().toString(Qt.SystemLocaleShortDate)) self.addBookmark(self.menu(), importRootNode)
def addConnectionByDialog(self): """ Public slot to add a database connection via an input dialog. """ dlg = SqlConnectionDialog(self) if dlg.exec_() == QDialog.Accepted: driver, dbName, user, password, host, port = dlg.getData() err = self.addConnection(driver, dbName, user, password, host, port) if err.type() != QSqlError.NoError: KQMessageBox.warning(self, self.trUtf8("Unable to open database"), self.trUtf8("""An error occurred while opening the connection."""))
def __sslErrors(self, reply, errors): """ Private slot to handle SSL errors. @param reply reference to the reply object (QNetworkReply) @param errors list of SSL errors (list of QSslError) """ errorStrings = QStringList() for err in errors: errorStrings.append(err.errorString()) errorString = errorStrings.join('.<br />') ret = KQMessageBox.warning(self, self.trUtf8("SSL Errors"), self.trUtf8("""<p>SSL Errors:</p>""" """<p>%1</p>""" """<p>Do you want to ignore these errors?</p>""")\ .arg(errorString), QMessageBox.StandardButtons(\ QMessageBox.No | \ QMessageBox.Yes), QMessageBox.No) if ret == QMessageBox.Yes: reply.ignoreSslErrors() else: self.__downloadCancelled = True reply.abort()
def on_deleteButton_clicked(self): """ Private slot to delete the selected entry. """ row = self.groupsList.currentRow() if row < 0: return res = KQMessageBox.warning(None, self.trUtf8("Delete tool group entry"), self.trUtf8("""<p>Do you really want to delete the tool group""" """ <b>"%1"</b>?</p>""")\ .arg(self.groupsList.currentItem().text()), QMessageBox.StandardButtons(\ QMessageBox.No | \ QMessageBox.Yes), QMessageBox.No) if res != QMessageBox.Yes: 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 loadTransFile(self, transFileName): """ Public slot to load a translation file. @param transFileName file name of the translation file (string or QString) @return reference to the new translator object (QTranslator) """ tr = QTranslator() if tr.load(transFileName): return tr KQMessageBox.warning(None, self.trUtf8("Load Translator"), self.trUtf8("""<p>The translation file <b>%1</b> could not be loaded.</p>""")\ .arg(transFileName)) return None
def __downloadFileDone(self): """ Private method called, after the file has been downloaded from the internet. """ self.__updateButton.setEnabled(True) self.__downloadCancelButton.setEnabled(False) self.statusLabel.setText(" ") ok = True reply = self.sender() if reply in self.__replies: self.__replies.remove(reply) if reply.error() != QNetworkReply.NoError: ok = False if not self.__downloadCancelled: KQMessageBox.warning(None, self.trUtf8("Error downloading file"), self.trUtf8( """<p>Could not download the requested file from %1.</p>""" """<p>Error: %2</p>""" ).arg(self.__downloadURL).arg(reply.errorString()) ) self.downloadProgress.setValue(0) self.__downloadURL = None self.__downloadIODevice.remove() self.__downloadIODevice = None if self.repositoryList.topLevelItemCount(): if self.repositoryList.currentItem() is None: self.repositoryList.setCurrentItem(\ self.repositoryList.topLevelItem(0)) else: self.__downloadButton.setEnabled(len(self.__selectedItems())) return self.__downloadIODevice.open(QIODevice.WriteOnly) self.__downloadIODevice.write(reply.readAll()) self.__downloadIODevice.close() if QFile.exists(self.__downloadFileName): QFile.remove(self.__downloadFileName) self.__downloadIODevice.rename(self.__downloadFileName) self.__downloadIODevice = None self.__downloadURL = None if self.__doneMethod is not None: self.__doneMethod(ok, self.__downloadFileName)
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 type(self.filename) is types.ListType: if len(self.filename) > 1: fname = self.vcs.splitPathList(self.filename)[0] else: dname, fname = self.vcs.splitPath(self.filename[0]) if fname != '.': fname = "%s.diff" % self.filename[0] else: fname = dname else: fname = self.vcs.splitPath(self.filename)[0] selectedFilter = QString("") fname = KQFileDialog.getSaveFileName(\ self, self.trUtf8("Save Diff"), fname, self.trUtf8("Patch Files (*.diff)"), selectedFilter, QFileDialog.Options(QFileDialog.DontConfirmOverwrite)) if fname.isEmpty(): return ext = QFileInfo(fname).suffix() if ext.isEmpty(): ex = selectedFilter.section('(*',1,1).section(')',0,0) if not ex.isEmpty(): fname.append(ex) if QFileInfo(fname).exists(): res = KQMessageBox.warning(self, self.trUtf8("Save Diff"), self.trUtf8("<p>The patch file <b>%1</b> already exists.</p>") .arg(fname), QMessageBox.StandardButtons(\ QMessageBox.Abort | \ QMessageBox.Save), QMessageBox.Abort) if res != QMessageBox.Save: return fname = unicode(Utilities.toNativeSeparators(fname)) try: f = open(fname, "wb") f.write(unicode(self.contents.toPlainText())) f.close() except IOError, why: KQMessageBox.critical(self, self.trUtf8('Save Diff'), self.trUtf8('<p>The patch file <b>%1</b> could not be saved.' '<br>Reason: %2</p>') .arg(unicode(fname)).arg(str(why)))
def __showPixmap(self, filename): """ Private method to show a file. @param filename name of the file to be shown (string or QString) @return flag indicating success """ image = QImage(filename) if image.isNull(): KQMessageBox.warning(self, self.trUtf8("Pixmap-Viewer"), self.trUtf8("""<p>The file <b>%1</b> cannot be displayed.""" """ The format is not supported.</p>""").arg(filename)) return False self.pixmapLabel.setPixmap(QPixmap.fromImage(image)) self.pixmapLabel.adjustSize() return True
def saveRules(self): """ Public method to save the subscription rules. """ fileName = self.rulesFileName() if fileName.isEmpty(): return f = QFile(fileName) if not f.open(QIODevice.ReadWrite | QIODevice.Truncate): KQMessageBox.warning( None, self.trUtf8("Saving subscription rules"), self.trUtf8("""Unable to open adblock file '%1' for writing.""").arg(fileName), ) return textStream = QTextStream(f) textStream << QString("[Adblock Plus 0.7.1]\n") for rule in self.__rules: textStream << rule.filter() << "\n"
def save(self): """ Public method to save the bookmarks. """ if not self.__loaded: return writer = XbelWriter() bookmarkFile = os.path.join(Utilities.getConfigDir(), "browser", "bookmarks.xbel") # 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): KQMessageBox.warning(None, self.trUtf8("Saving Bookmarks"), self.trUtf8("""Error saving bookmarks to <b>%1</b>.""").arg(bookmarkFile)) # restore localized titles self.__menu.title = self.trUtf8(BOOKMARKMENU) self.__toolbar.title = self.trUtf8(BOOKMARKBAR)
def changeGroup(self, oldname, newname, language = "All"): """ Public method to rename a group. @param oldname old name of the group (string or QString) @param newname new name of the group (string or QString) @param language programming language for the group (string or QString) """ if oldname != newname: if self.groups.has_key(newname): KQMessageBox.warning(self, self.trUtf8("Edit Template Group"), self.trUtf8("""<p>A template group with the name""" """ <b>%1</b> already exists.</p>""")\ .arg(newname)) return self.groups[newname] = self.groups[oldname] del self.groups[oldname] self.groups[newname].setName(newname) self.groups[newname].setLanguage(language) self.__resort()
def saveMultiProjectAs(self): """ Public slot to save the current multi project to a different file. @return flag indicating success """ if Preferences.getProject("CompressedProjectFiles"): selectedFilter = self.trUtf8("Compressed Multiproject Files (*.e4mz)") else: selectedFilter = self.trUtf8("Multiproject Files (*.e4m)") if self.ppath: defaultPath = self.ppath else: defaultPath = Preferences.getMultiProject("Workspace") or \ Utilities.getHomeDir() fn = KQFileDialog.getSaveFileName(\ self.parent(), self.trUtf8("Save multiproject as"), defaultPath, self.trUtf8("Multiproject Files (*.e4m);;" "Compressed Multiproject Files (*.e4mz)"), selectedFilter, QFileDialog.Options(QFileDialog.DontConfirmOverwrite)) if not fn.isEmpty(): ext = QFileInfo(fn).suffix() if ext.isEmpty(): ex = selectedFilter.section('(*', 1, 1).section(')', 0, 0) if not ex.isEmpty(): fn.append(ex) if QFileInfo(fn).exists(): res = KQMessageBox.warning(None, self.trUtf8("Save File"), self.trUtf8("""<p>The file <b>%1</b> already exists.</p>""") .arg(fn), QMessageBox.StandardButtons(\ QMessageBox.Abort | \ QMessageBox.Save), QMessageBox.Abort) if res != QMessageBox.Save: return False self.name = unicode(QFileInfo(fn).baseName()) ok = self.__writeMultiProject(unicode(fn)) self.emit(SIGNAL('multiProjectClosed')) self.emit(SIGNAL('multiProjectOpened')) return True else: return False
def loadWidget(self, uiFileName): """ Public slot to load a UI file. @param uiFileName name of the UI file to load (string or QString) """ wview = self.__findWidget(uiFileName) if wview is None: name = _filename(uiFileName) if name.isEmpty(): KQMessageBox.warning(None, self.trUtf8("Load UI File"), self.trUtf8("""<p>The file <b>%1</b> could not be loaded.</p>""")\ .arg(uiFileName)) return uname = QString(name) cnt = 1 while self.findChild(WidgetView, uname) is not None: cnt += 1 uname = QString("%1 <%2>").arg(name).arg(cnt) name = QString(uname) wview = WidgetView(uiFileName, self, name) wview.buildWidget() if not wview.isValid(): del wview return self.connect(self, SIGNAL("rebuildWidgets"), wview.buildWidget) wview.installEventFilter(self) self.addWindow(wview) self.widgets.append(wview) wview.showNormal()
def on_addButton_clicked(self): """ Private slot to add documents to the help database. """ fileNames = KQFileDialog.getOpenFileNames(\ self, self.trUtf8("Add Documentation"), QString(), self.trUtf8("Qt Compressed Help Files (*.qch)"), None) if fileNames.isEmpty(): return for fileName in fileNames: ns = QHelpEngineCore.namespaceName(fileName) if ns.isEmpty(): KQMessageBox.warning(self, self.trUtf8("Add Documentation"), self.trUtf8("""The file <b>%1</b> is not a valid Qt Help File.""")\ .arg(fileName) ) continue if len(self.documentsList.findItems(ns, Qt.MatchFixedString)): KQMessageBox.warning(self, self.trUtf8("Add Documentation"), self.trUtf8("""The namespace <b>%1</b> is already registered.""")\ .arg(ns) ) continue self.__engine.registerDocumentation(fileName) self.documentsList.addItem(ns) self.__registeredDocs.append(ns) if ns in self.__unregisteredDocs: self.__unregisteredDocs.remove(ns)
def __rulesDownloaded(self): """ Private slot to deal with the downloaded rules. """ reply = self.sender() response = reply.readAll() redirect = reply.attribute(QNetworkRequest.RedirectionTargetAttribute).toUrl() reply.close() self.__downloading = None if reply.error() != QNetworkReply.NoError: if not self.__defaultSubscription: # don't show error if we try to load the default KQMessageBox.warning( None, self.trUtf8("Downloading subscription rules"), self.trUtf8("""<p>Subscription rules could not be downloaded.</p>""" """<p>Error: %1</p>""").arg( reply.errorString() ), ) else: # reset after first download attempt self.__defaultSubscription = False return if redirect.isValid(): request = QNetworkRequest(redirect) self.__downloading = Helpviewer.HelpWindow.HelpWindow.networkAccessManager().get(request) self.connect(self.__downloading, SIGNAL("finished()"), self.__rulesDownloaded) return if response.isEmpty(): KQMessageBox.warning( None, self.trUtf8("Downloading subscription rules"), self.trUtf8("""Got empty subscription rules.""") ) return fileName = self.rulesFileName() f = QFile(fileName) if not f.open(QIODevice.ReadWrite): KQMessageBox.warning( None, self.trUtf8("Downloading subscription rules"), self.trUtf8("""Unable to open adblock file '%1' for writing.""").arg(fileName), ) return f.write(response) self.__lastUpdate = QDateTime.currentDateTime() self.__loadRules() self.emit(SIGNAL("changed()")) self.__downloading = None
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 (QString). The filter for "All Files (*)" is appended by this method. """ filter_ = QString() filter_.append(QApplication.translate("Exporter", "All Files (*)")) selectedFilter = QString(filter) fn = KQFileDialog.getSaveFileName( self.editor, self.trUtf8("Export source"), QString(), filter_, selectedFilter, QFileDialog.Options(QFileDialog.DontConfirmOverwrite), ) if not fn.isEmpty(): ext = QFileInfo(fn).suffix() if ext.isEmpty(): ex = selectedFilter.section("(*", 1, 1).section(")", 0, 0) if not ex.isEmpty(): fn.append(ex) if QFileInfo(fn).exists(): res = KQMessageBox.warning( self.editor, self.trUtf8("Export source"), self.trUtf8("<p>The file <b>%1</b> already exists.</p>").arg(fn), QMessageBox.StandardButtons(QMessageBox.Abort | QMessageBox.Save), QMessageBox.Abort, ) if res == QMessageBox.Abort or res == QMessageBox.Cancel: return QString() fn = Utilities.toNativeSeparators(fn) return fn
def on_saveButton_clicked(self): """ Private slot to save the regexp to a file. """ selectedFilter = QString("") fname = KQFileDialog.getSaveFileName(\ self, self.trUtf8("Save regular expression"), QString(), self.trUtf8("RegExp Files (*.rx);;All Files (*)"), selectedFilter, QFileDialog.Options(QFileDialog.DontConfirmOverwrite)) if not fname.isEmpty(): ext = QFileInfo(fname).suffix() if ext.isEmpty(): ex = selectedFilter.section('(*', 1, 1).section(')', 0, 0) if not ex.isEmpty(): fname.append(ex) if QFileInfo(fname).exists(): res = KQMessageBox.warning(self, self.trUtf8("Save regular expression"), self.trUtf8("<p>The file <b>%1</b> already exists.</p>") .arg(fname), QMessageBox.StandardButtons(\ QMessageBox.Abort | \ QMessageBox.Save), QMessageBox.Abort) if res == QMessageBox.Abort or res == QMessageBox.Cancel: return try: f=open(unicode(Utilities.toNativeSeparators(fname)), "wb") f.write(unicode(self.regexpLineEdit.text())) f.close() except IOError, err: KQMessageBox.information(self, self.trUtf8("Save regular expression"), self.trUtf8("""<p>The regular expression could not be saved.</p>""" """<p>Reason: %1</p>""").arg(str(err)))
def _vcsRemove(self): """ Protected slot used to remove the local project from the repository. Depending on the parameters set in the vcs object the project may be removed from the local disk as well. """ res = KQMessageBox.warning(None, self.trUtf8("Remove project from repository"), self.trUtf8("Dou you really want to remove this project from" " the repository (and disk)?"), QMessageBox.StandardButtons(\ QMessageBox.No | \ QMessageBox.Yes), QMessageBox.No) if res == QMessageBox.Yes: self.vcs.vcsRemove(self.project.ppath, True) self._vcsCommit() if not os.path.exists(self.project.pfile): ppath = self.project.ppath self.setDirty(False) self.project.closeProject() shutil.rmtree(ppath, True)
def __saveImage(self): """ Private method to handle the save context menu entry. """ selectedFilter = QString('') fname = KQFileDialog.getSaveFileName(\ self, self.trUtf8("Save Diagram"), QString(), self.trUtf8("Portable Network Graphics (*.png);;" "Scalable Vector Graphics (*.svg)"), selectedFilter, QFileDialog.Options(QFileDialog.DontConfirmOverwrite)) if not fname.isEmpty(): ext = QFileInfo(fname).suffix() if ext.isEmpty(): ex = selectedFilter.section('(*',1,1).section(')',0,0) if not ex.isEmpty(): fname.append(ex) if QFileInfo(fname).exists(): res = KQMessageBox.warning(self, self.trUtf8("Save Diagram"), self.trUtf8("<p>The file <b>%1</b> already exists.</p>") .arg(fname), QMessageBox.StandardButtons(\ QMessageBox.Abort | \ QMessageBox.Save), QMessageBox.Abort) if res == QMessageBox.Abort or res == QMessageBox.Cancel: return success = self.saveImage(fname, QFileInfo(fname).suffix().toUpper()) if not success: KQMessageBox.critical(None, self.trUtf8("Save Diagram"), self.trUtf8("""<p>The file <b>%1</b> could not be saved.</p>""") .arg(fname))
def checkDirty(self): """ Public method to check the dirty status and open a message window. @return flag indicating whether this operation was successful """ if self.isDirty(): res = KQMessageBox.warning(self.parent(), self.trUtf8("Close Multiproject"), self.trUtf8("The current multiproject has unsaved changes."), QMessageBox.StandardButtons(\ QMessageBox.Abort | \ QMessageBox.Discard | \ QMessageBox.Save), QMessageBox.Save) if res == QMessageBox.Save: return self.saveMultiProject() elif res == QMessageBox.Discard: self.setDirty(False) return True elif res == QMessageBox.Abort: return False return True
def editPaste(self, pasting = False): """ Public slot to paste an image from the clipboard. @param pasting flag indicating part two of the paste operation (boolean) """ img, ok = self.__clipboardImage() if ok: if img.width() > self.__image.width() or img.height() > self.__image.height(): res = KQMessageBox.question(self, self.trUtf8("Paste"), self.trUtf8("""<p>The clipboard image is larger than the current """ """image.<br/>Paste as new image?</p>"""), QMessageBox.StandardButtons(\ QMessageBox.No | \ QMessageBox.Yes), QMessageBox.No) if res == QMessageBox.Yes: self.editPasteAsNew() return elif not pasting: self.__isPasting = True self.__clipboardSize = img.size() else: cmd = IconEditCommand(self, self.trUtf8("Paste Clipboard"), self.__image) self.__markImage.fill(self.NoMarkColor.rgba()) for sx in range(self.__pasteRect.width() + 1): for sy in range(self.__pasteRect.height() + 1): dx = self.__pasteRect.x() + sx dy = self.__pasteRect.y() + sy if True: # TODO: insert code to test for compositing # Porter-Duff Over composition colorS = img.pixel(sx, sy) colorD = self.__image.pixel(dx, dy) alphaS = qAlpha(colorS) / 255.0 alphaD = qAlpha(colorD) / 255.0 r = qRed(colorS) * alphaS + \ (1 - alphaS) * qRed(colorD) * alphaD g = qGreen(colorS) * alphaS + \ (1 - alphaS) * qGreen(colorD) * alphaD b = qBlue(colorS) * alphaS + \ (1 - alphaS) * qBlue(colorD) * alphaD a = alphaS + \ (1 - alphaS) * alphaD # Remove multiplication by alpha if a > 0: r /= a g /= a b /= a else: r = 0 g = 0 b = 0 ir = int(r + 0.5) if ir < 0: ir = 0 elif ir > 255: ir = 255 ig = int(g + 0.5) if ig < 0: ig = 0 elif ig > 255: ig = 255 ib = int(b + 0.5) if ib < 0: ib = 0 elif ib > 255: ib = 255 ia = int(a * 255 + 0.5) if ia < 0: ia = 0 elif ia > 255: ia = 255 self.__image.setPixel(dx, dy, qRgba(ir, ig, ib, ia)) else: self.__image.setPixel(dx, dy, img.pixel(sx, sy)) self.__undoStack.push(cmd) cmd.setAfterImage(self.__image) self.__updateImageRect(self.__pasteRect.topLeft(), self.__pasteRect.bottomRight() + QPoint(1, 1)) else: KQMessageBox.warning(self, self.trUtf8("Pasting Image"), self.trUtf8("""Invalid image data in clipboard."""))