def fillInAvailableTools(self): # Operations on the selected item choices = {} # Classification for the selected item classification = "" if self.model.isDir(self.currentIndex): regex = QRegExp("\\d{4}") # match directory names with four digits name = self.model.fileName(self.currentIndex) parentname = self.model.fileName(self.model.parent(self.currentIndex)) isdir = self.model.isDir(self.currentIndex) parentisdir = self.model.isDir(self.model.parent(self.currentIndex)) # print "%s %s %s %s" % (name, parentname,isdir,parentisdir) if isdir and regex.exactMatch(name): # We have a database dir # print "Database Dir" classification = "database" elif parentisdir and regex.exactMatch(parentname): # We have a dataset # print "Dataset Dir" classification = "dataset" else: regex = QRegExp("\\d{4}") model = self.model parentIndex = model.parent(self.currentIndex) parentparentIndex = model.parent(parentIndex) parentparentname = model.fileName(parentparentIndex) parentparentisdir = model.isDir(parentparentIndex) if parentparentisdir and regex.exactMatch(parentparentname): # We have a file with a parentparent which is a database classification classification = "array" # Build up a list of available operations based on the classification tool_set_nodes = [tool_set_node for tool_set_node in self.tool_library_node if tool_set_node.tag == 'tool_group'] tool_file_nodes = [] for tool_set_node in tool_set_nodes: tool_file_nodes.extend([node for node in tool_set_node if node.tag == 'tool']) # Find all tool_nodes that acts on the resolved classification # (by looking at the XML node 'acts_on') for tool_node in tool_file_nodes: acts_on_node = tool_node.find('acts_on') exports_to_node = tool_node.find('exports_to') if acts_on_node is None or exports_to_node is None: # This tool doesn't export anything continue tool_classifications = acts_on_node.text.split(',') exports_to_value = exports_to_node.text if classification in tool_classifications: choices[exports_to_value] = tool_node self.classification = classification return choices
def validate(self, _input, _pos): re_valid = QRegExp('^([0-9A-Fa-f]{2})*$') re_interm = QRegExp('^([0-9A-Fa-f]{2})*([0-9A-Fa-f]{1})$') _input=_input.upper() if re_valid.exactMatch(_input): return (QValidator.Acceptable, _input, _pos) elif re_interm.exactMatch(_input): return (QValidator.Intermediate, _input, _pos) return (QValidator.Invalid, _input, _pos)
def validate(self, _input, _pos): re_valid = QRegExp('^([0-9A-Fa-f]{2})*$') re_interm = QRegExp('^([0-9A-Fa-f]{2})*([0-9A-Fa-f]{1})$') _input = _input.upper() if re_valid.exactMatch(_input): return (QValidator.Acceptable, _input, _pos) elif re_interm.exactMatch(_input): return (QValidator.Intermediate, _input, _pos) return (QValidator.Invalid, _input, _pos)
class HexValidator(QValidator): def __init__(self, max_bytes=-1): QValidator.__init__(self) self.max_bytes = max_bytes if max_bytes == 0: self.re_acceptable = QRegExp('') self.re_intermediate = QRegExp('') elif max_bytes > 0: self.re_acceptable = QRegExp( '([0-9A-Fa-f]{2} ){0,%d}[0-9A-Fa-f]{2}' % (max_bytes - 1)) self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*){1,%d}' % (max_bytes * 2)) else: self.re_acceptable = QRegExp('([0-9A-Fa-f]{2} )*[0-9A-Fa-f]{2}') self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*)+') def validate(self, _input, _pos): _input = _input.upper() if self.re_acceptable.exactMatch(_input): return QValidator.Acceptable, _input, _pos elif self.re_intermediate.exactMatch(_input): return QValidator.Intermediate, _input, _pos else: return QValidator.Invalid, _input, _pos def fixup(self, _input): s = '' n = self.max_bytes * 2 for i, c in enumerate(_input.replace(' ', '').upper()): if n == 0: break if i % 2 == 0: s += ' ' s += c n -= 1 s = s.strip() if len(s.replace(' ', '')) % 2 == 1: s = s[:-1] + '0' + s[-1:] return s
def data(self, arg, value, *args, **kwargs): ip_reg = QRegExp(IP_REG) if (isinstance(value, list) or isinstance(value, tuple) or isinstance(value, str) or isinstance(value, int)) \ and not ip_reg.exactMatch(str(value)): return ArgDataUserID(arg, value, *args, **kwargs) else: return ArgDataIP(arg, value, *args, **kwargs)
def pg_tables(schema="public", exclude_lookups=False): """ Returns all the tables in the given schema minus the default PostGIS tables. Views are also excluded. See separate function for retrieving views. """ t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \ "ORDER BY table_name ASC") result = _execute(t,tschema = schema,tbtype = "BASE TABLE") pgTables = [] for r in result: tableName = r["table_name"] #Remove default PostGIS tables tableIndex = getIndex(_postGISTables, tableName) if tableIndex == -1: if exclude_lookups: #Validate if table is a lookup table and if it is, then omit rx = QRegExp("check_*") rx.setPatternSyntax(QRegExp.Wildcard) if not rx.exactMatch(tableName): pgTables.append(tableName) else: pgTables.append(tableName) return pgTables
class HoogleRunner(plasmascript.Runner): def init(self): """ Initialize and register with Plasma. """ self.myIcon = QIcon(self.package().filePath("images", "lambda.svg")) self.regExp = QRegExp("^hoogle (.*)$") syntax = Plasma.RunnerSyntax("hoogle :q:", "Query hoogle for :q:") self.addSyntax(syntax) def match(self, context): """ Add a match to the given `context` iff the query starts with 'hoogle'. """ if context.isValid() and self.regExp.exactMatch(context.query()): term = self.regExp.cap(1) m = Plasma.QueryMatch(self.runner) m.setText("Query Hoogle for '%s'" % term) m.setType(Plasma.QueryMatch.ExactMatch) m.setIcon(self.myIcon) m.setData(term) context.addMatch(term, m) 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 event(self, event): if event.type() == QEvent.KeyPress: if event.key() in (Qt.Key_Shift, Qt.Key_Control, Qt.Key_AltGr, Qt.Key_Alt): return True regex = QRegExp(self.keyWordREGEX, Qt.CaseInsensitive, QRegExp.RegExp) if regex.exactMatch(self.text()) and not (event.key() == Qt.Key_Backspace): # 16777219 is the backspace #if event.key() != Qt.Key_Backspace and event.key() != Qt.Key_Space: QLineEdit.event(self, event) self.getWords() if not len(self.completions): return True if self.text() == "": return True if len(self.partials) >= 1: autocomplete = self.partials[0] self.applyCompletion(autocomplete) signalAttach = QString(autocomplete) self.AutoComplete.emit(signalAttach) #if autocomplete got a "@" in it, only the part, starting with "@..." will be sent return True else: signalAttach = QString('NONE') self.AutoComplete.emit(signalAttach) return True else: return QLineEdit.event(self, event) else: return QLineEdit.event(self, event)
def pg_tables(schema="public"): """ Returns all the tables in the given schema minus the default PostGIS tables. Views are also excluded. See separate function for retrieving views. """ t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \ "ORDER BY table_name ASC") result = _execute(t, tschema=schema, tbtype="BASE TABLE") pgTables = [] for r in result: tableName = r["table_name"] #Remove default PostGIS tables tableIndex = getIndex(_postGISTables, tableName) if tableIndex == -1: #Validate if table is a lookup table and if it is, then omit rx = QRegExp("check_*") rx.setPatternSyntax(QRegExp.Wildcard) if not rx.exactMatch(tableName): pgTables.append(tableName) return pgTables
class HexValidator(QValidator): def __init__(self, max_bytes=-1): QValidator.__init__(self) self.max_bytes = max_bytes if max_bytes == 0: self.re_acceptable = QRegExp('') self.re_intermediate = QRegExp('') elif max_bytes > 0: self.re_acceptable = QRegExp('([0-9A-Fa-f]{2} ){0,%d}[0-9A-Fa-f]{2}' % (max_bytes - 1)) self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*){1,%d}' % (max_bytes * 2)) else: self.re_acceptable = QRegExp('([0-9A-Fa-f]{2} )*[0-9A-Fa-f]{2}') self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*)+') def validate(self, _input, _pos): _input = _input.upper() if self.re_acceptable.exactMatch(_input): return QValidator.Acceptable, _input, _pos elif self.re_intermediate.exactMatch(_input): return QValidator.Intermediate, _input, _pos else: return QValidator.Invalid, _input, _pos def fixup(self, _input): s = '' n = self.max_bytes * 2 for i, c in enumerate(_input.replace(' ', '').upper()): if n == 0: break if i % 2 == 0: s += ' ' s += c n -= 1 s = s.strip() if len(s.replace(' ', '')) % 2 == 1: s = s[:-1] + '0' + s[-1:] return s
def get_pagelinks(self, field, arg_data): if isinstance(arg_data.value, int) and not arg_data.compatibility.user_id: value = arg_data.label else: value = arg_data.value ip_reg = QRegExp(IP_REG) if (isinstance(value, list) or isinstance(value, tuple) or isinstance(value, str) or isinstance(value, int)) \ and not ip_reg.exactMatch(str(value)): return arg_types['username'].get_pagelinks(field, arg_data) else: return arg_types['ip_saddr_str'].get_pagelinks(field, arg_data)
class MacroHighlighter(QSyntaxHighlighter): def __init__(self, textboxdoc, valid_list_of_commands): QSyntaxHighlighter.__init__(self, textboxdoc) self.valid_syntax = "|".join( [command.regexp_str for command in valid_list_of_commands]) self.my_expression = QRegExp(self.valid_syntax) #define a blue font format for valid commands self.valid = QTextCharFormat() self.valid.setForeground(Qt.black) #define a bold red font format for invalid commands self.invalid = QTextCharFormat() self.invalid.setFontWeight(QFont.Bold) self.invalid.setForeground(Qt.red) #define a blue font format for valid parameters self.valid_value = QTextCharFormat() self.valid_value.setFontWeight(QFont.Bold) #self.valid_value.setForeground(QColor.fromRgb(255,85,0)) self.valid_value.setForeground(Qt.blue) def highlightBlock(self, text): #this function is automatically called when some text is changed #in the texbox. 'text' is the line of text where the change occured #check if the line of text contains a valid command match = self.my_expression.exactMatch(text) if match: #valid command found: highlight the command in blue self.setFormat(0, len(text), self.valid) #highlight the parameters in orange #loop on all the parameters that can be captured for i in range(self.my_expression.captureCount()): #if a parameter was captured, it's position in the text will be >=0 and its capture contains some value 'xxx' #otherwise its position is -1 and its capture contains an empty string '' if self.my_expression.pos(i + 1) != -1: self.setFormat(self.my_expression.pos(i + 1), len(self.my_expression.cap(i + 1)), self.valid_value) else: #no valid command found: highlight in red self.setFormat(0, len(text), self.invalid)
class MacroHighlighter(QSyntaxHighlighter): def __init__(self,textboxdoc,valid_list_of_commands): QSyntaxHighlighter.__init__(self,textboxdoc) self.valid_syntax="|".join([command.regexp_str for command in valid_list_of_commands]) self.my_expression = QRegExp(self.valid_syntax) #define a blue font format for valid commands self.valid = QTextCharFormat() self.valid.setForeground(Qt.black) #define a bold red font format for invalid commands self.invalid = QTextCharFormat() self.invalid.setFontWeight(QFont.Bold) self.invalid.setForeground(Qt.red) #define a blue font format for valid parameters self.valid_value=QTextCharFormat() self.valid_value.setFontWeight(QFont.Bold) #self.valid_value.setForeground(QColor.fromRgb(255,85,0)) self.valid_value.setForeground(Qt.blue) def highlightBlock(self, text): #this function is automatically called when some text is changed #in the texbox. 'text' is the line of text where the change occured #check if the line of text contains a valid command match = self.my_expression.exactMatch(text) if match: #valid command found: highlight the command in blue self.setFormat(0, len(text), self.valid) #highlight the parameters in orange #loop on all the parameters that can be captured for i in range(self.my_expression.captureCount()): #if a parameter was captured, it's position in the text will be >=0 and its capture contains some value 'xxx' #otherwise its position is -1 and its capture contains an empty string '' if self.my_expression.pos(i+1)!=-1: self.setFormat(self.my_expression.pos(i+1), len(self.my_expression.cap(i+1)), self.valid_value) else: #no valid command found: highlight in red self.setFormat(0, len(text), self.invalid)
class SvnChangeListsDialog(QDialog, Ui_SvnChangeListsDialog): """ Class implementing a dialog to browse the change lists. """ def __init__(self, vcs, parent=None): """ Constructor @param vcs reference to the vcs object @param parent parent widget (QWidget) """ QDialog.__init__(self, parent) self.setupUi(self) self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False) self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True) self.process = None self.vcs = vcs self.rx_status = \ QRegExp('(.{8,9})\\s+([0-9-]+)\\s+([0-9?]+)\\s+(\\S+)\\s+(.+)\\s*') # flags (8 or 9 anything), revision, changed rev, author, path self.rx_status2 = \ QRegExp('(.{8,9})\\s+(.+)\\s*') # flags (8 or 9 anything), path self.rx_changelist = \ QRegExp('--- \\S+ .([\\w\\s]+).:\\s+') # three dashes, Changelist (translated), quote, # changelist name, quote, : @pyqtSignature("QListWidgetItem*, QListWidgetItem*") def on_changeLists_currentItemChanged(self, current, previous): """ Private slot to handle the selection of a new item. @param current current item (QListWidgetItem) @param previous previous current item (QListWidgetItem) """ self.filesList.clear() if current is not None: changelist = unicode(current.text()) if changelist in self.changeListsDict: self.filesList.addItems(sorted(self.changeListsDict[changelist])) def start(self, path): """ Public slot to populate the data. @param path directory name to show change lists for (string) """ self.changeListsDict = {} self.filesLabel.setText(self.trUtf8("Files (relative to %1):").arg(path)) self.errorGroup.hide() self.intercept = False self.path = path self.currentChangelist = "" self.process = QProcess() self.process.finished.connect(self.__procFinished) self.process.readyReadStandardOutput.connect(self.__readStdout) self.process.readyReadStandardError.connect(self.__readStderr) args = [] args.append('status') self.vcs.addArguments(args, self.vcs.options['global']) self.vcs.addArguments(args, self.vcs.options['status']) if '--verbose' not in self.vcs.options['global'] and \ '--verbose' not in self.vcs.options['status']: args.append('--verbose') if isinstance(path, list): self.dname, fnames = self.vcs.splitPathList(path) self.vcs.addArguments(args, fnames) else: self.dname, fname = self.vcs.splitPath(path) args.append(fname) self.process.setWorkingDirectory(self.dname) self.process.start('svn', args) procStarted = self.process.waitForStarted() if not procStarted: self.inputGroup.setEnabled(False) self.inputGroup.hide() KQMessageBox.critical(self, self.trUtf8('Process Generation Error'), self.trUtf8( 'The process %1 could not be started. ' 'Ensure, that it is in the search path.' ).arg('svn')) else: self.inputGroup.setEnabled(True) self.inputGroup.show() def __finish(self): """ Private slot called when the process finished or the user pressed the button. """ if self.process is not None and \ self.process.state() != QProcess.NotRunning: self.process.terminate() QTimer.singleShot(2000, self.process.kill) self.process.waitForFinished(3000) self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True) self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False) self.buttonBox.button(QDialogButtonBox.Close).setDefault(True) self.inputGroup.setEnabled(False) self.inputGroup.hide() if len(self.changeListsDict) == 0: self.changeLists.addItem(self.trUtf8("No changelists found")) self.buttonBox.button(QDialogButtonBox.Close).setFocus(Qt.OtherFocusReason) else: self.changeLists.addItems(sorted(self.changeListsDict.keys())) self.changeLists.setCurrentRow(0) self.changeLists.setFocus(Qt.OtherFocusReason) def on_buttonBox_clicked(self, button): """ Private slot called by a button of the button box clicked. @param button button that was clicked (QAbstractButton) """ if button == self.buttonBox.button(QDialogButtonBox.Close): self.close() elif button == self.buttonBox.button(QDialogButtonBox.Cancel): self.__finish() def __procFinished(self, exitCode, exitStatus): """ Private slot connected to the finished signal. @param exitCode exit code of the process (integer) @param exitStatus exit status of the process (QProcess.ExitStatus) """ self.__finish() def __readStdout(self): """ Private slot to handle the readyReadStandardOutput signal. It reads the output of the process, formats it and inserts it into the contents pane. """ if self.process is not None: self.process.setReadChannel(QProcess.StandardOutput) while self.process.canReadLine(): s = unicode(self.process.readLine(), Preferences.getSystem("IOEncoding"), 'replace') if self.currentChangelist != "" and self.rx_status.exactMatch(s): file = unicode(self.rx_status.cap(5)).strip() filename = file.replace(self.path + os.sep, "") if filename not in self.changeListsDict[self.currentChangelist]: self.changeListsDict[self.currentChangelist].append(filename) elif self.currentChangelist != "" and self.rx_status2.exactMatch(s): file = unicode(self.rx_status2.cap(2)).strip() filename = file.replace(self.path + os.sep, "") if filename not in self.changeListsDict[self.currentChangelist]: self.changeListsDict[self.currentChangelist].append(filename) elif self.rx_changelist.exactMatch(s): self.currentChangelist = unicode(self.rx_changelist.cap(1)) if self.currentChangelist not in self.changeListsDict: self.changeListsDict[self.currentChangelist] = [] def __readStderr(self): """ Private slot to handle the readyReadStandardError signal. It reads the error output of the process and inserts it into the error pane. """ if self.process is not None: self.errorGroup.show() s = QString(self.process.readAllStandardError()) self.errors.insertPlainText(s) self.errors.ensureCursorVisible() def on_passwordCheckBox_toggled(self, isOn): """ Private slot to handle the password checkbox toggled. @param isOn flag indicating the status of the check box (boolean) """ if isOn: self.input.setEchoMode(QLineEdit.Password) else: self.input.setEchoMode(QLineEdit.Normal) @pyqtSignature("") def on_sendButton_clicked(self): """ Private slot to send the input to the subversion process. """ input = self.input.text() input += os.linesep if self.passwordCheckBox.isChecked(): self.errors.insertPlainText(os.linesep) self.errors.ensureCursorVisible() else: self.errors.insertPlainText(input) self.errors.ensureCursorVisible() self.process.write(input) self.passwordCheckBox.setChecked(False) self.input.clear() def on_input_returnPressed(self): """ Private slot to handle the press of the return key in the input field. """ self.intercept = True self.on_sendButton_clicked() def keyPressEvent(self, evt): """ Protected slot to handle a key press event. @param evt the key press event (QKeyEvent) """ if self.intercept: self.intercept = False evt.accept() return QDialog.keyPressEvent(self, evt)
def loadMetadata(self, metaStream): sectionRE = QRegExp( u"\{\{(" + '|'.join ( ['PAGETABLE','CHARCENSUS','WORDCENSUS','BOOKMARKS', 'NOTES','GOODWORDS','BADWORDS','CURSOR','VERSION', 'STALECENSUS','NEEDSPELLCHECK','ENCODING', 'DOCHASH', 'MAINDICT'] ) \ + u")(.*)\}\}", Qt.CaseSensitive) metaVersion = 0 # base version while not metaStream.atEnd(): qline = metaStream.readLine().trimmed() if qline.isEmpty(): continue # allow blank lines between sections if sectionRE.exactMatch(qline): # section start section = sectionRE.cap(1) argument = unicode(sectionRE.cap(2).trimmed()) endsec = QString(u"{{/" + section + u"}}") if section == u"VERSION": if len(argument) != 0: metaVersion = int(argument) continue # no more data after {{VERSION x }} elif section == u"STALECENSUS": if argument == u"TRUE": IMC.staleCensus = IMC.staleCensusLoaded continue # no more data after {{STALECENSUS x}} elif section == u"NEEDSPELLCHECK": if argument == u"TRUE": IMC.needSpellCheck = True continue # no more data after {{NEEDSPELLCHECK x}} elif section == u"ENCODING": IMC.bookSaveEncoding = QString(argument) continue elif section == u"MAINDICT": IMC.bookMainDict = QString(argument) continue elif section == u"DOCHASH": IMC.metaHash = argument continue elif section == u"PAGETABLE": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and ( not qline.isEmpty()): IMC.pageTable.metaStringIn(qline) qline = metaStream.readLine() continue elif section == u"CHARCENSUS": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and ( not qline.isEmpty()): # can't just .split the char census, the first # char is the char being counted and it can be a space. str = unicode(qline) parts = str[2:].split(' ') IMC.charCensus.append(QString(str[0]), int(parts[0]), int(parts[1])) qline = metaStream.readLine() continue elif section == u"WORDCENSUS": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and ( not qline.isEmpty()): parts = unicode(qline).split(' ') IMC.wordCensus.append(QString(parts[0]), int(parts[1]), int(parts[2])) qline = metaStream.readLine() continue elif section == u"BOOKMARKS": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and ( not qline.isEmpty()): parts = unicode(qline).split(' ') tc = QTextCursor(self.document()) tc.setPosition(int(parts[1])) if len(parts ) == 3: # early versions didn't save anchor tc.movePosition(int(parts[2]), QTextCursor.KeepAnchor) self.bookMarkList[int(parts[0])] = tc qline = metaStream.readLine() continue elif section == u"NOTES": e = IMC.notesEditor e.setUndoRedoEnabled(False) qline = metaStream.readLine() while (not qline.startsWith(endsec) ) and not metaStream.atEnd(): if qline.startsWith(u"\xfffd"): # escaped {{ qline.remove(0, 1) e.appendPlainText(qline) qline = metaStream.readLine() e.setUndoRedoEnabled(True) continue elif section == u"GOODWORDS": # not going to bother checking for endsec return, # if it isn't that then we will shortly fail anyway w = IMC.goodWordList.load(metaStream, endsec) continue elif section == u"BADWORDS": w = IMC.badWordList.load(metaStream, endsec) continue elif section == u"CURSOR": # restore selection as of save p1p2 = argument.split(' ') tc = QTextCursor(self.document()) tc.setPosition(int(p1p2[0]), QTextCursor.MoveAnchor) tc.setPosition(int(p1p2[1]), QTextCursor.KeepAnchor) self.setTextCursor(tc) else: # this can't happen; section is text captured by the RE # and we have accounted for all possibilities raise AssertionError, "impossible metadata" else: # Non-blank line that doesn't match sectionRE? pqMsgs.infoMsg( "Unexpected line in metadata: {0}".format( pqMsgs.trunc(qline, 20)), "Metadata may be incomplete, suggest quit") break
class CompleterPython(CompleterBase): """ Class implementing typing completer for Python. """ def __init__(self, editor, parent = None): """ Constructor @param editor reference to the editor object (QScintilla.Editor) @param parent reference to the parent object (QObject) """ CompleterBase.__init__(self, editor, parent) self.__defRX = QRegExp(r"""^[ \t]*def \w+\(""") self.__defSelfRX = QRegExp(r"""^[ \t]*def \w+\([ \t]*self[ \t]*[,)]""") self.__defClsRX = QRegExp(r"""^[ \t]*def \w+\([ \t]*cls[ \t]*[,)]""") self.__classRX = QRegExp(r"""^[ \t]*class \w+\(""") self.__importRX = QRegExp(r"""^[ \t]*from [\w.]+ """) self.__classmethodRX = QRegExp(r"""^[ \t]*@classmethod""") self.__defOnlyRX = QRegExp(r"""^[ \t]*def """) self.__ifRX = QRegExp(r"""^[ \t]*if """) self.__elifRX = QRegExp(r"""^[ \t]*elif """) self.__elseRX = QRegExp(r"""^[ \t]*else:""") self.__tryRX = QRegExp(r"""^[ \t]*try:""") self.__finallyRX = QRegExp(r"""^[ \t]*finally:""") self.__exceptRX = QRegExp(r"""^[ \t]*except """) self.__exceptcRX = QRegExp(r"""^[ \t]*except:""") self.__whileRX = QRegExp(r"""^[ \t]*while """) self.__forRX = QRegExp(r"""^[ \t]*for """) self.readSettings() def readSettings(self): """ Public slot called to reread the configuration parameters. """ self.setEnabled(Preferences.getEditorTyping("Python/EnabledTypingAids")) self.__insertClosingBrace = \ Preferences.getEditorTyping("Python/InsertClosingBrace") self.__indentBrace = \ Preferences.getEditorTyping("Python/IndentBrace") self.__skipBrace = \ Preferences.getEditorTyping("Python/SkipBrace") self.__insertQuote = \ Preferences.getEditorTyping("Python/InsertQuote") self.__dedentElse = \ Preferences.getEditorTyping("Python/DedentElse") self.__dedentExcept = \ Preferences.getEditorTyping("Python/DedentExcept") self.__py24StyleTry = \ Preferences.getEditorTyping("Python/Py24StyleTry") self.__insertImport = \ Preferences.getEditorTyping("Python/InsertImport") self.__insertSelf = \ Preferences.getEditorTyping("Python/InsertSelf") self.__insertBlank = \ Preferences.getEditorTyping("Python/InsertBlank") self.__colonDetection= \ Preferences.getEditorTyping("Python/ColonDetection") self.__dedentDef= \ Preferences.getEditorTyping("Python/DedentDef") def charAdded(self, charNumber): """ Public slot called to handle the user entering a character. @param charNumber value of the character entered (integer) """ char = unichr(charNumber) if char not in ['(', ')', '{', '}', '[', ']', ' ', ',', "'", '"', '\n', ':']: return # take the short route line, col = self.editor.getCursorPosition() if self.__inComment(line, col) or \ (char != '"' and self.__inDoubleQuotedString()) or \ (char != '"' and self.__inTripleDoubleQuotedString()) or \ (char != "'" and self.__inSingleQuotedString()) or \ (char != "'" and self.__inTripleSingleQuotedString()): return # open parenthesis # insert closing parenthesis and self if char == '(': txt = self.editor.text(line).left(col) if self.__insertSelf and \ self.__defRX.exactMatch(txt): if self.__isClassmethodDef(): self.editor.insert('cls') self.editor.setCursorPosition(line, col + 3) elif self.__isClassMethod(): self.editor.insert('self') self.editor.setCursorPosition(line, col + 4) if self.__insertClosingBrace: if self.__defRX.exactMatch(txt) or \ self.__classRX.exactMatch(txt): self.editor.insert('):') else: self.editor.insert(')') # closing parenthesis # skip matching closing parenthesis elif char in [')', '}', ']']: if char == self.editor.text(line).mid(col, 1): if self.__skipBrace: self.editor.setSelection(line, col, line, col + 1) self.editor.removeSelectedText() # space # insert import, dedent to if for elif, dedent to try for except, dedent def elif char == ' ': txt = self.editor.text(line).left(col) if self.__insertImport and self.__importRX.exactMatch(txt): self.editor.insert('import ') self.editor.setCursorPosition(line, col + 7) elif self.__dedentElse and self.__elifRX.exactMatch(txt): self.__dedentToIf() elif self.__dedentExcept and self.__exceptRX.exactMatch(txt): self.__dedentExceptToTry(False) elif self.__dedentDef and self.__defOnlyRX.exactMatch(txt): self.__dedentDefStatement() # comma # insert blank elif char == ',': if self.__insertBlank: self.editor.insert(' ') self.editor.setCursorPosition(line, col + 1) # open curly brace # insert closing brace elif char == '{': if self.__insertClosingBrace: self.editor.insert('}') # open bracket # insert closing bracket elif char == '[': if self.__insertClosingBrace: self.editor.insert(']') # double quote # insert double quote elif char == '"': if self.__insertQuote: self.editor.insert('"') # quote # insert quote elif char == '\'': if self.__insertQuote: self.editor.insert('\'') # colon # skip colon, dedent to if for else: elif char == ':': if char == self.editor.text(line).mid(col, 1): if self.__colonDetection: self.editor.setSelection(line, col, line, col + 1) self.editor.removeSelectedText() else: txt = self.editor.text(line).left(col) if self.__dedentElse and self.__elseRX.exactMatch(txt): self.__dedentElseToIfWhileForTry() elif self.__dedentExcept and self.__exceptcRX.exactMatch(txt): self.__dedentExceptToTry(True) elif self.__dedentExcept and self.__finallyRX.exactMatch(txt): self.__dedentFinallyToTry() # new line # indent to opening brace elif char == '\n': if self.__indentBrace: txt = self.editor.text(line - 1) if txt.lastIndexOf(QRegExp(":\r?\n")) == -1: openCount = txt.count(QRegExp("[({[]")) closeCount = txt.count(QRegExp("[)}\]]")) if openCount > closeCount: lastOpenIndex = 0 openCount = 0 closeCount = 0 while lastOpenIndex > -1 and openCount == closeCount: lastOpenIndex = \ txt.lastIndexOf(QRegExp("[({[]"), lastOpenIndex - 1) txt2 = txt.mid(lastOpenIndex) openCount = txt2.count(QRegExp("[({[]")) closeCount = txt2.count(QRegExp("[)}\]]")) if lastOpenIndex > -1 and lastOpenIndex > col: self.editor.insert(' ' * (lastOpenIndex - col + 1)) self.editor.setCursorPosition(line, lastOpenIndex + 1) def __dedentToIf(self): """ Private method to dedent the last line to the last if statement with less (or equal) indentation. """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) ifLine = line - 1 while ifLine >= 0: txt = self.editor.text(ifLine) edInd = self.editor.indentation(ifLine) if txt.indexOf(self.__elseRX) == 0 and edInd <= indentation: indentation = edInd - 1 elif (txt.indexOf(self.__ifRX) == 0 or \ txt.indexOf(self.__elifRX) == 0) and edInd <= indentation: self.editor.cancelList() self.editor.setIndentation(line, edInd) break ifLine -= 1 def __dedentElseToIfWhileForTry(self): """ Private method to dedent the line of the else statement to the last if, while, for or try statement with less (or equal) indentation. """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) if line > 0: prevInd = self.editor.indentation(line - 1) ifLine = line - 1 while ifLine >= 0: txt = self.editor.text(ifLine) edInd = self.editor.indentation(ifLine) if txt.indexOf(self.__elseRX) == 0 and edInd <= indentation: indentation = edInd - 1 elif txt.indexOf(self.__elifRX) == 0 and \ edInd == indentation and \ edInd == prevInd: indentation = edInd - 1 elif (txt.indexOf(self.__ifRX) == 0 or \ txt.indexOf(self.__whileRX) == 0 or \ txt.indexOf(self.__forRX) == 0 or \ txt.indexOf(self.__tryRX) == 0) and \ edInd <= indentation: self.editor.cancelList() self.editor.setIndentation(line, edInd) break ifLine -= 1 def __dedentExceptToTry(self, hasColon): """ Private method to dedent the line of the except statement to the last try statement with less (or equal) indentation. @param hasColon flag indicating the except type (boolean) """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) tryLine = line - 1 while tryLine >= 0: txt = self.editor.text(tryLine) edInd = self.editor.indentation(tryLine) if (txt.indexOf(self.__exceptcRX) == 0 or \ txt.indexOf(self.__finallyRX) == 0) and edInd <= indentation: indentation = edInd - 1 elif (txt.indexOf(self.__exceptRX) == 0 or \ txt.indexOf(self.__tryRX) == 0) and edInd <= indentation: self.editor.cancelList() self.editor.setIndentation(line, edInd) break tryLine -= 1 def __dedentFinallyToTry(self): """ Private method to dedent the line of the except statement to the last try statement with less (or equal) indentation. """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) tryLine = line - 1 while tryLine >= 0: txt = self.editor.text(tryLine) edInd = self.editor.indentation(tryLine) if self.__py24StyleTry: if (txt.indexOf(self.__exceptcRX) == 0 or \ txt.indexOf(self.__exceptRX) == 0 or \ txt.indexOf(self.__finallyRX) == 0) and edInd <= indentation: indentation = edInd - 1 elif txt.indexOf(self.__tryRX) == 0 and edInd <= indentation: self.editor.cancelList() self.editor.setIndentation(line, edInd) break else: if txt.indexOf(self.__finallyRX) == 0 and edInd <= indentation: indentation = edInd - 1 elif (txt.indexOf(self.__tryRX) == 0 or \ txt.indexOf(self.__exceptcRX) == 0 or \ txt.indexOf(self.__exceptRX) == 0) and edInd <= indentation: self.editor.cancelList() self.editor.setIndentation(line, edInd) break tryLine -= 1 def __dedentDefStatement(self): """ Private method to dedent the line of the def statement to a previous def statement or class statement. """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) tryLine = line - 1 while tryLine >= 0: txt = self.editor.text(tryLine) edInd = self.editor.indentation(tryLine) newInd = -1 if txt.indexOf(self.__defRX) == 0 and edInd < indentation: newInd = edInd elif txt.indexOf(self.__classRX) == 0 and edInd < indentation: newInd = edInd + \ (self.editor.indentationWidth() or self.editor.tabWidth()) if newInd >= 0: self.editor.cancelList() self.editor.setIndentation(line, newInd) break tryLine -= 1 def __isClassMethod(self): """ Private method to check, if the user is defining a class method. @return flag indicating the definition of a class method (boolean) """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) curLine = line - 1 while curLine >= 0: if (self.editor.text(curLine).indexOf(self.__defSelfRX) == 0 or \ self.editor.text(curLine).indexOf(self.__defClsRX) == 0) and \ self.editor.indentation(curLine) == indentation: return True elif self.editor.text(curLine).indexOf(self.__classRX) == 0 and \ self.editor.indentation(curLine) < indentation: return True elif self.editor.text(curLine).indexOf(self.__defRX) == 0 and \ self.editor.indentation(curLine) <= indentation: return False curLine -= 1 return False def __isClassmethodDef(self): """ Private method to check, if the user is defing a classmethod (@classmethod) method. @return flag indicating the definition of a classmethod method (boolean) """ line, col = self.editor.getCursorPosition() indentation = self.editor.indentation(line) curLine = line - 1 if self.editor.text(curLine).indexOf(self.__classmethodRX) == 0 and \ self.editor.indentation(curLine) == indentation: return True return False def __inComment(self, line, col): """ Private method to check, if the cursor is inside a comment @param line current line (integer) @param col current position within line (integer) @return flag indicating, if the cursor is inside a comment (boolean) """ txt = self.editor.text(line) while col >= 0: if txt.mid(col, 1) == "#": return True col -= 1 return False def __inDoubleQuotedString(self): """ Private method to check, if the cursor is within a double quoted string. @return flag indicating, if the cursor is inside a double quoted string (boolean) """ return self.editor.currentStyle() == QsciLexerPython.DoubleQuotedString def __inTripleDoubleQuotedString(self): """ Private method to check, if the cursor is within a triple double quoted string. @return flag indicating, if the cursor is inside a triple double quoted string (boolean) """ return self.editor.currentStyle() == QsciLexerPython.TripleDoubleQuotedString def __inSingleQuotedString(self): """ Private method to check, if the cursor is within a single quoted string. @return flag indicating, if the cursor is inside a single quoted string (boolean) """ return self.editor.currentStyle() == QsciLexerPython.SingleQuotedString def __inTripleSingleQuotedString(self): """ Private method to check, if the cursor is within a triple single quoted string. @return flag indicating, if the cursor is inside a triple single quoted string (boolean) """ return self.editor.currentStyle() == QsciLexerPython.TripleSingleQuotedString
class NewConnectionDlg(QDialog): def __init__(self): QDialog.__init__(self) self.host = '' self.port = 0 self.schema = '' self.__host_reg = QRegExp( "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$") self.__port_reg = QRegExp("[1-9][0-9]{0,4}") self.__host_correct = False self.__port_correct = False self.__setup_ui() self.__connect_slot() def __setup_ui(self): self.setMaximumSize(300, 300) self.setMinimumSize(300, 300) vlayout = QVBoxLayout() host_layout = QHBoxLayout() port_layout = QHBoxLayout() slotid_layout = QHBoxLayout() intfid_layout = QHBoxLayout() onuid_layout = QHBoxLayout() btn_layout = QHBoxLayout() host_layout.addWidget(QLabel('Host'), 3) self.__host_edit = QLineEdit('192.168.184.128') #self.__host_edit = QLineEdit() self.__host_edit.setValidator(QRegExpValidator(self.__host_reg)) host_layout.addWidget(self.__host_edit, 7) port_layout.addWidget(QLabel('Port'), 3) self.__port_edit = QLineEdit('6641') #self.__port_edit = QLineEdit() self.__port_edit.setValidator(QRegExpValidator(self.__port_reg)) port_layout.addWidget(self.__port_edit, 7) slotid_layout.addWidget(QLabel('Slot id'), 3) # self.__port_edit = QLineEdit('6641') self.__slotid_edit = QLineEdit('1') self.__slotid_edit.setValidator(QRegExpValidator(QRegExp("[0-9]"))) slotid_layout.addWidget(self.__slotid_edit, 7) intfid_layout.addWidget(QLabel('Intf id'), 3) self.__intfid_edit = QLineEdit('0') self.__intfid_edit.setValidator(QRegExpValidator( QRegExp("[0-9][0-9]"))) intfid_layout.addWidget(self.__intfid_edit, 7) onuid_layout.addWidget(QLabel('Intf id'), 3) # self.__port_edit = QLineEdit('6641') self.__onuid_edit = QLineEdit('1') self.__onuid_edit.setValidator(QRegExpValidator(QRegExp("[0-9][0-9]"))) onuid_layout.addWidget(self.__onuid_edit, 7) self.ok_btn = QPushButton('ok') #self.ok_btn.setFlat(True) #self.ok_btn.setEnabled(False) self.cancel_btn = QPushButton('cancel') btn_layout.addWidget(self.ok_btn, 5) btn_layout.addWidget(self.cancel_btn, 5) vlayout.addLayout(host_layout) vlayout.addLayout(port_layout) vlayout.addLayout(slotid_layout) vlayout.addLayout(intfid_layout) vlayout.addLayout(onuid_layout) vlayout.addLayout(btn_layout) self.setLayout(vlayout) def __connect_slot(self): self.connect(self.ok_btn, SIGNAL('clicked()'), self, SLOT('__on_ok_btn()')) self.connect(self.cancel_btn, SIGNAL('clicked()'), self, SLOT('reject()')) self.connect(self.__host_edit, SIGNAL('textChanged(QString)'), self, SLOT('__on_host_edit_change(QString)')) self.connect(self.__port_edit, SIGNAL('textChanged(QString)'), self, SLOT('__on_port_edit_change(QString)')) @pyqtSlot() def __on_ok_btn(self): self.host = to_python_str(self.__host_edit.text()) self.port = int(self.__port_edit.text() if ( self.__port_edit.text() != '') else '0') self.slotid = int(self.__slotid_edit.text() if ( self.__slotid_edit.text() != '') else '1') self.intfid = int(self.__intfid_edit.text() if ( self.__intfid_edit.text() != '') else '0') self.onuid = int(self.__onuid_edit.text() if ( self.__onuid_edit.text() != '') else '1') self.accept() @pyqtSlot('QString') def __on_host_edit_change(self, text): if self.__host_reg.exactMatch(text): self.__host_edit.setStyleSheet( 'border: 2px groove ;border-color: green;') self.__host_correct = True else: self.__host_edit.setStyleSheet( 'border: 2px groove ;border-color: red;') self.__host_correct = False self.__check_ok() @pyqtSlot('QString') def __on_port_edit_change(self, text): if self.__port_reg.exactMatch(text): self.__port_edit.setStyleSheet( 'border: 2px groove ;border-color: green;') self.__port_correct = True else: self.__port_edit.setStyleSheet( 'border: 2px groove ;border-color: red;') self.__port_correct = False self.__check_ok() def __check_ok(self): if self.__host_correct and self.__port_correct: self.ok_btn.setEnabled(True) else: self.ok_btn.setEnabled(False)
MW.show() fn = QFileDialog.getOpenFileName(None, "Select a Test Book") print(fn) fh = QFile(fn) if not fh.open(QFile.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QTextStream(fh) stream.setCodec("UTF-8") IMC.editWidget.setPlainText(stream.readAll()) # load the editor doc widj.docWillChange() # Code from pqEdit to parse a doc by lines and extract page seps. reLineSep = QRegExp( u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*', Qt.CaseSensitive) qtb = IMC.editWidget.document().begin() # first text block IMC.pageTable.clear() while qtb != IMC.editWidget.document().end(): # up to end of document qsLine = qtb.text() # text of line as qstring if reLineSep.exactMatch(qsLine): # a page separator qsfilenum = reLineSep.capturedTexts()[1] qsproofers = reLineSep.capturedTexts()[2] # proofer names can contain spaces, replace with en-space char qsproofers.replace(QChar(" "), QChar(0x2002)) tcursor = QTextCursor(IMC.editWidget.document()) tcursor.setPosition(qtb.position()) IMC.pageTable.loadPsep(tcursor, qsfilenum, qsproofers) # ignore non-seps qtb = qtb.next() widj.docHasChanged() app.exec_()
class SvnStatusMonitorThread(VcsStatusMonitorThread): """ Class implementing the VCS status monitor thread class for Subversion. """ def __init__(self, interval, projectDir, vcs, parent = None): """ Constructor @param interval new interval in seconds (integer) @param projectDir project directory to monitor (string or QString) @param vcs reference to the version control object @param parent reference to the parent object (QObject) """ VcsStatusMonitorThread.__init__(self, interval, projectDir, vcs, parent) self.__ioEncoding = str(Preferences.getSystem("IOEncoding")) self.rx_status1 = \ QRegExp('(.{8,9})\\s+([0-9-]+)\\s+(.+)\\s*') self.rx_status2 = \ QRegExp('(.{8,9})\\s+([0-9-]+)\\s+([0-9?]+)\\s+(\\S+)\\s+(.+)\\s*') def _performMonitor(self): """ Protected method implementing the monitoring action. This method populates the statusList member variable with a list of strings giving the status in the first column and the path relative to the project directory starting with the third column. The allowed status flags are: <ul> <li>"A" path was added but not yet comitted</li> <li>"M" path has local changes</li> <li>"O" path was removed</li> <li>"R" path was deleted and then re-added</li> <li>"U" path needs an update</li> <li>"Z" path contains a conflict</li> <li>" " path is back at normal</li> </ul> @return tuple of flag indicating successful operation (boolean) and a status message in case of non successful operation (QString) """ self.shouldUpdate = False process = QProcess() args = QStringList() args.append('status') if not Preferences.getVCS("MonitorLocalStatus"): args.append('--show-updates') args.append('--non-interactive') args.append('.') process.setWorkingDirectory(self.projectDir) process.start('svn', args) procStarted = process.waitForStarted() if procStarted: finished = process.waitForFinished(300000) if finished and process.exitCode() == 0: output = \ unicode(process.readAllStandardOutput(), self.__ioEncoding, 'replace') states = {} for line in output.splitlines(): if self.rx_status1.exactMatch(line): flags = str(self.rx_status1.cap(1)) path = self.rx_status1.cap(3).trimmed() elif self.rx_status2.exactMatch(line): flags = str(self.rx_status2.cap(1)) path = self.rx_status2.cap(5).trimmed() else: continue if flags[0] in "ACDMR" or \ (flags[0] == " " and flags[-1] == "*"): if flags[-1] == "*": status = "U" else: status = flags[0] if status == "C": status = "Z" # give it highest priority elif status == "D": status = "O" if status == "U": self.shouldUpdate = True name = unicode(path) states[name] = status try: if self.reportedStates[name] != status: self.statusList.append("%s %s" % (status, name)) except KeyError: self.statusList.append("%s %s" % (status, name)) for name in self.reportedStates.keys(): if name not in states: self.statusList.append(" %s" % name) self.reportedStates = states return True, \ self.trUtf8("Subversion status checked successfully (using svn)") else: process.kill() process.waitForFinished() return False, QString(process.readAllStandardError()) else: process.kill() process.waitForFinished() return False, self.trUtf8("Could not start the Subversion process.")
def fillInAvailableTools(self): # Operations on the selected item choices = {} # Classification for the selected item classification = "" if self.model.isDir(self.currentIndex): regex = QRegExp("\\d{4}") # match directory names with four digits name = self.model.fileName(self.currentIndex) parentname = self.model.fileName( self.model.parent(self.currentIndex)) isdir = self.model.isDir(self.currentIndex) parentisdir = self.model.isDir(self.model.parent( self.currentIndex)) # print "%s %s %s %s" % (name, parentname,isdir,parentisdir) if isdir and regex.exactMatch(name): # We have a database dir # print "Database Dir" classification = "database" elif parentisdir and regex.exactMatch(parentname): # We have a dataset # print "Dataset Dir" classification = "dataset" else: regex = QRegExp("\\d{4}") model = self.model parentIndex = model.parent(self.currentIndex) parentparentIndex = model.parent(parentIndex) parentparentname = model.fileName(parentparentIndex) parentparentisdir = model.isDir(parentparentIndex) if parentparentisdir and regex.exactMatch(parentparentname): # We have a file with a parentparent which is a database classification classification = "array" # Build up a list of available operations based on the classification tool_set_nodes = [ tool_set_node for tool_set_node in self.tool_library_node if tool_set_node.tag == 'tool_group' ] tool_file_nodes = [] for tool_set_node in tool_set_nodes: tool_file_nodes.extend( [node for node in tool_set_node if node.tag == 'tool']) # Find all tool_nodes that acts on the resolved classification # (by looking at the XML node 'acts_on') for tool_node in tool_file_nodes: acts_on_node = tool_node.find('acts_on') exports_to_node = tool_node.find('exports_to') if acts_on_node is None or exports_to_node is None: # This tool doesn't export anything continue tool_classifications = acts_on_node.text.split(',') exports_to_value = exports_to_node.text if classification in tool_classifications: choices[exports_to_value] = tool_node self.classification = classification return choices
MW.setCentralWidget(widj) MW.setWinModStatus = setWinModStatus MW.show() fn = QFileDialog.getOpenFileName(None,"Select a Test Book") print(fn) fh = QFile(fn) if not fh.open(QFile.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QTextStream(fh) stream.setCodec("UTF-8") IMC.editWidget.setPlainText(stream.readAll()) # load the editor doc widj.docWillChange() # Code from pqEdit to parse a doc by lines and extract page seps. reLineSep = QRegExp(u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*',Qt.CaseSensitive) qtb = IMC.editWidget.document().begin() # first text block IMC.pageTable.clear() while qtb != IMC.editWidget.document().end(): # up to end of document qsLine = qtb.text() # text of line as qstring if reLineSep.exactMatch(qsLine): # a page separator qsfilenum = reLineSep.capturedTexts()[1] qsproofers = reLineSep.capturedTexts()[2] # proofer names can contain spaces, replace with en-space char qsproofers.replace(QChar(" "),QChar(0x2002)) tcursor = QTextCursor(IMC.editWidget.document()) tcursor.setPosition(qtb.position()) IMC.pageTable.loadPsep(tcursor, qsfilenum, qsproofers) # ignore non-seps qtb = qtb.next() widj.docHasChanged() app.exec_()
class NewConnectionDlg(QDialog): def __init__(self): QDialog.__init__(self) self.host = '' self.port = 0 self.schema = '' self.__host_reg = QRegExp( "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$") self.__port_reg = QRegExp("[1-9][0-9]{0,4}") self.__host_correct = False self.__port_correct = False self.__setup_ui() self.__connect_slot() def __setup_ui(self): self.setMaximumSize(300, 200) self.setMinimumSize(300, 200) vlayout = QVBoxLayout() host_layout = QHBoxLayout() port_layout = QHBoxLayout() schema_layout = QHBoxLayout() btn_layout = QHBoxLayout() host_layout.addWidget(QLabel('Host'), 3) #self.__host_edit = QLineEdit('192.168.184.128') self.__host_edit = QLineEdit() self.__host_edit.setValidator(QRegExpValidator(self.__host_reg)) host_layout.addWidget(self.__host_edit, 7) port_layout.addWidget(QLabel('Port'), 3) #self.__port_edit = QLineEdit('6641') self.__port_edit = QLineEdit() self.__port_edit.setValidator(QRegExpValidator(self.__port_reg)) port_layout.addWidget(self.__port_edit, 7) schema_layout.addWidget(QLabel('Schema'), 3) self.__schema_combo_box = QComboBox() self.__schema_combo_box.addItems( QStringList() << 'Open_vSwitch' << 'OVN_Northbound' << 'OVN_Southbound' << 'hardware_vtep') self.__schema_combo_box.view().setSpacing(3) #self.__schema_combo_box.setCurrentIndex(1) schema_layout.addWidget(self.__schema_combo_box, 7) self.ok_btn = QPushButton('ok') #self.ok_btn.setFlat(True) self.ok_btn.setEnabled(False) self.cancel_btn = QPushButton('cancel') btn_layout.addWidget(self.ok_btn, 5) btn_layout.addWidget(self.cancel_btn, 5) vlayout.addLayout(host_layout) vlayout.addLayout(port_layout) vlayout.addLayout(schema_layout) vlayout.addLayout(btn_layout) self.setLayout(vlayout) def __connect_slot(self): self.connect(self.ok_btn, SIGNAL('clicked()'), self, SLOT('__on_ok_btn()')) self.connect(self.cancel_btn, SIGNAL('clicked()'), self, SLOT('reject()')) self.connect(self.__host_edit, SIGNAL('textChanged(QString)'), self, SLOT('__on_host_edit_change(QString)')) self.connect(self.__port_edit, SIGNAL('textChanged(QString)'), self, SLOT('__on_port_edit_change(QString)')) @pyqtSlot() def __on_ok_btn(self): self.host = to_python_str(self.__host_edit.text()) self.port = int(self.__port_edit.text() if ( self.__port_edit.text() != '') else '0') self.schema = to_python_str(self.__schema_combo_box.currentText()) self.accept() @pyqtSlot('QString') def __on_host_edit_change(self, text): if self.__host_reg.exactMatch(text): self.__host_edit.setStyleSheet( 'border: 2px groove ;border-color: green;') self.__host_correct = True else: self.__host_edit.setStyleSheet( 'border: 2px groove ;border-color: red;') self.__host_correct = False self.__check_ok() @pyqtSlot('QString') def __on_port_edit_change(self, text): if self.__port_reg.exactMatch(text): self.__port_edit.setStyleSheet( 'border: 2px groove ;border-color: green;') self.__port_correct = True else: self.__port_edit.setStyleSheet( 'border: 2px groove ;border-color: red;') self.__port_correct = False self.__check_ok() def __check_ok(self): if self.__host_correct and self.__port_correct: self.ok_btn.setEnabled(True) else: self.ok_btn.setEnabled(False)
def loadMetadata(self,metaStream): sectionRE = QRegExp( u"\{\{(" + '|'.join ( ['PAGETABLE','CHARCENSUS','WORDCENSUS','BOOKMARKS', 'NOTES','GOODWORDS','BADWORDS','CURSOR','VERSION', 'STALECENSUS','NEEDSPELLCHECK','ENCODING', 'DOCHASH', 'MAINDICT'] ) \ + u")(.*)\}\}", Qt.CaseSensitive) metaVersion = 0 # base version while not metaStream.atEnd() : qline = metaStream.readLine().trimmed() if qline.isEmpty() : continue # allow blank lines between sections if sectionRE.exactMatch(qline) : # section start section = sectionRE.cap(1) argument = unicode(sectionRE.cap(2).trimmed()) endsec = QString(u"{{/" + section + u"}}") if section == u"VERSION": if len(argument) != 0 : metaVersion = int(argument) continue # no more data after {{VERSION x }} elif section == u"STALECENSUS" : if argument == u"TRUE" : IMC.staleCensus = IMC.staleCensusLoaded continue # no more data after {{STALECENSUS x}} elif section == u"NEEDSPELLCHECK" : if argument == u"TRUE" : IMC.needSpellCheck = True continue # no more data after {{NEEDSPELLCHECK x}} elif section == u"ENCODING" : IMC.bookSaveEncoding = QString(argument) continue elif section == u"MAINDICT" : IMC.bookMainDict = QString(argument) continue elif section == u"DOCHASH" : IMC.metaHash = argument continue elif section == u"PAGETABLE": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and (not qline.isEmpty()): IMC.pageTable.metaStringIn(qline) qline = metaStream.readLine() continue elif section == u"CHARCENSUS": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and (not qline.isEmpty()): # can't just .split the char census, the first # char is the char being counted and it can be a space. str = unicode(qline) parts = str[2:].split(' ') IMC.charCensus.append(QString(str[0]),int(parts[0]),int(parts[1])) qline = metaStream.readLine() continue elif section == u"WORDCENSUS": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and (not qline.isEmpty()): parts = unicode(qline).split(' ') IMC.wordCensus.append(QString(parts[0]),int(parts[1]),int(parts[2])) qline = metaStream.readLine() continue elif section == u"BOOKMARKS": qline = metaStream.readLine() while (not qline.startsWith(endsec)) and (not qline.isEmpty()): parts = unicode(qline).split(' ') tc = QTextCursor(self.document() ) tc.setPosition(int(parts[1])) if len(parts) == 3 : # early versions didn't save anchor tc.movePosition(int(parts[2]),QTextCursor.KeepAnchor) self.bookMarkList[int(parts[0])] = tc qline = metaStream.readLine() continue elif section == u"NOTES": e = IMC.notesEditor e.setUndoRedoEnabled(False) qline = metaStream.readLine() while (not qline.startsWith(endsec)) and not metaStream.atEnd(): if qline.startsWith(u"\xfffd"): # escaped {{ qline.remove(0,1) e.appendPlainText(qline) qline = metaStream.readLine() e.setUndoRedoEnabled(True) continue elif section == u"GOODWORDS" : # not going to bother checking for endsec return, # if it isn't that then we will shortly fail anyway w = IMC.goodWordList.load(metaStream,endsec) continue elif section == u"BADWORDS" : w = IMC.badWordList.load(metaStream,endsec) continue elif section == u"CURSOR" : # restore selection as of save p1p2 = argument.split(' ') tc = QTextCursor(self.document()) tc.setPosition(int(p1p2[0]),QTextCursor.MoveAnchor) tc.setPosition(int(p1p2[1]),QTextCursor.KeepAnchor) self.setTextCursor(tc) else: # this can't happen; section is text captured by the RE # and we have accounted for all possibilities raise AssertionError, "impossible metadata" else: # Non-blank line that doesn't match sectionRE? pqMsgs.infoMsg( "Unexpected line in metadata: {0}".format(pqMsgs.trunc(qline,20)), "Metadata may be incomplete, suggest quit") break
def filter(self, client, arg, value, *args, **kwargs): ip_reg = QRegExp(IP_REG) if isinstance(value, list) or isinstance(value, tuple) or isinstance(value, str) or isinstance(value, int) or not ip_reg.exactMatch(value): return ArgFilterUserID(client, arg, value, *args, **kwargs) else: return ArgFilterIP(client, arg, value, *args, **kwargs)