def send_to_process(self, qstr): if not isinstance(qstr, QString): qstr = QString(qstr) if not qstr.endsWith('\n'): qstr.append('\n') self.process.write(qstr.toLocal8Bit()) self.process.waitForBytesWritten(-1)
def start(self): #reads the info in the widgets and calls the sql command command = self.command for i,item in enumerate(self.dlg.ui.widgets): if type(item)==type(QTextEdit()): text=unicode(item.toPlainText()) elif type(item)==type(QLineEdit()): text=unicode(item.text()) elif type(item)==type(QDoubleSpinBox()): text=unicode(item.value()) elif type(item)==type(QComboBox()): text=unicode(item.currentText()) elif isinstance(item, RListWidget): items=item.selectedItems() text=QString() for j in items: text.append(j.text()+item.spDelimiter()) text.remove(-1,1) else: try: text=unicode(item.currentText()) except: text="Error loading widget." command = command.replace("|"+unicode(i+1)+"|",text) self.runCommand(command) self.dlg.close()
def trunc(qs,maxl): q2 = QString(qs) # make a copy if q2.length() > maxl: q2.truncate(maxl-3) q2.append(u"...") q2 = q2.replace(QString("<"),QString("<")) return q2
def parameterValues(self): params = QString() for widget in self.widget.children(): vals = widget.parameterValues() if not vals is None: params.append(QStringList(vals.values()).join("")) return {self.id:params}
def value(self): if (self.cacheIsDirty): self.cacheIsDirty = False formulaStr = self.formula() if (formulaStr.startsWith('\'')): self.cachedValue = formulaStr.mid(1) elif (formulaStr.startsWith('=')): self.cachedValue = self.Invalid expr = QString(formulaStr.mid(1)) expr.replace(" ", "") expr.append(QChar.Null) pos = int(0) cachedValue = self.evalExpression(expr, pos) if (expr[pos] != QChar.Null): cachedValue = self.Invalid else: pass ok = bool(False) # double d = formulaStr.toDouble(&ok) # if (ok) # cachedValue = d # else # cachedValue = formulaStr # return self.cachedValue
def __init__(self, values, target, parent=None): super(KeyButton, self).__init__(parent) # Save the target QLineEdit self.target = target # save the dictionary of values for each modifier state, and set up # parallel dicts of keytop display QStrings and tooltip QStrings. # Where a value is None, convert it to an empty QString. self.values = values self.glyphs = {} self.tooltips = {} for mode in self.values : py_string = self.values[mode] if py_string is not None: self.glyphs[mode] = QString(py_string) tip = QString() # A value can have multiple chars, put all in tooltip for uc in py_string : if not tip.isEmpty(): tip.append(u'+') tip.append(unicodedata.name(uc)) self.tooltips[mode] = tip else : # value is None, use empty strings self.glyphs[mode] = QString() self.tooltips[mode] = QString() # set constant properties self.setAlignment(Qt.AlignCenter) # both horizontal and vertical self.setTextInteractionFlags(Qt.NoTextInteraction) self.setScaledContents(True) # Make our look square, at least 20px, but able to grow self.setMinimumSize(QSize(20,20)) self.setSizePolicy(SPOLICY) self.setFrameStyle(QFrame.Panel) self.setFrameShadow(QFrame.Raised) self.setLineWidth(3) # initialize with a glyph self.shift(0)
def processBuffer(self, buff): printer = QString() for char in buff: if (char > "\x20" and char < "\x7e") or (self.isMetaChar(char)): printer.append(char) return printer
def __init__(self, values, target, parent=None): super(KeyButton, self).__init__(parent) # Save the target QLineEdit self.target = target # save the dictionary of values for each modifier state, and set up # parallel dicts of keytop display QStrings and tooltip QStrings. # Where a value is None, convert it to an empty QString. self.values = values self.glyphs = {} self.tooltips = {} for mode in self.values: py_string = self.values[mode] if py_string is not None: self.glyphs[mode] = QString(py_string) tip = QString() # A value can have multiple chars, put all in tooltip for uc in py_string: if not tip.isEmpty(): tip.append(u'+') tip.append(unicodedata.name(uc)) self.tooltips[mode] = tip else: # value is None, use empty strings self.glyphs[mode] = QString() self.tooltips[mode] = QString() # set constant properties self.setAlignment(Qt.AlignCenter) # both horizontal and vertical self.setTextInteractionFlags(Qt.NoTextInteraction) self.setScaledContents(True) # Make our look square, at least 20px, but able to grow self.setMinimumSize(QSize(20, 20)) self.setSizePolicy(SPOLICY) self.setFrameStyle(QFrame.Panel) self.setFrameShadow(QFrame.Raised) self.setLineWidth(3) # initialize with a glyph self.shift(0)
def value(self) : if (self.cacheIsDirty): self.cacheIsDirty = False formulaStr = self.formula() if (formulaStr.startsWith('\'')): self.cachedValue = formulaStr.mid(1) elif (formulaStr.startsWith('=')): self.cachedValue = self.Invalid expr = QString(formulaStr.mid(1)) expr.replace(" ", "") expr.append(QChar.Null) pos = int(0) cachedValue = self.evalExpression(expr, pos) if (expr[pos] != QChar.Null): cachedValue = self.Invalid else: pass ok = bool(False) # double d = formulaStr.toDouble(&ok) # if (ok) # cachedValue = d # else # cachedValue = formulaStr # return self.cachedValue
def run(self, context, match): """ Have KDE open the query in the browser. """ urlString = QString("http://www.haskell.org/hoogle/?hoogle=") # Apparently Hoogle doesn't like percent encoded URLs. # urlString.append(QUrl.toPercentEncoding(match.data().toString())) urlString.append(match.data().toString()) QDesktopServices().openUrl(QUrl(urlString))
def send_to_process(self, qstr): if not isinstance(qstr, QString): qstr = QString(qstr) if not qstr.endsWith('\n'): qstr.append('\n') self.process.write(qstr.toLocal8Bit()) self.process.waitForBytesWritten(-1) # Eventually write prompt faster (when hitting Enter continuously) # -- necessary/working on Windows only: if os.name == 'nt': self.write_error()
def displayItem(self, item, col): message = QString() it = 0 for it in xrange(0,item.columnCount()): message.append(item.text(it)) if it != item.columnCount() - 1: message.append(":\n") msg = QMessageBox(self) msg.setText(message) msg.setIcon(QMessageBox.Information) msg.setStandardButtons(QMessageBox.Ok) msg.exec_()
def run(self): commands = QString() selected = self.commandList.selectedIndexes() count = 1 for index in selected: if count == len(selected): commands.append(self.commandList.model().data(index, Qt.DisplayRole).toString()) else: commands.append(self.commandList.model().data(index, Qt.DisplayRole).toString()+"\n") count += 1 self.runCommands(commands)
def copy(self): ''' Copy the table selection to the clipboard ''' selection = self.selectionModel() indexes = selection.selectedIndexes() indexes.sort() previous = indexes.pop(0) data = self.model().data(previous) try: text = data.toString() except: text = str(data) selected_text = QString(text) for current in indexes: if current.row() != previous.row(): selected_text.append('\n') else: selected_text.append('\t') data = self.model().data(current) try: text = data.toString() except: text = str(data) selected_text.append(text) previous = current selected_text.append('\n') QApplication.clipboard().setText(selected_text)
def build_colored_qstring_from_list(text, configuration): """ Produces an QString of the given str. Parts of the given text will be colored using html tags (highlighted text). @param text: str object with text that should be converted to the colored text @return: QString object with the colored text of the given str parameter """ text_output = QString() for i in "".join(text).split("\n"): if len(i.strip()) > 0: text_output.append(format_colored_text(configuration, i + "\n")) return text_output
def send_to_process(self, qstr): if not isinstance(qstr, QString): qstr = QString(qstr) if qstr[:-1] in ["clear", "cls", "CLS"]: self.shell.clear() self.send_to_process(QString(os.linesep)) return if not qstr.endsWith('\n'): qstr.append('\n') if os.name == 'nt': self.process.write(unicode(qstr).encode('cp850')) else: self.process.write(qstr.toLocal8Bit()) self.process.waitForBytesWritten(-1)
def copy(self): ''' Copy the table selection to the clipboard At this point, works only for single line selection ''' selection = self.selectionModel() indexes = selection.selectedIndexes() indexes.sort() previous = indexes.pop(0) data = self.model().data(previous) text = data.toString() selected_text = QString(text) for current in indexes: if current.row() != previous.row(): selected_text.append('\n') else: selected_text.append('\t') data = self.model().data(current) text = data.toString() selected_text.append(text) previous = current selected_text.append('\n') QApplication.clipboard().setText(selected_text)
def copy(self): commands = QString() selected = self.commandList.selectedIndexes() count = 1 for index in selected: if count == len(selected): commands.append(self.commandList.model().data(index, Qt.DisplayRole).toString()) else: commands.append(self.commandList.model().data(index, Qt.DisplayRole).toString()+"\n") count += 1 clipboard = QApplication.clipboard() clipboard.setText(commands, QClipboard.Clipboard)
def parameterValues(self): params = QString() if self.isChecked(): xlim1 = self.xMinLineEdit.text() xlim2 = self.xMaxLineEdit.text() ylim1 = self.yMinLineEdit.text() ylim2 = self.yMaxLineEdit.text() if (not xlim1.isEmpty() == xlim2.isEmpty()) or \ (not ylim1.isEmpty() == ylim2.isEmpty()): raise Exception("Error: Both min and max values must be specified") if not xlim1.isEmpty(): # if one isn't empty, then neither are params.append(", xlim=c(%s,%s)" % (xlim1, xlim2)) if not ylim1.isEmpty(): # if one isn't empty, then neither are params.append(", ylim=c(%s,%s)" % (ylim1, ylim2)) return {self.id:params}
def parameterValues(self): self.widget.selectAll() items = self.widget.selectedItems() first = True var = QString() for item in items: if first: var.append(item.text()) first = False else: var.append("%s%s" % (self.sep, item.text())) if var.isEmpty(): raise Exception("Error: Insufficient number of input variables") params = {self.id:var} return params
def inquireSaveFilename(self): ''' Prompt the user for the name of the file into which to save the scene. The file format will be determined from the filename extension. ''' formattypes = [ ("png", self.tr("PNG - Portable Networks Graphics (*.png)")), ("jpeg", self. tr("JPEG - Joint Photographic Experts Group (*.jpeg *.jpg *.jpe)") ), ("tiff", self.tr("TIFF - Tagged Image File Format (*.tiff *.tif)")), ("bmp", self.tr("BMP - Windows Bitmap (*.bmp)")), ("ppm", self.tr("PPM - Portable Pixmap (*.ppm)")), ("xpm", self.tr("XPM - X11 Pixmap (*.xpm)")), ("xbm", self.tr("XBM - X11 Bitmap (*.xbm)")), ] # tr returns QStrings so the following does not work # filters = ";;".join( [ t[1] for t in formattypes ] ) filters = QString(formattypes[0][1]) for typePair in formattypes[1:]: filters.append(";;") filters.append(typePair[1]) # getSaveFileNameAndFilter does not want to accept a default filter # for (fmt, fmtQName) in formattypes: # if self.__lastformat == fmt: # dfltfilter = fmtQName # break # else: # dfltfilter = formattypes[0][1] # getSaveFileNameAndFilter is a PyQt (but not Qt?) method (fileName, fileFilter) = QFileDialog.getSaveFileNameAndFilter( self, self.tr("Save the current image as "), self.__lastfilename, filters) if fileName: for (fmt, fmtQName) in formattypes: if fmtQName.compare(fileFilter) == 0: fileFormat = fmt break else: raise RuntimeError("Unexpected file format name '%s'" % fileFilter) self.saveSceneToFile(fileName, fileFormat, None, None) self.__lastfilename = fileName self.__lastformat = fileFormat
def updateUi(self): # TODO: Implement IDs self.setData(0, Qt.DisplayRole, QString(str(self.id))) self.setData(1, Qt.DisplayRole, QString(self.name)) self.setData(2, Qt.DisplayRole, QString(self.command)) self.setData(3, Qt.DisplayRole, QString(self.description)) # TODO: Allow dependencies dependencyString = QString() if len(self.dependencies) == 0: dependencyString = QString("None") else: dependencyString = QString(str(self.dependencies[0])) for dependency in self.dependencies[1:]: dependencyString.append(QString("," + str(dependency))) self.setData(4, Qt.DisplayRole, dependencyString)
def refresh(self, clearCache=False): # this could be first refresh for this book file, so set the # base URL for its images. sep = QChar(u'/') qsp = QString(IMC.bookDirPath) if not qsp.endsWith(sep): qsp.append(sep) self.baseURL = QUrl.fromLocalFile(qsp) # this might be the second or nth refresh of the book, note the # scroll position so we can restore it in loadEnds below. This # means that when you make a little edit at the end of a book, and # refresh the preview, you won't have to scroll down to the end # for the 500th time to see your changes. self.scrollPosition = self.webPage.mainFrame().scrollPosition() if clearCache: self.settings.clearMemoryCaches() # We are reloading our base page, so clear any history of prior links self.history.clear() self.preview.setHtml(IMC.editWidget.toPlainText(), self.baseURL)
def keyPressEvent(self, event): key = int(event.key()) mods = int(event.modifiers()) #pqMsgs.printKeyEvent(event) if (key == Qt.Key_C) and (mods & Qt.ControlModifier) : event.accept() # PyQt4's implementation of QTableView::selectedIndexes() does # not return a QList but rather a Python list of indices. lix = self.selectedIndexes() if len(lix) : # non-zero selection ans = QString() for ix in lix : ans.append( self.model().data(ix, Qt.DisplayRole).toString() ) ans.append(u' ') ans.chop(1) # drop final space QApplication.clipboard().setText(ans) elif (0 == key & 0x01000000) and \ ( (mods == Qt.NoModifier) or (mods == Qt.ShiftModifier) ) and \ ( 0 == self.horizontalHeader().sortIndicatorSection()) and \ ( Qt.AscendingOrder == self.horizontalHeader().sortIndicatorOrder() ): # An ordinary data key with or without shift, and the table # is sorted on column 0, the words, and sorted ascending. event.accept() sortProxy = self.panelRef.proxy rc = self.panelRef.caseSwitch.isChecked() qc = QChar(key) if rc and (mods == Qt.NoModifier) : qc = qc.toLower() hi = sortProxy.rowCount() lo = 0 while (lo < hi) : mid = (lo + hi) // 2 cc = sortProxy.data(sortProxy.index(mid,0)).toString().at(0) if not rc : cc = cc.toUpper() if qc > cc : lo = mid + 1 else : hi = mid self.scrollTo(sortProxy.index(lo,0)) if not event.isAccepted() : # if we didn't handle it, pass it up super(myTableView, self).keyPressEvent(event)
def refresh(self, clearCache=False ): # this could be first refresh for this book file, so set the # base URL for its images. sep = QChar(u'/') qsp = QString(IMC.bookDirPath) if not qsp.endsWith(sep): qsp.append(sep) self.baseURL = QUrl.fromLocalFile(qsp) # this might be the second or nth refresh of the book, note the # scroll position so we can restore it in loadEnds below. This # means that when you make a little edit at the end of a book, and # refresh the preview, you won't have to scroll down to the end # for the 500th time to see your changes. self.scrollPosition = self.webPage.mainFrame().scrollPosition() if clearCache : self.settings.clearMemoryCaches() # We are reloading our base page, so clear any history of prior links self.history.clear() self.preview.setHtml(IMC.editWidget.toPlainText(),self.baseURL)
def contextMenuEvent(self,event) : ctx_menu = self.createStandardContextMenu() if self.textCursor().hasSelection : qs = self.textCursor().selectedText() if 0 == self.oneWordRE.indexIn(qs) : # it matches at 0 or not at all self.menuWord = self.oneWordRE.cap(1) # save the word ctx_menu.addSeparator() gw_name = QString(self.menuWord) # make a copy gw_action = ctx_menu.addAction(gw_name.append(QString(u' -> Goodwords'))) self.connect(gw_action, SIGNAL("triggered()"), self.addToGW) ctx_menu.exec_(event.globalPos())
def addFiles(self): """ Open a Dialog for select a file and add in VFS """ edialog = evidenceDialog(self.parent) ir = edialog.exec_() if ir > 0: args = {} paths = edialog.manager.get("local") if edialog.rawcheck.isChecked(): module = "local" args["path"] = paths args["parent"] = self.vfs.getnode("/Logical files") elif edialog.ewfcheck.isChecked(): module = "ewf" args["files"] = paths args["parent"] = self.vfs.getnode("/Logical files") else: module = "aff" args["path"] = paths args["parent"] = self.vfs.getnode("/Logical files") self.conf = self.loader.get_conf(str(module)) try: genargs = self.conf.generate(args) self.taskmanager.add(str(module), genargs, ["thread", "gui"]) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr)
def addDevices(self): """Open a device list dialog""" dev = DevicesDialog(self.parent) if dev.exec_(): if dev.selectedDevice: args = {} args["path"] = str(dev.selectedDevice.blockDevice()) args["parent"] = self.vfs.getnode("/Local devices") args["size"] = long(dev.selectedDevice.size()) exec_type = ["thread", "gui"] try: if os.name == "nt": args["name"] = str(dev.selectedDevice.model()) conf = self.loader.get_conf(str("devices")) genargs = conf.generate(args) self.taskmanager.add("devices", genargs, exec_type) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr) del dev
def addDevicesCreateProcess(self, dev): if dev.selectedDevice: args = {} args["path"] = str(dev.selectedDevice.blockDevice()) args["parent"] = self.vfs.getnode("/Local devices") args["size"] = long(dev.selectedDevice.size()) exec_type = ["thread", "gui"] try: if os.name == "nt": args["name"] = str(dev.selectedDevice.model()) conf = self.loader.get_conf(str("devices")) genargs = conf.generate(args) self.taskmanager.add("devices", genargs, exec_type) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only( err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr)
def addFilesCreateProcess(self, edialog): args = {} paths = edialog.manager.get("local") if edialog.rawcheck.isChecked(): module = "local" args["path"] = paths args["parent"] = self.vfs.getnode('/Logical files') elif edialog.ewfcheck.isChecked(): module = "ewf" args["files"] = paths args["parent"] = self.vfs.getnode('/Logical files') else: module = "aff" args["path"] = paths args["parent"] = self.vfs.getnode('/Logical files') self.conf = self.loader.get_conf(str(module)) try: genargs = self.conf.generate(args) self.taskmanager.add(str(module), genargs, ["thread", "gui"]) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr)
def validateModule(self): args = {} try : for argname, lmanager in self.valueArgs.iteritems(): if lmanager.isEnabled(): arg = self.conf.argumentByName(argname) if arg.type() == typeId.Node and arg.inputType() == Argument.List: plist = lmanager.get(argname) params = [] for param in plist: params.append(self.vfs.getnode(param)) elif arg.type() == typeId.Node and arg.inputType() == Argument.Single: params = self.vfs.getnode(lmanager.get(argname)) elif arg.inputType() == Argument.Empty: params = True else: params = lmanager.get(argname) args[argname] = params return self.conf.generate(args) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr)
def validateModule(self): args = {} try: for argname, lmanager in self.valueArgs.iteritems(): if lmanager.isEnabled(): arg = self.conf.argumentByName(argname) if arg.type() == typeId.Node and arg.inputType( ) == Argument.List: plist = lmanager.get(argname) params = [] for param in plist: params.append(self.vfs.getnode(param)) elif arg.type() == typeId.Node and arg.inputType( ) == Argument.Single: params = self.vfs.getnode(lmanager.get(argname)) elif arg.inputType() == Argument.Empty: params = True else: params = lmanager.get(argname) args[argname] = params return self.conf.generate(args) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr)
def validateModule(self): # get values args = {} try: for argname, lmanager in self.valueArgs.iteritems(): if lmanager.isEnabled(): arg = self.conf.argumentByName(argname) if arg.inputType() == Argument.Empty: params = True else: params = lmanager.get(argname) args[argname] = params genargs = self.conf.generate(args) self.taskmanager = TaskManager() self.taskmanager.add(str(self.nameModule), genargs, ["thread", "gui"]) self.accept() except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr) return
def contextMenuEvent(self, event): ctx_menu = self.createStandardContextMenu() if self.textCursor().hasSelection: qs = self.textCursor().selectedText() if 0 == self.oneWordRE.indexIn( qs): # it matches at 0 or not at all self.menuWord = self.oneWordRE.cap(1) # save the word ctx_menu.addSeparator() gw_name = QString(self.menuWord) # make a copy gw_action = ctx_menu.addAction( gw_name.append(QString(u' -> Goodwords'))) self.connect(gw_action, SIGNAL("triggered()"), self.addToGW) ctx_menu.exec_(event.globalPos())
def about(self): text = QString("GuloMail v0.1\n\n") text.append( "GuloMail is a freeware email client written in Python using PyQt4 (Python bindings for Nokia's Qt)\n\n" ) text.append(QChar(0x00A9)) text.append("GulonSoft 2010\nhttp://www.gulon.co.uk/") QMessageBox.about(self, "About GuloMail", text)
def parameterValues(self): params = QString() if self.isChecked(): params.append(", main='%s'" % self.mainLineEdit.text()) params.append(", sub='%s'" % self.subLineEdit.text()) params.append(", xlab='%s'" % self.xlabLineEdit.text()) params.append(", ylab='%s'" % self.ylabLineEdit.text()) return {self.id:params}
def helprun(self): # print "Help pressed..." infoString = QString("Written by Carson Farmer\n" "[email protected]\n") infoString = infoString.append("www.geog.uvic.ca/spar/carson\n") infoString = infoString.append("Code adapted from Eric Wolfs " "pyCartogram.py\n\n" "This tool creates a new shapefile " "based on the input shapefile with " "each polygon vertex shifted. " "Should be called iteratively to get " "the results desired.\n") infoString = infoString.append("Based on a translation of Andy " "Agenda's ESRI ArcScript for " "contiguous cartograms:\n" "http://arcscripts.esri.com/details.asp" "?dbid=10509\n" ) infoString = infoString.append("He based the routine on Charles B. " "Jackel's script in:\n" "'Using ArcView to Create Contiguous " "and Noncontiguous Area Cartograms,'" "Cartography and Geographic " "Information Systems, vol. 24, no. 2, " "1997, pp. 101-109\n" ) infoString = infoString.append("Charles B. Jackel based his script on " "the method proposed in:\n" "Dougenik, J. A, N. R. Chrisman, and " "D. R. Niemeyer. 1985. 'An algorithm " "to construct continuous cartograms.' " "Professional Geographer 37:75-81" ) QMessageBox.information(self.iface.mainWindow(), "About Cartogram Creator", infoString )
def __init__(self, pds = None, debug = False, forceCache = False): self.iconSizes = (128, 64, 48, 32, 22, 16) if not pds: pds = Pds(debug = debug) self.pds = pds self._forceCache = forceCache # Get possible Data Directories dataDirs = QFile.decodeName(getenv('XDG_DATA_DIRS')) if dataDirs.isEmpty(): dataDirs = QString('/usr/local/share/:/usr/share/') dataDirs.prepend(QDir.homePath() + ":") dataDirs.prepend(str(self.pds.config_path) + 'share:') if self.pds.session.ExtraDirs: dirs = QFile.decodeName( getenv(self.pds.session.ExtraDirs)).split(':') for dirName in dirs: dataDirs.append(':' + dirName + '/share') self.themeName = self.pds.settings(self.pds.session.IconKey, \ self.pds.session.DefaultIconTheme) # Define icon directories self.iconDirs = filter(lambda x: path.exists(x), map(lambda x: path.join(unicode(x), 'icons'), dataDirs.split(':'))) self.iconDirs = list(set(self.iconDirs)) logging.debug('Icon Dirs : %s' % ','.join(self.iconDirs)) self.themeIndex = self.readThemeIndex(self.themeName) self.extraIcons = ['/usr/share/pixmaps'] self.updateAvailableIcons()
def exportVariable(self): items = self.workspaceTree.selectedIndexes() if len(items) < 1: return False tree = self.workspaceTree.model().parentTree(items[0]) fd = QFileDialog(self.parent, "Save data to file", str(robjects.r.getwd()), "Comma separated (*.csv);;Text file (*.txt);;All files (*.*)") fd.setAcceptMode(QFileDialog.AcceptSave) if not fd.exec_() == QDialog.Accepted: return False files = fd.selectedFiles() selectedFile = files.first() if selectedFile.length() == 0: return False suffix = QString(fd.selectedNameFilter()) index1 = suffix.lastIndexOf("(")+2 index2 = suffix.lastIndexOf(")") suffix = suffix.mid(index1, index2-index1) if not selectedFile.endsWith(suffix): selectedFile.append(suffix) command = QString('write.table(%s, file = "%s",' % (tree, selectedFile)) command.append(QString('append = FALSE, quote = TRUE, sep = ",", eol = "\\n", na = "NA"')) command.append(QString(', dec = ".", row.names = FALSE, col.names = TRUE, qmethod = "escape")')) self.runCommand(command)
def __init__(self, pds=None, debug=False, forceCache=False): self.iconSizes = (128, 64, 48, 32, 22, 16) if not pds: pds = Pds(debug=debug) self.pds = pds self._forceCache = forceCache # Get possible Data Directories dataDirs = QFile.decodeName(getenv('XDG_DATA_DIRS')) if dataDirs.isEmpty(): dataDirs = QString('/usr/local/share/:/usr/share/') dataDirs.prepend(QDir.homePath() + ":") dataDirs.prepend(str(self.pds.config_path) + 'share:') if self.pds.session.ExtraDirs: dirs = QFile.decodeName(getenv( self.pds.session.ExtraDirs)).split(':') for dirName in dirs: dataDirs.append(':' + dirName + '/share') self.themeName = self.pds.settings(self.pds.session.IconKey, \ self.pds.session.DefaultIconTheme) # Define icon directories self.iconDirs = filter( lambda x: path.exists(x), map(lambda x: path.join(unicode(x), 'icons'), dataDirs.split(':'))) self.iconDirs = list(set(self.iconDirs)) logging.debug('Icon Dirs : %s' % ','.join(self.iconDirs)) self.themeIndex = self.readThemeIndex(self.themeName) self.extraIcons = ['/usr/share/pixmaps'] self.updateAvailableIcons()
def _read_log(self,filename,key): newKey = key logText = QString("") try: logfile = open(filename) logfile.seek(key) lines = logfile.read() newKey = logfile.tell() if newKey != key: logText.append(lines) else: logText.append(QString("..")) logfile.close() except IOError: if self.firstRead == True: logText.append("No logfile yet") self.firstRead = False else: logText.append(QString(".")) return [newKey,logText]
def _read_log(self, filename, key): newKey = key logText = QString("") try: logfile = open(filename) logfile.seek(key) lines = logfile.read() newKey = logfile.tell() if newKey != key: logText.append(lines) else: logText.append(QString("..")) logfile.close() except IOError: if self.firstRead == True: logText.append("No logfile yet") self.firstRead = False else: logText.append(QString(".")) return [newKey, logText]
def launchTask(self, genargs): try: self.taskmanager = TaskManager() self.taskmanager.add(str(self.modulename), genargs, ["thread", "gui"]) except RuntimeError: err_type, err_value, err_traceback = sys.exc_info() err_trace = traceback.format_tb(err_traceback) err_typeval = traceback.format_exception_only(err_type, err_value) terr = QString() detailerr = QString() for err in err_trace: detailerr.append(err) for errw in err_typeval: terr.append(errw) detailerr.append(err) self.messageBox(terr, detailerr) return
def printFullOffset(self, start, len): count = 0 fullBuff = QString() while count <= len: if self.heditor.decimalview: fullBuff.append("%.10d" % start) else: fullBuff.append("%.10X" % start) fullBuff.append("\n") start += 16 count += 1 #Clear and set cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(fullBuff) cursor.movePosition(QTextCursor.Start)
def printFullOffset(self, start, len): count = 0 fullBuff = QString() while count <= len: if self.bdiff.opt_offsetBase == 1: fullBuff.append("%.10d" % start) elif self.bdiff.opt_offsetBase == 0: fullBuff.append("%.10X" % start) fullBuff.append("\n") start += 16 count += 1 #Clear and set cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(fullBuff) cursor.movePosition(QTextCursor.Start)
def printFullBuffer(self, buff): del self.buffer pos = str(len(buff)) + 'B' self.buffer = struct.unpack(pos, buff) count = 0 fullBuff = QString() for byte in self.buffer: fullBuff.append("%.2x" % byte) if count < 15: fullBuff.append(" ") count += 1 else: fullBuff.append("\n") count = 0 cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(fullBuff) cursor.movePosition(QTextCursor.Start)
def printBuffer(self, buff): del self.buffer self.buffer = buff count = 0 printer = QString() for char in buff: if char > "\x20" and char < "\x7e": printer.append(char) else: printer.append(".") if count < 15: count += 1 else: printer.append("\n") count = 0 #Clear and set cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(printer) cursor.movePosition(QTextCursor.Start)
def shown(self): self.wallpaperSettings = wallpaperWidget.Widget.screenSettings self.mouseSettings = mouseWidget.Widget.screenSettings self.menuSettings = menuWidget.Widget.screenSettings self.styleSettings = styleWidget.Widget.screenSettings self.packageSettings = packageWidget.Widget.screenSettings self.servicesSettings = servicesWidget.Widget.screenSettings self.securitySettings = securityWidget.Widget.screenSettings self.extraSettings = extraWidget.Widget.screenSettings subject = "<p><li><b>%s</b></li><ul>" item = "<li>%s</li>" end = "</ul></p>" content = QString("") content.append("""<html><body><ul>""") # Mouse Settings content.append(subject % i18n("Mouse Settings")) content.append(item % i18n("Selected Mouse configuration: <b>%s</b>") % self.mouseSettings["summaryMessage"]["selectedMouse"]) content.append(item % i18n("Selected clicking behavior: <b>%s</b>") % self.mouseSettings["summaryMessage"]["clickBehavior"]) content.append(end) # Menu Settings content.append(subject % i18n("Menu Settings")) content.append(item % i18n("Selected Menu: <b>%s</b>") % self.menuSettings["summaryMessage"]) content.append(end) # Wallpaper Settings content.append(subject % i18n("Wallpaper Settings")) if not self.wallpaperSettings["hasChanged"]: content.append(item % i18n("You haven't selected any wallpaper.")) else: content.append( item % i18n("Selected Wallpaper: <b>%s</b>") % os.path.basename( str(self.wallpaperSettings["selectedWallpaper"]))) content.append(end) # Style Settings content.append(subject % i18n("Style Settings")) if not self.styleSettings["hasChanged"]: content.append(item % i18n("You haven't selected any style.")) else: content.append(item % i18n("Selected Style: <b>%s</b>") % unicode(self.styleSettings["summaryMessage"])) content.append(end) # Notifier Settings if self.packageSettings["hasChanged"]: content.append(subject % i18n("Package Management Settings")) content.append( item % i18n("You have enabled or disabled octopi-notifier.")) content.append(end) # Services Settings if self.servicesSettings["hasChanged"]: self.daemon = Daemon() self.svctext = i18n("You have: ") self.svcissset = False content.append(subject % i18n("Services Settings")) if self.servicesSettings[ "enableCups"] and not self.daemon.isEnabled( "org.cups.cupsd"): self.svctext += i18n("enabled cups; ") self.svcisset = True elif not self.servicesSettings[ "enableCups"] and self.daemon.isEnabled("org.cups.cupsd"): self.svctext += i18n("disabled cups; ") self.svcisset = True if self.servicesSettings[ "enableBluetooth"] and not self.daemon.isEnabled( "bluetooth"): self.svctext += i18n("enabled bluetooth; ") self.svcisset = True elif not self.servicesSettings[ "enableBluetooth"] and self.daemon.isEnabled("bluetooth"): self.svctext += i18n("disabled bluetooth; ") self.svcisset = True #FIXME: when can this ever happen? if not self.svcisset: self.svctext = i18n("You have made no changes.") self.servicesSettings["hasChanged"] = False content.append(item % i18n(self.svctext)) content.append(end) # Security Settings if self.securitySettings["hasChanged"]: self.daemon = Daemon() self.sectext = i18n("You have: ") self.secisset = False content.append(subject % i18n("Security Settings")) if self.securitySettings[ "enableClam"] and not self.daemon.isEnabled("clamd"): self.sectext += i18n("enabled ClamAV; ") self.secisset = True elif not self.securitySettings[ "enableClam"] and self.daemon.isEnabled("clamd"): self.sectext += i18n("disabled ClamAV; ") self.secisset = True if self.securitySettings[ "enableFire"] and not self.daemon.isEnabled("ufw"): self.sectext += i18n("enabled the firewall; ") self.secisset = True elif not self.securitySettings[ "enableFire"] and self.daemon.isEnabled("ufw"): self.sectext += i18n("disabled the firewall; ") self.secisset = True if not self.secisset: self.sectext = i18n("You have made no changes.") self.securitySettings["hasChanged"] = False content.append(item % i18n(self.sectext)) content.append(end) # Extra Settings if self.extraSettings["hasChanged"]: self.repos = Repos() self.extratext = i18n("You have: ") self.extraisset = False content.append(subject % i18n("Extra Settings")) if self.extraSettings[ "enableExtra"] and not self.repos.extraIsEnabled(): self.extratext += i18n("enabled the [extra] repo; ") self.extraisset = True elif not self.extraSettings[ "enableExtra"] and self.repos.extraIsEnabled(): self.extratext += i18n("disabled the [extra] repo; ") self.extraisset = True if not self.extraisset: self.extratext = i18n("You have made no changes.") self.extraSettings["hasChanged"] = False content.append(item % i18n(self.extratext)) content.append(end) self.ui.textSummary.setText(content)
class MainWindowStart(QMainWindow, MainWindow_Pro.Ui_MainWindow): def __init__(self, parent=None): super(MainWindowStart, self).__init__(parent) # Mappers for connecting buttons and labels self.myMapper = QSignalMapper(self) self.myMapper_StyleSheet = QSignalMapper(self) # Load UI self.setupUi(self) self.regex_edits = QRegExp(r"(^[0]+$|^$)") self._filter = Filter() self.filename = QString() self.edit1_delayh.installEventFilter(self._filter) self.sizeLabel = QLabel() self.sizeLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.statusBar1.addPermanentWidget(self.sizeLabel) self.statusBar1.setSizeGripEnabled(False) self.create_connections() self.assign_shortcuts() self.create_tool_bar() self.update_devices_list() # self.button_stop.clicked.connect(self.stop_all) # List of valve pushbuttons self.valve_list = [ self.valve1, self.valve2, self.valve3, self.valve4, self.valve5, self.valve6, self.valve7, self.valve8 ] # GroupBoxes for grouping labels and buttons on each row, used for applying StyleSheets self.group_boxes = [ self.groupbox1, self.groupbox2, self.groupbox3, self.groupbox4, self.groupbox5, self.groupbox6, self.groupbox7, self.groupbox8 ] # List of lineEdits self.lineEdits_list = [ (self.edit1_delayh, self.edit1_delaym, self.edit1_delays, self.edit1_onh, self.edit1_onm, self.edit1_ons, self.edit1_offh, self.edit1_offm, self.edit1_offs, self.edit1_totalh, self.edit1_totalm, self.edit1_totals), (self.edit2_delayh, self.edit2_delaym, self.edit2_delays, self.edit2_onh, self.edit2_onm, self.edit2_ons, self.edit2_offh, self.edit2_offm, self.edit2_offs, self.edit2_totalh, self.edit2_totalm, self.edit2_totals), (self.edit3_delayh, self.edit3_delaym, self.edit3_delays, self.edit3_onh, self.edit3_onm, self.edit3_ons, self.edit3_offh, self.edit3_offm, self.edit3_offs, self.edit3_totalh, self.edit3_totalm, self.edit3_totals), (self.edit4_delayh, self.edit4_delaym, self.edit4_delays, self.edit4_onh, self.edit4_onm, self.edit4_ons, self.edit4_offh, self.edit4_offm, self.edit4_offs, self.edit4_totalh, self.edit4_totalm, self.edit4_totals), (self.edit5_delayh, self.edit5_delaym, self.edit5_delays, self.edit5_onh, self.edit5_onm, self.edit5_ons, self.edit5_offh, self.edit5_offm, self.edit5_offs, self.edit5_totalh, self.edit5_totalm, self.edit5_totals), (self.edit6_delayh, self.edit6_delaym, self.edit6_delays, self.edit6_onh, self.edit6_onm, self.edit6_ons, self.edit6_offh, self.edit6_offm, self.edit6_offs, self.edit6_totalh, self.edit6_totalm, self.edit6_totals), (self.edit7_delayh, self.edit7_delaym, self.edit7_delays, self.edit7_onh, self.edit7_onm, self.edit7_ons, self.edit7_offh, self.edit7_offm, self.edit7_offs, self.edit7_totalh, self.edit7_totalm, self.edit7_totals), (self.edit8_delayh, self.edit8_delaym, self.edit8_delays, self.edit8_onh, self.edit8_onm, self.edit8_ons, self.edit8_offh, self.edit8_offm, self.edit8_offs, self.edit8_totalh, self.edit8_totalm, self.edit8_totals) ] for index, editLabels in enumerate(self.lineEdits_list, 1): for index2, lineedits in enumerate(editLabels, 0): # Apply mapper (GUIObject, objectIndex) self.myMapper_StyleSheet.setMapping( self.lineEdits_list[index - 1][index2], index - 1) # Connect mapper to signal (self.lineEdits_list[index - 1][index2]).textChanged.connect( self.myMapper_StyleSheet.map) # Set event Filter, for detecting when Focus changes self.lineEdits_list[index - 1][index2].installEventFilter( self._filter) # Set Mappers for buttons (1..8) self.myMapper.setMapping(self.valve_list[index - 1], index) # Connect mapper to signal for detecting clicks on buttons (self.valve_list[index - 1]).clicked.connect(self.myMapper.map) # Connect to signal for enabling labelEdits self.myMapper.mapped['int'].connect(self.enable_fields) # Connect to signal for changing color of groupbox used for visual indication self.myMapper_StyleSheet.mapped['int'].connect(self.valve_color_status) # Create Keyboard Shortcuts def assign_shortcuts(self): self.actionArchivo_Nuevo.setShortcut(QKeySequence.New) self.action_Abrir.setShortcut(QKeySequence.Open) self.action_Guardar.setShortcut(QKeySequence.Save) self.actionGuardar_Como.setShortcut(QKeySequence.SaveAs) self.action_Limpiar.setShortcut('Ctrl+L') self.actionVAL_508_Ayuda.setShortcut(QKeySequence.HelpContents) self.action_Salir.setShortcut(QKeySequence.Close) # self.actionPreferencias.setShortcut(QKeySequence.Preferences) self.action_Detener_USB.setShortcut('Ctrl+Shift+C') self.action_Ejecutar.setShortcut('Ctrl+Shift+X') self.action_Para_Valvulas.setShortcut('Ctrl+Shift+P') # Create connections to signals def create_connections(self): self.actionArchivo_Nuevo.triggered.connect(self.new_file) self.action_Abrir.triggered.connect(self.open_file) self.action_Guardar.triggered.connect(self.save_file) self.actionGuardar_Como.triggered.connect(self.save_file_as) self.action_Limpiar.triggered.connect(self.clean_fields) self.action_Salir.triggered.connect(self.close) self.actionVAL_508_Ayuda.triggered.connect(self.show_help) self.actionAcerca_de_VAL_508.triggered.connect(self.show_about) self.action_Detener_USB.triggered.connect(self.stop_usb) self.action_Ejecutar.triggered.connect(self.execute) self.action_Para_Valvulas.triggered.connect(self.stop_all) # Creation of About Dialog def show_about(self): about = aboutdialog.AboutDialog(self) about.show() # Creation of Help Form def show_help(self): form = helpform.HelpForm('Help.html', self) form.show() def new_file(self): self.filename = QString() self.clean_fields() # Close connection to arduino before closing Program def closeEvent(self, QCloseEvent): try: self.thread_connection.serial_connection.close() logging.debug("Thread running and killed at closing program") except AttributeError: logging.debug("Thread was not running when closing program OK") def clean_fields(self): for index, editLabels in enumerate(self.lineEdits_list, 1): for index2, lineedits in enumerate(editLabels, 0): self.lineEdits_list[index - 1][index2].setText('0') def save_file_as(self): filename_copy = self.filename logging.info("Current filename: %s" % self.filename) my_home = os.path.expanduser('~') self.filename = QFileDialog.getSaveFileName( self, self.tr('Guardar como'), os.path.join(my_home, "archivo.txt"), "", "", QFileDialog.DontUseNativeDialog) logging.info("Filename to save: %s" % self.filename) if not self.filename.isNull(): if self.filename.endsWith(QString('.txt')): self.write_data_to_file('w') else: self.filename.append(QString('.txt')) messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Advertencia')) messageBox.setText( self.tr(u"El archivo ya existe, ¿Reemplazar?")) messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) messageBox.setIconPixmap(QPixmap(':/broken_file.png')) if messageBox.exec_() == QMessageBox.Yes: self.write_data_to_file('w') else: try: while True: self.filename = QFileDialog.getSaveFileName( self, self.tr('Guardar como'), os.path.join(my_home, "archivo.txt"), "", "", QFileDialog.DontUseNativeDialog) if self.filename.isNull(): raise Saved_Canceled() else: messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}' ) messageBox.setWindowTitle( self.tr('Advertencia')) messageBox.setText( self.tr( u"El archivo ya existe, ¿Reemplazar?")) messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) messageBox.setIconPixmap( QPixmap(':/broken_file.png')) if messageBox.exec_() == QMessageBox.Yes: self.write_data_to_file('w') raise Saved_Accepted() except Saved_Canceled: self.filename = filename_copy except Saved_Accepted: pass logging.info("Current filename after operation: %s" % self.filename) def save_file(self): if self.filename.isNull(): self.save_file_as() else: self.write_data_to_file('w') # Colect data for arduino def execute(self): string_data = '' list_strings = [] if str(self.arduino_combobox.currentText()): self.statusBar1.showMessage(self.tr('Conectando...')) # Gather all the contents of each row of valves and create a list of lists with them for elem_edit in self.lineEdits_list: # delay string_data = string_data + str( ((int(elem_edit[0].text()) * 3600) + (int(elem_edit[1].text()) * 60) + (int(elem_edit[2].text()))) * 1000) + ';' # ON string_data = string_data + str( ((int(elem_edit[3].text()) * 3600) + (int(elem_edit[4].text()) * 60) + (int(elem_edit[5].text()))) * 1000) + ';' # OFF string_data = string_data + str( ((int(elem_edit[6].text()) * 3600) + (int(elem_edit[7].text()) * 60) + (int(elem_edit[8].text()))) * 1000) + ';' # Total string_data = string_data + str( ((int(elem_edit[9].text()) * 3600) + (int(elem_edit[10].text()) * 60) + (int(elem_edit[11].text()))) * 1000) + ';' list_strings.append(string_data) string_data = '' # Start QThread for communicating with arduino self.thread_connection = Arduino_Communication( str(self.arduino_combobox.currentText()), list_strings) self.thread_connection.start() self.action_Ejecutar.setEnabled(False) self.action_Para_Valvulas.setEnabled(False) # Connect to current QThread instance in order to know the status of it's termination # This line used only when stopping current task self.thread_connection.finished.connect(self.finished_thread) self.thread_connection.connection_exit_status.connect( self.finished_thread) else: messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Advertencia')) messageBox.setText(self.tr("Arduino no seleccionado")) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/usb_error.png')) messageBox.exec_() # Inform QThread to stop sending data to arduino def stop_usb(self): if str(self.arduino_combobox.currentText()): try: self.statusBar1.showMessage(self.tr(u'Conexión detenida')) if self.thread_connection.isRunning(): mutex.lock() self.thread_connection.kill_serial = True mutex.unlock() except AttributeError: logging.debug("Thread not running \'disconnected! \'") else: messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Advertencia')) messageBox.setText(self.tr("Arduino no seleccionado")) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/usb_error.png')) messageBox.exec_() def enable_fields(self, index): hours_reg = QRegExp(r"0*[0-9]{1,3}") sec_reg = QRegExp(r"(0*[0-9])|(0*[0-5][0-9])") for counter, line_edit in enumerate(self.lineEdits_list[index - 1]): line_edit.setEnabled(self.valve_list[index - 1].isChecked()) if counter % 3 == 0: line_edit.setValidator(QRegExpValidator(hours_reg, self)) else: line_edit.setValidator(QRegExpValidator(sec_reg, self)) def valve_color_status(self, index): logging.info("Checking color from valve button") for edit in self.lineEdits_list[index]: if edit.text().contains(self.regex_edits): self.group_boxes[index].setStyleSheet('''QGroupBox { border: 2px solid; border-color: rgba(255, 255, 255, 0);}''' ) else: self.group_boxes[index].setStyleSheet( '''QGroupBox {background-color: rgba(103, 255, 126, 150); border: 2px solid; border-color: rgba(255, 255, 255, 255);}''' ) break def create_tool_bar(self): self.label_arduino = QLabel(self.tr('Dispositivos: ')) self.toolBar.addWidget(self.label_arduino) self.arduino_combobox = QComboBox() self.arduino_combobox.setToolTip(self.tr('Seleccionar Arduino')) self.arduino_combobox.setFocusPolicy(Qt.NoFocus) # Update List of Arduino devices self.reload = QAction(QIcon(":/reload.png"), self.tr("&Refrescar"), self) self.reload.setShortcut(QKeySequence.Refresh) self.reload.setToolTip(self.tr('Refrescar Dispositivos')) self.reload.triggered.connect(self.update_devices_list) self.toolBar.addWidget(self.arduino_combobox) self.toolBar.addAction(self.reload) # Update current usb devices connected to PC def update_devices_list(self): device_list = serial.tools.list_ports.comports() current_arduino = self.arduino_combobox.currentText() self.arduino_combobox.clear() for device_index, device in enumerate(sorted(device_list)): self.arduino_combobox.addItem(device.device) if device.device == current_arduino: self.arduino_combobox.setCurrentIndex(device_index) # Stop current arduino task def stop_all(self): if str(self.arduino_combobox.currentText()): self.thread_connection = Arduino_Communication( str(self.arduino_combobox.currentText())) self.thread_connection.start() self.action_Ejecutar.setEnabled(False) self.action_Para_Valvulas.setEnabled(False) self.action_Detener_USB.setEnabled(False) self.thread_connection.finished.connect(self.finished_thread) self.thread_connection.connection_exit_status.connect( self.finished_thread) else: messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Advertencia')) messageBox.setText(self.tr("Arduino no seleccionado")) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/usb_error.png')) messageBox.exec_() def open_file(self): try: my_home = os.path.expanduser('~') file_name = QFileDialog.getOpenFileName( self, self.tr('Abrir archivo'), my_home, '*.txt', '*.txt', QFileDialog.DontUseNativeDialog) logging.warning("file_name type: %s" % type(file_name)) list_values = [] if not file_name.isNull(): with open(file_name) as fp: for line in fp: list_values.extend([line.replace('\n', '')]) logging.info("List Content: %s" % list_values) count = 0 for elems in self.lineEdits_list: for inner_elem in elems: if not unicode(list_values[count]).isdigit(): raise Uncompatible_Data() inner_elem.setText(list_values[count]) count = count + 1 self.filename = file_name except (IOError, OSError): messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Error')) messageBox.setText(self.tr('No se pudo abrir el archivo')) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/broken_file.png')) messageBox.exec_() except (IndexError, Uncompatible_Data): messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Error')) messageBox.setText(self.tr('Formato Incompatible')) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/broken_file.png')) messageBox.exec_() # Inform the user if we were able to send data successfully to arduino def finished_thread(self, error=None, message=''): if error == 'error': messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Error')) messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/usb_error.png')) messageBox.exec_() return elif error == 'success': messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr(u'Éxito')) messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/usb_success.png')) messageBox.exec_() return elif error == 'stopped': messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr(u'Éxito')) messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIconPixmap(QPixmap(':/success_general.png')) messageBox.exec_() return self.action_Ejecutar.setEnabled(True) self.action_Para_Valvulas.setEnabled(True) self.action_Detener_USB.setEnabled(True) self.statusBar1.showMessage(self.tr('Finalizado')) # Save data to disk def write_data_to_file(self, open_mode): progressDialog = QProgressDialog() progressDialog.setModal(True) progressDialog.setLabelText(self.tr('Guardando...')) progressDialog.setMaximum(8) progressDialog.setCancelButton(None) progressDialog.show() try: # File is closed automatically even on error with open(unicode(self.filename), open_mode) as file_obj: for count, elem_edit in enumerate(self.lineEdits_list, 1): file_obj.write(''.join([str(elem_edit[0].text()), '\n'])) file_obj.write(''.join([str(elem_edit[1].text()), '\n'])) file_obj.write(''.join([str(elem_edit[2].text()), '\n'])) file_obj.write(''.join([str(elem_edit[3].text()), '\n'])) file_obj.write(''.join([str(elem_edit[4].text()), '\n'])) file_obj.write(''.join([str(elem_edit[5].text()), '\n'])) file_obj.write(''.join([str(elem_edit[6].text()), '\n'])) file_obj.write(''.join([str(elem_edit[7].text()), '\n'])) file_obj.write(''.join([str(elem_edit[8].text()), '\n'])) file_obj.write(''.join([str(elem_edit[9].text()), '\n'])) file_obj.write(''.join([str(elem_edit[10].text()), '\n'])) file_obj.write(''.join([str(elem_edit[11].text()), '\n'])) progressDialog.setValue(count) except (IOError, OSError): progressDialog.close() messageBox = QMessageBox(self) messageBox.setStyleSheet( 'QMessageBox QLabel {font: bold 14pt "Cantarell";}') messageBox.setWindowTitle(self.tr('Error')) messageBox.setText(self.tr('Error al guardar')) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.setIcon(QMessageBox.Critical) messageBox.exec_() else: self.statusBar1.showMessage(self.tr('Guardado'), 3000)
class mainwin(QMainWindow): def __init__(self): QMainWindow.__init__(self) # inizialize the module cWidget = QWidget(self) # widget container self.version = '0.2.6' # Changelog moved to README.txt self.setGeometry(30, 30, 600, 300) # starting position and size of the window self.setWindowTitle('A GUI for FFmpeg - v%s' % self.version) # Store parameters here self.command = QString( '') # it is a string that will be passed to ffmpeg self.input = QString('') # absolute path of the input self.output = QString('') # absolute path of the output or output name self.acodec = QString('copy') # audio codec, default = copy self.vcodec = QString('copy') # video codec, default = copy self.width = QString('') # Resize parameter self.height = QString('') # Resize parameter self.crf = QString('23') # Video quality (default crf = 23) # Layout vBox = QVBoxLayout() # main layout hBox1 = QHBoxLayout() # input layout hBox2 = QHBoxLayout() # output layout hBox3 = QHBoxLayout() # 'convert' layout hBox4 = QHBoxLayout() # codecs layout hBox5 = QHBoxLayout() # resize layout vBox1 = QVBoxLayout() # resize sub-layout vBox2 = QVBoxLayout() # resize sub-layout vBox3 = QVBoxLayout() # resize sub-layout # StyleSheets self.setStyleSheet("""QWidget{background-color: rgb(100,100,105)} QToolTip{background-color: black; color: white} QLineEdit{background-color: white; color: black} QLabel{color: white} QLineEdit{background-color: white; color:black} QPushButton{background-color: white; color:black} QCheckBox{color: white} QComboBox{background-color: white; color: black} QComboBox QAbstractItemView{background-color: white} QStatusBar{border-top: 1px solid #777} QSizeGrip{background-image: url(./images/sizegrip.png); width:16px; height:16px;} """) # Label1: input self.label_in = QLabel() self.label_in.setFont(QFont('Ubuntu', 12)) self.label_in.setText('<b><i>Input file</i></b>') self.label_in.setAlignment(Qt.AlignLeft) vBox.addWidget(self.label_in) # Line edit1: input self.ledit_in = QLineEdit() self.ledit_in.setAlignment(Qt.AlignLeft) self.ledit_in.setReadOnly(True) # input is chosen with dialog self.ledit_in.textChanged.connect( self.update_input) # store input path hBox1.addWidget(self.ledit_in) # PushButton1: input self.but_in = QPushButton() self.but_in.setText('Input') self.but_in.clicked.connect(self.get_input) hBox1.addWidget(self.but_in) vBox.addLayout(hBox1) vBox.addItem(QSpacerItem(20, 20)) # Label2: output self.label_out = QLabel() self.label_out.setFont(QFont('Ubuntu', 12)) self.label_out.setText('<b><i>Output file</i></b>') self.label_out.setAlignment(Qt.AlignLeft) vBox.addWidget(self.label_out) # Line edit2: output self.ledit_out = QLineEdit() self.ledit_out.setAlignment(Qt.AlignLeft) self.ledit_out.setReadOnly(False) # input is chosen with dialog self.ledit_out.textChanged.connect( self.update_output) # store input path self.ledit_out.setToolTip( 'Output file. If no path is provided,\nit works on\ the current path.\nDefault name is \'output.mp4\'') hBox2.addWidget(self.ledit_out) # PushButton2: output self.but_out = QPushButton() self.but_out.setText('Output') self.but_out.clicked.connect(self.get_output) hBox2.addWidget(self.but_out) vBox.addLayout(hBox2) vBox.addItem(QSpacerItem(15, 15)) # Quality (crf) # Label: crf self.label_crf = QLabel() self.label_crf.setFont(QFont('Ubuntu condensed', 12)) self.label_crf.setText('CRF') # Line Edit: crf self.ledit_crf = QLineEdit() self.ledit_crf.setAlignment(Qt.AlignRight) self.ledit_crf.setFixedWidth(50) self.ledit_crf.setValidator(QIntValidator( 0, 51)) # CRF line edit only accepts integers between 0 and 51 self.ledit_crf.textChanged.connect(self.update_crf) # store CRF self.ledit_crf.setToolTip( 'Video quality.<br>The CRF scale is between 0 (loseless) and 51\ (worst quality). The default is 23 and a normally acceptable value is between 17-28.' ) hBox4.addWidget(self.label_crf) hBox4.addWidget(self.ledit_crf) hBox4.addItem(QSpacerItem(50, 20)) hBox4.addStretch() # Dropdown menus # Label: Audio codec self.label_acodec = QLabel() self.label_acodec.setFont(QFont('Ubuntu condensed', 12)) self.label_acodec.setText('Audio codec') hBox4.addWidget(self.label_acodec) # ComboBox: Audio codec self.combo_acodec = QComboBox() # Use StyledItemDelegate (without this, it inherits the non-styled ItemDelegate and # stylesheet doesn't work properly) itDel = QStyledItemDelegate() self.combo_acodec.setItemDelegate(itDel) self.combo_acodec.addItems(['-', 'AAC', 'AC3', 'OGG', 'MP3']) self.combo_acodec.currentIndexChanged.connect(self.update_acodec) self.combo_acodec.setMinimumContentsLength(5) self.combo_acodec.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.combo_acodec.setToolTip( 'Audio codec<br> Select none for <i>copy</i>') # if HTML tags are used special characters like \n can't be used hBox4.addWidget(self.combo_acodec) hBox4.addItem(QSpacerItem(20, 20)) # Label: Video codec self.label_vcodec = QLabel() self.label_vcodec.setFont(QFont('Ubuntu condensed', 12)) self.label_vcodec.setText('Video codec') hBox4.addWidget(self.label_vcodec) # ComboBox: Video codec self.combo_vcodec = QComboBox() # Use StyledItemDelegate (without this, it inherits the non-styled ItemDelegate and # stylesheet doesn't work properly) self.combo_vcodec.setItemDelegate(itDel) self.combo_vcodec.addItems(['-', 'H264', 'H265', 'MPEG4']) self.combo_vcodec.currentIndexChanged.connect(self.update_vcodec) self.combo_vcodec.setMinimumContentsLength(6) self.combo_vcodec.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.combo_vcodec.setToolTip( 'Video codec<br> Select none for <i>copy</i>') hBox4.addWidget(self.combo_vcodec) vBox.addLayout(hBox4) # CheckBox: resize self.check_res = QCheckBox() self.check_res.setText('Resize') self.check_res.setFont(QFont('Ubuntu', 12)) self.check_res.stateChanged.connect(self.res_update) hBox5.addWidget(self.check_res) # Label: width self.label_width = QLabel() self.label_width.setText('Width') self.label_width.setFont(QFont('Ubuntu', 12)) self.label_width.setAlignment(Qt.AlignCenter) vBox1.addWidget(self.label_width) # Line Edit: width self.ledit_w = QLineEdit() self.ledit_w.setAlignment(Qt.AlignRight) self.ledit_w.setValidator(QIntValidator()) # only integer input self.ledit_w.setMaxLength(4) self.ledit_w.textChanged.connect(self.width_update) self.ledit_w.setToolTip( 'Video dimensions. Leave one of the\nfields blank to keep aspect ratio.' ) vBox1.addWidget(self.ledit_w) hBox5.addStretch() hBox5.addLayout(vBox1) # spacer + label vBox2.addItem(QSpacerItem(10, 20)) self.label_x = QLabel('x') self.label_x.setFont(QFont('Ubuntu', 12)) vBox2.addWidget(self.label_x) hBox5.addLayout(vBox2) # Label: height self.label_height = QLabel() self.label_height.setText('Height') self.label_height.setFont(QFont('Ubuntu', 12)) self.label_height.setAlignment(Qt.AlignCenter) vBox3.addWidget(self.label_height) # Line Edit: height self.ledit_h = QLineEdit() self.ledit_h.setAlignment(Qt.AlignRight) self.ledit_h.setValidator(QIntValidator()) # only integer input self.ledit_h.setMaxLength(4) self.ledit_h.textChanged.connect(self.height_update) self.ledit_h.setToolTip( 'Video dimensions. Leave one of the\nfields blank to keep aspect ratio.' ) vBox3.addWidget(self.ledit_h) hBox5.addLayout(vBox3) vBox.addItem(QSpacerItem(20, 30)) vBox.addLayout(hBox5) # PushButton3: convert self.but_conv = QPushButton() self.but_conv.setText('Convert') self.but_conv.clicked.connect(self.convert2) hBox3.addStretch() hBox3.addWidget(self.but_conv) hBox3.addStretch() vBox.addItem(QSpacerItem(20, 20)) vBox.addLayout(hBox3) vBox.addStretch() # to keep widgets from resizing # Applying Layout cWidget.setLayout(vBox) self.setCentralWidget(cWidget) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.res_update() # check the intial state of the checkbox ## SLOT definitions def update_input(self): self.input = self.ledit_in.text() def get_input(self): # print self.input.toUtf8() # Debug fname = QFileDialog.getOpenFileName( self, 'Open file', './', "Video files (*.avi *.mpeg *.mp4)") self.input = fname self.ledit_in.setText(self.input) def update_output(self): self.output = self.ledit_out.text() def get_output(self): # print self.output.toUtf8() # Debug fname = QFileDialog.getSaveFileName( self, 'Save file', './', "Video files (*.avi *.mpeg *.mp4)") self.output = fname self.ledit_out.setText(self.output) def update_acodec(self): codecs = { 'AAC': 'aac', 'MP3': 'libmp3lame', 'AC3': 'ac3', 'OGG': 'libvorbis', '-': 'copy' } ind = self.combo_acodec.currentIndex() key = str(self.combo_acodec.itemText(ind)) self.acodec = QString(codecs[key]) # print 'acodec = ', self.acodec.toUtf8() # Debug def update_vcodec(self): codecs = { 'H264': 'libx264', 'H265': 'libx265', 'MPEG4': 'libxvid', '-': 'copy' } ind = self.combo_vcodec.currentIndex() key = str(self.combo_vcodec.itemText(ind)) self.vcodec = QString(codecs[key]) # print 'vcodec = ', self.vcodec.toUtf8() # Debug def update_crf(self): self.crf = self.ledit_crf.text() def width_update(self): self.width = self.ledit_w.text() # print self.width # Debug def height_update(self): self.height = self.ledit_h.text() # print self.height # Debug def res_update(self): if self.check_res.isChecked(): self.ledit_w.setEnabled(True) self.ledit_h.setEnabled(True) self.ledit_h.setStyleSheet( 'background-color: white; color = black') self.ledit_w.setStyleSheet( 'background-color: white; color = black') else: self.ledit_w.setEnabled(False) self.ledit_h.setEnabled(False) self.ledit_h.setStyleSheet('background-color: gray; color = black') self.ledit_w.setStyleSheet('background-color: gray; color = black') self.ledit_h.clear() self.ledit_w.clear() def convert2(self): if not QString.compare(self.input, ''): os.system('echo "Error: missing input"') # bash in linux else: self.command = QString('') # clear command self.command.append('ffmpeg ') # call the program self.command.append('-i "%s" ' % self.input) # input file self.command.append('-c:a %s ' % self.acodec) # audio codec self.command.append('-c:v %s ' % self.vcodec) # video codec if not QString.compare(self.crf, ''): # if text is empty, default video quality. CRF = 23 self.command.append('-crf 23 ') else: self.command.append('-crf %s ' % self.crf) # video quality if self.check_res.isChecked(): if not QString.compare(self.vcodec, 'copy'): os.system( 'echo "Error: cannot resize without encoding video. \ Please select a video codec."') #sys.exit(app.exec_()) return # this way it just exits from the function instead of terminating the app self.command.append('-vf scale=') # resize filter if not QString.compare(self.width, '') and not QString.compare( self.height, ''): self.command.append('iw:ih ') # do not resize elif not QString.compare(self.width, '') and QString.compare( self.height, ''): self.command.append( '-2:%s ' % self.height) # change height with constant ratio elif QString.compare(self.width, '') and not QString.compare( self.height, ''): self.command.append( '%s:-2 ' % self.width) # change width with constant ratio elif QString.compare(self.width, '') and QString.compare( self.height, ''): self.command.append( '%s:%s ' % (self.width, self.height)) # change height with constant ratio if not QString.compare(self.output, ''): self.command.append('output.mp4') # default output else: self.command.append('"%s"' % self.output) # output file os.system(str(self.command.toUtf8()))