def highlightBlock(self, text): for rule in self.rules: expression = QRegExp(rule["pattern"]) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, rule["format"]) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0)
def highlightBlock(self, text): for rule in self.rules: expression = QRegExp(rule['pattern']) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, rule['format']) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0)
def match(self, text): """ Check if label matches search criterion. Arguments: text (str): Regular expression. Returns: bool: *True* if label matches search criterion; *False* otherwise. """ regex = QRegExp(text, Qt.CaseInsensitive) return regex.indexIn(self._titlelabel.text()) != -1 or \ regex.indexIn(self.path().name()) != -1
def filterItem(self, text): """ Filter out the item. Arguments: text (str): Regular expression. """ regex = QRegExp(text, Qt.CaseInsensitive) for i in range(self._list.topLevelItemCount()): item = self._list.topLevelItem(i) cnt_visible = 0 for j in xrange(item.childCount()): sub_item = item.child(j) item_text = sub_item.text(0) hidden = text != "" and regex.indexIn(item_text) == -1 sub_item.setHidden(hidden) if not hidden: cnt_visible += 1 item.setHidden(cnt_visible == 0)
class PythonHighlighter(QSyntaxHighlighter): # {{{ Rules = [] Formats = {} KEYWORDS = [ "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield" ] BUILTINS = [ "abs", "all", "any", "basestring", "bool", "callable", "chr", "classmethod", "cmp", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "execfile", "exit", "file", "filter", "float", "frozenset", "getattr", "globals", "hasattr", "hex", "id", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "long", "map", "max", "min", "object", "oct", "open", "ord", "pow", "property", "range", "reduce", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "unichr", "unicode", "vars", "xrange", "zip" ] CONSTANTS = ["False", "True", "None", "NotImplemented", "Ellipsis"] def __init__(self, parent=None): super(PythonHighlighter, self).__init__(parent) self.initializeFormats() PythonHighlighter.Rules.append((QRegExp("|".join( [r"\b%s\b" % keyword for keyword in self.KEYWORDS])), "keyword")) PythonHighlighter.Rules.append((QRegExp("|".join( [r"\b%s\b" % builtin for builtin in self.BUILTINS])), "builtin")) PythonHighlighter.Rules.append((QRegExp("|".join([ r"\b%s\b" % constant for constant in self.CONSTANTS ])), "constant")) PythonHighlighter.Rules.append( (QRegExp(r"\b[+-]?[0-9]+[lL]?\b" r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b" r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"), "number")) PythonHighlighter.Rules.append( (QRegExp(r"\bPyQt5\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt")) PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"), "decorator")) stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""") stringRe.setMinimal(True) PythonHighlighter.Rules.append((stringRe, "string")) self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""") self.stringRe.setMinimal(True) PythonHighlighter.Rules.append((self.stringRe, "string")) self.tripleSingleRe = QRegExp(r"""'''(?!")""") self.tripleDoubleRe = QRegExp(r'''"""(?!')''') @classmethod def initializeFormats(cls): baseFormat = QTextCharFormat() baseFormat.setFontFamily('monospace') p = QApplication.instance().palette() for name, color, bold, italic in (("normal", None, False, False), ("keyword", p.color(p.Link).name(), True, False), ("builtin", p.color(p.Link).name(), False, False), ("constant", p.color(p.Link).name(), False, False), ("decorator", "#0000E0", False, False), ("comment", "#007F00", False, True), ("string", "#808000", False, False), ("number", "#924900", False, False), ("error", "#FF0000", False, False), ("pyqt", "#50621A", False, False)): fmt = QTextCharFormat(baseFormat) if color is not None: fmt.setForeground(QColor(color)) if bold: fmt.setFontWeight(QFont.Bold) if italic: fmt.setFontItalic(italic) cls.Formats[name] = fmt def highlightBlock(self, text): NORMAL, TRIPLESINGLE, TRIPLEDOUBLE, ERROR = range(4) textLength = len(text) prevState = self.previousBlockState() self.setFormat(0, textLength, PythonHighlighter.Formats["normal"]) if text.startswith("Traceback") or text.startswith("Error: "): self.setCurrentBlockState(ERROR) self.setFormat(0, textLength, PythonHighlighter.Formats["error"]) return if prevState == ERROR and \ not (text.startswith('>>>') or text.startswith("#")): self.setCurrentBlockState(ERROR) self.setFormat(0, textLength, PythonHighlighter.Formats["error"]) return for regex, format in PythonHighlighter.Rules: i = regex.indexIn(text) while i >= 0: length = regex.matchedLength() self.setFormat(i, length, PythonHighlighter.Formats[format]) i = regex.indexIn(text, i + length) # Slow but good quality highlighting for comments. For more # speed, comment this out and add the following to __init__: # PythonHighlighter.Rules.append((QRegExp(r"#.*"), "comment")) if not text: pass elif text[0] == "#": self.setFormat(0, len(text), PythonHighlighter.Formats["comment"]) else: stack = [] for i, c in enumerate(text): if c in ('"', "'"): if stack and stack[-1] == c: stack.pop() else: stack.append(c) elif c == "#" and len(stack) == 0: self.setFormat(i, len(text), PythonHighlighter.Formats["comment"]) break self.setCurrentBlockState(NORMAL) if self.stringRe.indexIn(text) != -1: return # This is fooled by triple quotes inside single quoted strings for i, state in ((self.tripleSingleRe.indexIn(text), TRIPLESINGLE), (self.tripleDoubleRe.indexIn(text), TRIPLEDOUBLE)): if self.previousBlockState() == state: if i == -1: i = len(text) self.setCurrentBlockState(state) self.setFormat(0, i + 3, PythonHighlighter.Formats["string"]) elif i > -1: self.setCurrentBlockState(state) self.setFormat(i, len(text), PythonHighlighter.Formats["string"]) def rehighlight(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QSyntaxHighlighter.rehighlight(self) QApplication.restoreOverrideCursor()
class PythonHighlighter(QSyntaxHighlighter): # {{{ Rules = [] Formats = {} KEYWORDS = ["and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield"] BUILTINS = ["abs", "all", "any", "basestring", "bool", "callable", "chr", "classmethod", "cmp", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "execfile", "exit", "file", "filter", "float", "frozenset", "getattr", "globals", "hasattr", "hex", "id", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "long", "map", "max", "min", "object", "oct", "open", "ord", "pow", "property", "range", "reduce", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "unichr", "unicode", "vars", "xrange", "zip"] CONSTANTS = ["False", "True", "None", "NotImplemented", "Ellipsis"] def __init__(self, parent=None): super(PythonHighlighter, self).__init__(parent) self.initializeFormats() PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS])), "keyword")) PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % builtin for builtin in self.BUILTINS])), "builtin")) PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % constant for constant in self.CONSTANTS])), "constant")) PythonHighlighter.Rules.append((QRegExp( r"\b[+-]?[0-9]+[lL]?\b" r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b" r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"), "number")) PythonHighlighter.Rules.append((QRegExp( r"\bPyQt5\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt")) PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"), "decorator")) stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""") stringRe.setMinimal(True) PythonHighlighter.Rules.append((stringRe, "string")) self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""") self.stringRe.setMinimal(True) PythonHighlighter.Rules.append((self.stringRe, "string")) self.tripleSingleRe = QRegExp(r"""'''(?!")""") self.tripleDoubleRe = QRegExp(r'''"""(?!')''') @classmethod def initializeFormats(cls): if cls.Formats: return baseFormat = QTextCharFormat() baseFormat.setFontFamily('monospace') baseFormat.setFontPointSize(11) for name, color, bold, italic in ( ("normal", "#000000", False, False), ("keyword", "#000080", True, False), ("builtin", "#0000A0", False, False), ("constant", "#0000C0", False, False), ("decorator", "#0000E0", False, False), ("comment", "#007F00", False, True), ("string", "#808000", False, False), ("number", "#924900", False, False), ("error", "#FF0000", False, False), ("pyqt", "#50621A", False, False)): format = QTextCharFormat(baseFormat) format.setForeground(QColor(color)) if bold: format.setFontWeight(QFont.Bold) format.setFontItalic(italic) cls.Formats[name] = format def highlightBlock(self, text): NORMAL, TRIPLESINGLE, TRIPLEDOUBLE, ERROR = range(4) textLength = len(text) prevState = self.previousBlockState() self.setFormat(0, textLength, PythonHighlighter.Formats["normal"]) if text.startswith(u"Traceback") or text.startswith(u"Error: "): self.setCurrentBlockState(ERROR) self.setFormat(0, textLength, PythonHighlighter.Formats["error"]) return if prevState == ERROR and \ not (text.startswith(u'>>>') or text.startswith(u"#")): self.setCurrentBlockState(ERROR) self.setFormat(0, textLength, PythonHighlighter.Formats["error"]) return for regex, format in PythonHighlighter.Rules: i = regex.indexIn(text) while i >= 0: length = regex.matchedLength() self.setFormat(i, length, PythonHighlighter.Formats[format]) i = regex.indexIn(text, i + length) # Slow but good quality highlighting for comments. For more # speed, comment this out and add the following to __init__: # PythonHighlighter.Rules.append((QRegExp(r"#.*"), "comment")) if not text: pass elif text[0] == u"#": self.setFormat(0, len(text), PythonHighlighter.Formats["comment"]) else: stack = [] for i, c in enumerate(text): if c in (u'"', u"'"): if stack and stack[-1] == c: stack.pop() else: stack.append(c) elif c == u"#" and len(stack) == 0: self.setFormat(i, len(text), PythonHighlighter.Formats["comment"]) break self.setCurrentBlockState(NORMAL) if self.stringRe.indexIn(text) != -1: return # This is fooled by triple quotes inside single quoted strings for i, state in ((self.tripleSingleRe.indexIn(text), TRIPLESINGLE), (self.tripleDoubleRe.indexIn(text), TRIPLEDOUBLE)): if self.previousBlockState() == state: if i == -1: i = len(text) self.setCurrentBlockState(state) self.setFormat(0, i + 3, PythonHighlighter.Formats["string"]) elif i > -1: self.setCurrentBlockState(state) self.setFormat(i, len(text), PythonHighlighter.Formats["string"]) def rehighlight(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QSyntaxHighlighter.rehighlight(self) QApplication.restoreOverrideCursor()
def Mr_Proper(self): self.logger.warning("FLSQLITE: FIXME: Mr_Proper no regenera tablas") util = FLUtil() self.db_.dbAux().transaction() rx = QRegExp("^.*[\\d][\\d][\\d][\\d].[\\d][\\d].*[\\d][\\d]$") rx2 = QRegExp("^.*alteredtable[\\d][\\d][\\d][\\d].*$") qry = FLSqlQuery(None, "dbAux") qry2 = FLSqlQuery(None, "dbAux") qry3 = FLSqlQuery(None, "dbAux") steps = 0 item = "" rx3 = QRegExp("^.*\\d{6,9}$") #listOldBks = self.tables("").grep(rx3) listOldBks_prev = self.tables("") listOldBks = [] for l in listOldBks_prev: if rx3.indexIn(l) > -1: listOldBks.append(l) qry.exec_("select nombre from flfiles") util.createProgressDialog(util.tr("Borrando backups"), len(listOldBks) + qry.size() + 5) while qry.next(): item = qry.value(0) if rx.indexIn(item) > -1 or rx2.indexIn(item) > -1: util.setLabelText(util.tr("Borrando regisro %s" % item)) qry2.exec_("delete from flfiles where nombre = '%s'" % item) if item.find("alteredtable") > -1: if item.replace(".mtd", "") in self.tables(""): util.setLabelText(util.tr("Borrando tabla %s" % item)) qry2.exec_("drop table %s" % item.replace(".mtd", "")) steps = steps + 1 util.setProgress(steps) for item in listOldBks: if item in self.tables(""): util.tr("Borrando tabla %s" % item) util.setLabelText(util.tr("Borrando tabla %s" % item)) qry2.exec_("drop table %s" % item) steps = steps + 1 util.setProgress(steps) util.setLabelText(util.tr("Inicializando cachés")) steps = steps + 1 util.setProgress(steps) qry.exec_("delete from flmetadata") qry.exec_("delete from flvar") self.db_.manager().cleanupMetaData() self.db_.dbAux().commit() util.setLabelText(util.tr("Vacunando base de datos")) steps = steps + 1 util.setProgress(steps) qry3.exec_("vacuum") steps = steps + 1 util.setProgress(steps) util.destroyProgressDialog()