Beispiel #1
0
    def __init__(self, document):
        QSyntaxHighlighter.__init__(self, document)


        self.tri_single = (QRegularExpression("'''"), 1, STYLES['string2'])
        self.tri_double = (QRegularExpression('"""'), 2, STYLES['string2'])

        rules = []

        # Keyword, operator, and brace rules
        rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
            for w in PythonHighlighter.keywords]
        rules += [(r'%s' % o, 0, STYLES['operator'])
            for o in PythonHighlighter.operators]
        rules += [(r'%s' % b, 0, STYLES['brace'])
            for b in PythonHighlighter.braces]

        # All other rules
        rules += [
            (r'\bself\b', 0, STYLES['self']),
            (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
            (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
            (r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
            (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
            (r'#[^\n]*', 0, STYLES['comment']),
            (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']),
            (r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
            (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0, STYLES['numbers']),
        ]

        # Создайте QRegExp для каждого шаблона
        self.rules = [(QRegularExpression(pat), index, fmt)
            for (pat, index, fmt) in rules]
Beispiel #2
0
    def set_plain_text_format(self):
        # format for name labels
        regex_label_name = QRegularExpression("label_pl_[1-6]_name")
        for label_name in self.findChildren(QLabel, regex_label_name,
                                            Qt.FindChildrenRecursively):
            label_name: QLabel
            label_name.setTextFormat(Qt.PlainText)

        # format for stack of each player
        regex_label_btc = QRegularExpression("label_pl_[1-6]_btc")
        for label_btc in self.findChildren(QLabel, regex_label_btc,
                                           Qt.FindChildrenRecursively):
            label_name: QLabel
            label_btc.setTextFormat(Qt.PlainText)

        # format for bet amount of each player
        regex_label_bet = QRegularExpression("label_pl_[1-6]_bet_amt")
        for label_bet in self.findChildren(QLabel, regex_label_bet,
                                           Qt.FindChildrenRecursively):
            label_name: QLabel
            label_bet.setTextFormat(Qt.PlainText)

        # for pot and result label
        self.ui.label_result.setTextFormat(Qt.PlainText)
        self.ui.label_pot.setTextFormat(Qt.PlainText)
Beispiel #3
0
 def search_highlight(self):
     """The function that will be called whenever the
     search area is submitted. It will search within
     the text_field and highlights matches."""
     cursor = self.text_field.textCursor()
     char_format = QTextCharFormat()
     cursor.select(QTextCursor.Document)
     cursor.mergeCharFormat(char_format)
     cursor.clearSelection()
     char_format.setBackground(QBrush(QColor('yellow')))
     regex = QRegularExpression(self.ui.search_area.text())
     matches = regex.globalMatch(self.text_field.toPlainText())
     _matches = []
     while matches.hasNext():
         _matches.append(matches.next())
     self.search_matches = _matches
     self.ui.search_matches_label.setText('Matches: ' +
                                          str(len(self.search_matches)))
     self.ui.search_progress_bar.setRange(0, len(self.search_matches))
     if len(self.search_matches) > 100:
         self.ui.search_progress_bar.show()
     match_count = 1
     for match in self.search_matches:
         if match_count > 1000:
             # TODO: implement proper handling of > 1000 matches
             break
         self.ui.search_progress_bar.setValue(match_count)
         match_count += 1
         cursor.setPosition(match.capturedStart())
         cursor.setPosition(match.capturedEnd(), QTextCursor.KeepAnchor)
         cursor.mergeCharFormat(format)
     self.ui.search_progress_bar.hide()
Beispiel #4
0
    def procurar(self):
        if not self.diretorio:
            Ui_Dialog(text="selecione o diretorio alvo primeiro",
                      title="diretorio alvo",
                      buttonText="selecionar",
                      action=self.selecionarDiretorioDialog)
            return

        self.txtAlvo = self.lne_textAlvo.text()
        print(self.txtAlvo)
        if self.txtAlvo == '' or self.txtAlvo == 'Texto alvo':
            a = Ui_Entry(
                parent=self,
                lblText='digite o texto alvo, que será procurado',
                title="valro alvo",
            )
            a.signal.connect(self.dialogPronto)
            return

        exp = self.lne_textAlvo.text()
        if self.cb_palavraToda.isChecked():
            exp = "\\b" + exp + "\\b"

        if not self.cb_keySensitive.isChecked():
            self.expression = QRegularExpression(exp)
        else:
            self.expression = QRegularExpression(
                exp, QRegularExpression.CaseInsensitiveOption)

        t = refactorThread(self.diretorio, self.expression)
        t.appendTextSigal.connect(self.txt_textoAlvo.append)
        t.setTextSignal.connect(self.txt_textoAlvo.setText)
        t.statusBarSignal.connect(self.lbl_status.setText)
        t.focousSignal.connect(self.setFocousFormat)
        t.start()
    def highlight(self, regex: QRegularExpression, color: QColor = QColor(Qt.yellow)):
        if regex.pattern() == "":
            return

        self.moveCursor(QTextCursor.Start)
        matches = []
        it: QRegularExpressionMatchIterator = regex.globalMatch(self.toPlainText())
        while it.hasNext():
            match: QRegularExpressionMatch = it.next()
            if not match.hasMatch():
                continue
            begin = match.capturedStart()
            end = match.capturedEnd()

            matchSelection: QTextEdit.ExtraSelection = QTextEdit.ExtraSelection()
            fmt: QTextCharFormat = matchSelection.format
            fmt.setBackground(color)

            matchSelection.cursor = self.textCursor()
            matchSelection.cursor.setPosition(begin, QTextCursor.MoveAnchor)
            matchSelection.cursor.setPosition(end, QTextCursor.KeepAnchor)
            matches.append(matchSelection)

        self.setExtraSelections(matches)
        self.moveCursor(QTextCursor.Start)
Beispiel #6
0
 def highlightBlock(self, text):
     regExp = QRegularExpression("[0-9]")
     matchIterator = regExp.globalMatch(text)
     while matchIterator.hasNext():
         match = matchIterator.next()
         self.setFormat(match.capturedStart(), match.capturedLength(),
                        self.numberFormat)
Beispiel #7
0
    def __init__(self, document):
        QSyntaxHighlighter.__init__(self, document)

        rules = []

        # Keyword, operator, and brace rules
        rules += [(r'\b%s\b' % w, 0, self.STYLES['dot_keywords'],
                   "dot_keywords", []) for w in PythonHighlighter.dot_keywords]

        patterns_cond_bool_operators = [
            (r'\b%s\b' % c, 0, self.STYLES['cond_bool_operators'],
             "cond_bool_operators", [])
            for c in PythonHighlighter.cond_bool_operators
        ]
        rules_cond_bool_operators = [
            (QRegularExpression(pat), index, fmt, ruleid, subrules)
            for (pat, index, fmt, ruleid,
                 subrules) in patterns_cond_bool_operators
        ]

        patterns_cond_operators = [
            (r'\b%s\b' % c, 0, self.STYLES['cond_operators'], "cond_operators",
             []) for c in PythonHighlighter.cond_operators
        ]
        rules_cond_operators = [
            (QRegularExpression(pat), index, fmt, ruleid, subrules)
            for (pat, index, fmt, ruleid, subrules) in patterns_cond_operators
        ]

        patterns_cond_keywords = [
            (r'\b%s\b' % c, 0, self.STYLES['cond_keywords'], "cond_keywords",
             []) for c in PythonHighlighter.cond_keywords
        ]
        rules_cond_keywords = [
            (QRegularExpression(pat), index, fmt, ruleid, subrules)
            for (pat, index, fmt, ruleid, subrules) in patterns_cond_keywords
        ]

        # All other rules
        rules += [
            # Conditions
            (r'cond(ition)? *= *"[^"]*(\\.[^"\\]*)*"', 0,
             self.STYLES['default'], "cond1", rules_cond_operators +
             rules_cond_keywords + rules_cond_bool_operators),
            (r'cond(ition)? *=[^,\]]*[,\]]', 0, self.STYLES['default'],
             "cond2", rules_cond_operators + rules_cond_keywords +
             rules_cond_bool_operators),

            # Single-quoted string, possibly containing escape sequences
            (r"'[^'\\]*(\\.[^'\\]*)*'", 0, self.STYLES['default'],
             "singlequotedstrings", []),

            # From '//' until a newline: comments
            (r'^//[^\n]*', 0, self.STYLES['comment'], "comment", []),
        ]

        # Build a QRegularExpression for each pattern
        self.rules = [(QRegularExpression(pat), index, fmt, ruleid, subrules)
                      for (pat, index, fmt, ruleid, subrules) in rules]
Beispiel #8
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.setAttribute(Qt.WA_QuitOnClose, False)
     self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint
                         | Qt.WindowSystemMenuHint)
     self.setWindowTitle(_('Base Conversions'))
     self.value = 0
     self.numBits = 32
     self.twosComplement = False
     layout = QVBoxLayout(self)
     layout.setSpacing(0)
     decimalLabel = QLabel(_('&Decmal'))
     layout.addWidget(decimalLabel)
     decimalEdit = QLineEdit()
     decimalLabel.setBuddy(decimalEdit)
     decimalEdit.base = 10
     decRegEx = QRegularExpression('[-0-9]*')
     decimalEdit.setValidator(QRegularExpressionValidator(decRegEx))
     layout.addWidget(decimalEdit)
     layout.addSpacing(8)
     hexLabel = QLabel(_('&Hex'))
     layout.addWidget(hexLabel)
     hexEdit = QLineEdit()
     hexLabel.setBuddy(hexEdit)
     hexEdit.base = 16
     hexRegEx = QRegularExpression('[-0-9a-fA-F]*')
     hexEdit.setValidator(QRegularExpressionValidator(hexRegEx))
     layout.addWidget(hexEdit)
     layout.addSpacing(8)
     octalLabel = QLabel(_('&Octal'))
     layout.addWidget(octalLabel)
     octalEdit = QLineEdit()
     octalLabel.setBuddy(octalEdit)
     octalEdit.base = 8
     octRegEx = QRegularExpression('[-0-7]*')
     octalEdit.setValidator(QRegularExpressionValidator(octRegEx))
     layout.addWidget(octalEdit)
     layout.addSpacing(8)
     binaryLabel = QLabel(_('&Binary'))
     layout.addWidget(binaryLabel)
     binaryEdit = QLineEdit()
     binaryLabel.setBuddy(binaryEdit)
     binaryEdit.base = 2
     binRegEx = QRegularExpression('[-01]*')
     binaryEdit.setValidator(QRegularExpressionValidator(binRegEx))
     layout.addWidget(binaryEdit)
     layout.addSpacing(8)
     self.bitsButton = QPushButton('')
     self.setButtonLabel()
     layout.addWidget(self.bitsButton)
     self.bitsButton.clicked.connect(self.changeBitSettings)
     layout.addSpacing(8)
     closeButton = QPushButton(_('&Close'))
     layout.addWidget(closeButton)
     closeButton.clicked.connect(self.close)
     self.editors = (decimalEdit, hexEdit, octalEdit, binaryEdit)
     for editor in self.editors:
         editor.textEdited.connect(self.updateValue)
Beispiel #9
0
 def __init__(self, doc, pattern, color):
     super().__init__(doc)
     self._format = QTextCharFormat()
     self._format.setForeground(color)
     words = pattern.split()
     words.sort(key=len, reverse=True)
     pat = "|".join(re.escape(word) for word in words)
     self._expression = QRegularExpression(
         pat, QRegularExpression.CaseInsensitiveOption)
Beispiel #10
0
 def setExpression(self, exp, caseSensitive, wholeWord):
     if wholeWord:
         exp = "\\b" + exp + "\\b"
         print(exp)
     if caseSensitive:
         self.expression = QRegularExpression(exp)
     else:
         self.expression = QRegularExpression(
             exp, QRegularExpression.CaseInsensitiveOption)
    def _init_line_edits(self):
        validator = QRegularExpressionValidator(QRegularExpression("[^ ]+"))

        self.name_line_edit.setValidator(validator)
        self.symbol_line_edit.setValidator(validator)
        self.unit_line_edit.setValidator(validator)
        self.unit_net_price_line_edit.setValidator(
            QRegularExpressionValidator(QRegularExpression("\d+(,\d{2})?")))
        self.vat_line_edit.setValidator(
            QRegularExpressionValidator(QRegularExpression("\d{1,2}")))
Beispiel #12
0
 def highlightBlock(self, text):
     for pattern, fmt in self.highlightingRules:
         regex = QRegularExpression(pattern)
         i = regex.globalMatch(text)
         while i.hasNext():
             match = i.next()
             start = match.capturedStart()
             length = match.capturedLength()
             self.setFormat(start, length, fmt)
     self.setCurrentBlockState(0)
Beispiel #13
0
 def highlightBlock(self, text):
     for pattern, fmt in self.highlightingRules:
         regex = QRegularExpression(pattern)
         i = regex.globalMatch(text)
         while i.hasNext():
             match = i.next()
             start = match.capturedStart()
             length = match.capturedLength()
             self.setFormat(start, length, fmt)
     self.setCurrentBlockState(0)
Beispiel #14
0
    def addBlockRule(self, startPattern, endPattern, textFormat):
        """
        Add a block syntax highlighting rule, that begins with regex string
        *startPattern* and ends with *endPattern* formatted according to
        QTextCharFormat_ *format*.

        .. _QTextCharFormat: http://doc.qt.io/qt-5/qtextcharformat.html
        """
        startRegex = QRegularExpression(startPattern)
        endRegex = QRegularExpression(endPattern)
        self._blockHighlightingRules.append((startRegex, endRegex, textFormat))
Beispiel #15
0
    def highlightBlock(self, text):
        highlightFormat = QTextCharFormat()
        highlightFormat.setForeground(Qt.red)
        highlightFormat.setBackground(Qt.black)
        highlightFormat.setFontWeight(QFont.Bold)

        regex = QRegularExpression(self.query)
        it = regex.globalMatch(text)
        while(it.hasNext()):
            match = it.next()
            self.setFormat(match.capturedStart(),
                           match.capturedLength(), highlightFormat)
    def __setup_validators(self):
        positive_integer = QRegularExpression(r"\d+")
        positive_integer_validator = QRegularExpressionValidator(positive_integer)

        rational = QRegularExpression(r"-?\d+\.\d+")
        rational_validator = QRegularExpressionValidator(rational)

        self.__ui.x0_Input.setValidator(rational_validator)
        self.__ui.y0_Input.setValidator(rational_validator)
        self.__ui.x_Input.setValidator(rational_validator)
        self.__ui.n_Input.setValidator(positive_integer_validator)
        self.__ui.n0_error_Input.setValidator(positive_integer_validator)
        self.__ui.n_error_Input.setValidator(positive_integer_validator)
Beispiel #17
0
    def highlightBlock(self, text):
        rExpr = QRegularExpression(self.highStr)
        matches = rExpr.globalMatch(text)

        if not matches.isValid():
            return

        while matches.hasNext():
            match = matches.next()
            if not match.isValid():
                break
            self.setFormat(match.capturedStart(), match.capturedLength(),
                           self.fmt)
 def _init_line_edits(self):
     self.name_line_edit.setValidator(
         QRegularExpressionValidator(
             QRegularExpression("[a-zA-ZĄąĆćĘꣳŃńÓ󌜯żŹź\\s]+")))
     self.lastname_line_edit.setValidator(
         QRegularExpressionValidator(
             QRegularExpression("[a-zA-ZĄąĆćĘꣳŃńÓ󌜯żŹź\\s\\-]+")))
     self.taxid_line_edit.setValidator(
         QRegularExpressionValidator(QRegularExpression("[\\d\\-?]+")))
     self.postalcode_line_edit.setValidator(
         QRegularExpressionValidator(QRegularExpression("\\d{2}\\-\\d{3}")))
     self.city_line_edit.setValidator(
         QRegularExpressionValidator(
             QRegularExpression("[a-zA-ZĄąĆćĘꣳŃńÓ󌜯żŹź\\s\\-]+")))
Beispiel #19
0
    def apply_filter(self, *args):
        text = self.filterEdit.text()
        if text:
            if self.filter_columns.currentText() == "name":
                m = QRegularExpression(text)
                if m.isValid():
                    if self.name_regex_option.currentText(
                    ) == "case-insensitive":
                        m.setPatternOptions(
                            QRegularExpression.CaseInsensitiveOption)

                    m.optimize()
                    filter = lambda row_num: m.match(
                        self.table.item(row_num, 0).text()).hasMatch()
                else:
                    return

            elif self.filter_columns.currentText() == "denticity":
                if text.isdigit():
                    filter = lambda row_num: int(
                        self.table.item(row_num, 1).text()) == int(text)
                else:
                    filter = lambda row: True

            elif self.filter_columns.currentText() == "coordinating elements":
                method = self.coordinating_elements_method.currentText()

                def filter(row_num):
                    row_key_atoms = [
                        item.strip() for item in self.table.item(
                            row_num, 2).text().split(',')
                    ]
                    search_atoms = []
                    for item in text.split():
                        for ele in item.split(','):
                            if ele.strip() != "":
                                search_atoms.append(ele)

                    if method == "exactly":
                        if all([row_key_atoms.count(element) == search_atoms.count(element) for element in set(search_atoms)]) and \
                            all([row_key_atoms.count(element) == search_atoms.count(element) for element in set(row_key_atoms)]):
                            return True
                        else:
                            return False

                    elif method == "at least":
                        if all([
                                row_key_atoms.count(element) >=
                                search_atoms.count(element)
                                for element in set(search_atoms)
                        ]):
                            return True
                        else:
                            return False

        else:
            filter = lambda row: True

        for i in range(0, self.table.rowCount()):
            self.table.setRowHidden(i, not filter(i))
Beispiel #20
0
def rxExecute(regexp, options, text, startpos):
    """
    Function to execute the given regular expression for a given text.
    
    @param regexp regular expression to validate (string)
    @param options list of options (list of string)
    @param text text to execute on (string)
    @param startpos start position for the execution (integer)
    @return tuple of a flag indicating a successful match (boolean) and
        a list of captures containing the complete match as matched string
        (string), match start (integer), match end (integer) and match length
        (integer) for each entry
    """
    valid, error, errorOffset = rxValidate(regexp, options)
    if not valid:
        return valid, error, errorOffset

    from PyQt5.QtCore import QRegularExpression
    rxOptions = QRegularExpression.NoPatternOption
    if "CaseInsensitiveOption" in options:
        rxOptions |= QRegularExpression.CaseInsensitiveOption
    if "MultilineOption" in options:
        rxOptions |= QRegularExpression.MultilineOption
    if "DotMatchesEverythingOption" in options:
        rxOptions |= QRegularExpression.DotMatchesEverythingOption
    if "ExtendedPatternSyntaxOption" in options:
        rxOptions |= QRegularExpression.ExtendedPatternSyntaxOption
    if "InvertedGreedinessOption" in options:
        rxOptions |= QRegularExpression.InvertedGreedinessOption
    if "UseUnicodePropertiesOption" in options:
        rxOptions |= QRegularExpression.UseUnicodePropertiesOption
    if "DontCaptureOption" in options:
        rxOptions |= QRegularExpression.DontCaptureOption

    matched = False
    captures = []
    re = QRegularExpression(regexp, rxOptions)
    match = re.match(text, startpos)
    if match.hasMatch():
        matched = True
        for index in range(match.lastCapturedIndex() + 1):
            captures.append([
                match.captured(index),
                match.capturedStart(index),
                match.capturedEnd(index),
                match.capturedLength(index)
            ])

    return matched, captures
def rxExecute(regexp, options, text, startpos):
    """
    Function to execute the given regular expression for a given text.
    
    @param regexp regular expression to validate (string)
    @param options list of options (list of string)
    @param text text to execute on (string)
    @param startpos start position for the execution (integer)
    @return tuple of a flag indicating a successful match (boolean) and
        a list of captures containing the complete match as matched string
        (string), match start (integer), match end (integer) and match length
        (integer) for each entry
    """
    valid, error, errorOffset = rxValidate(regexp, options)
    if not valid:
        return valid, error, errorOffset
    
    from PyQt5.QtCore import QRegularExpression
    rxOptions = QRegularExpression.NoPatternOption
    if "CaseInsensitiveOption" in options:
        rxOptions |= QRegularExpression.CaseInsensitiveOption
    if "MultilineOption" in options:
        rxOptions |= QRegularExpression.MultilineOption
    if "DotMatchesEverythingOption" in options:
        rxOptions |= QRegularExpression.DotMatchesEverythingOption
    if "ExtendedPatternSyntaxOption" in options:
        rxOptions |= QRegularExpression.ExtendedPatternSyntaxOption
    if "InvertedGreedinessOption" in options:
        rxOptions |= QRegularExpression.InvertedGreedinessOption
    if "UseUnicodePropertiesOption" in options:
        rxOptions |= QRegularExpression.UseUnicodePropertiesOption
    if "DontCaptureOption" in options:
        rxOptions |= QRegularExpression.DontCaptureOption
    
    matched = False
    captures = []
    re = QRegularExpression(regexp, rxOptions)
    match = re.match(text, startpos)
    if match.hasMatch():
        matched = True
        for index in range(match.lastCapturedIndex() + 1):
            captures.append([
                match.captured(index),
                match.capturedStart(index),
                match.capturedEnd(index),
                match.capturedLength(index)
            ])
    
    return matched, captures
Beispiel #22
0
    def __init__(self):
        '''Initializes a MainModel instance.'''
        self._searchText = ''
        self._matchCase = False
        self._includePrivateMembers = False
        self._includeInheritedMembers = False
        self._sortByType = True

        # Initialize icons.
        iconDir = f'{dirname(dirname(__file__))}/icons'
        self._icons = {
            'module': QIcon(f'{iconDir}/module.svg'),
            'abstract base class': QIcon(f'{iconDir}/abstract.svg'),
            'class': QIcon(f'{iconDir}/class.svg'),
            'function': QIcon(f'{iconDir}/function.svg'),
            'property': QIcon(f'{iconDir}/property.svg'),
            'object': QIcon(f'{iconDir}/object.svg')
        }

        # Create the unfiltered tree model.
        self._treeModel = QStandardItemModel()

        # Create regular expressions that exclude or include private members.
        self._excludePrivateRegEx = QRegularExpression('^[^_]|^__')
        self._includePrivateRegEx = QRegularExpression('')

        # Create regular expressions that exclude or include inherited members.
        self._excludeInheritedRegEx = QRegularExpression('^$')
        self._includeInheritedRegEx = QRegularExpression('')

        # Create a filtered tree model used to exclude or include private members.
        self._intermediateTreeModel = QSortFilterProxyModel()
        self._intermediateTreeModel.setSourceModel(self._treeModel)
        privateRegEx = self._includePrivateRegEx if self._includePrivateMembers else self._excludePrivateRegEx
        self._intermediateTreeModel.setFilterRegularExpression(privateRegEx)

        # Create a filtered tree model used to exclude or include inherited members.
        self._secondIntermediateTreeModel = QSortFilterProxyModel()
        self._secondIntermediateTreeModel.setSourceModel(self._intermediateTreeModel)
        self._secondIntermediateTreeModel.setFilterKeyColumn(2)
        inheritedRegEx = self._includeInheritedRegEx if self._includeInheritedMembers else self._excludeInheritedRegEx
        self._secondIntermediateTreeModel.setFilterRegularExpression(inheritedRegEx)

        # Create a filtered tree model that matches the search text.
        self._filteredTreeModel = QSortFilterProxyModel()
        self._filteredTreeModel.setSourceModel(self._secondIntermediateTreeModel)
        self._filteredTreeModel.setRecursiveFilteringEnabled(True)
        self._filteredTreeModel.setFilterFixedString(self._searchText)
        self._filteredTreeModel.setFilterCaseSensitivity(1 if self._matchCase else 0)
    def checkSpelling(self, text):
        if not self.dictionary:
            return

        wordFinder = QRegularExpression("[A-Za-z]+");
        wordIterator = wordFinder.globalMatch(text)
        while wordIterator.hasNext():
            match = wordIterator.next()
            if not self.dictionary.check(match.captured()):
                # update the word's current format
                spellingErrorformat = self.format(match.capturedStart())
                spellingErrorformat.setUnderlineColor(Qt.red)
                spellingErrorformat.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

                # set the new format
                self.setFormat(match.capturedStart(), match.capturedLength(), spellingErrorformat)
Beispiel #24
0
    def __init__(self, parent=None):

        super(Highlighter, self).__init__(parent)

        self.highlighting_rules = list()

        self.keywordFormat = QTextCharFormat()
        self.keywordFormat.setForeground(Qt.darkBlue)
        self.keywordFormat.setFontWeight(QFont.Bold)

        self.keyword_patterns = [
            '\\babort\\b', '\\bexit\\b', '\\bdo\\b', '\\bloop\\b',
            '\\bunloop\\b', '\\bbegin\\b', '\\buntil\\b', '\\bwhile\\b',
            '\\brepeat\\b', '\\bexit\\b', '\\bif\\b', '\\belse\\b',
            '\\bthen\\b', '\\bcase\\b', '\\bendcase\\b', '\\bof\\b',
            '\\bendof\\b', '\\bagain\\b', '\\bleave\\b', '\\brequire\\b',
            '\\bincluded\\b', '\\bdecimal\\b', '\\bhex\\b', '\\balso\\b',
            '\\bonly\\b', '\\bprevious\\b', '\\bcreate\\b', '\\bdoes>\\b',
            '\\bvariable\\b', 'b\\value\\b', '\\b2variable\\b',
            '\\bconstant\\b', '\\babort"\\b', '\\bdup\\b', '\\bdrop\\b',
            '\\bswap\\b', '\\bover\\b', '\\bpick\\b', '\\broll\\b',
            '\\b2dup\\b', '\\b2drop\\b', '\\b2swas\\b', '\\b2over\\b',
            '\\b!\\b', '\\bc!\\b', '\\brot\\b', '\\b@\\b', '\\bc@\\b',
            '\\b2!\\b', '\\b2@\\b', '\\band\\b', '\\bor\\b', '\\bxor\\b',
            '\\binvert\\b', '\\bnegate\\b', '\\b/\\b', '\\b/mod\\b',
            '\\bbye\\b', '\\bmod\\b', '\\brshift\\b', '\\blshift\\b'
        ]

        for pattern in self.keyword_patterns:
            self.highlighting_rules.append(
                [QRegularExpression(pattern), self.keywordFormat])
Beispiel #25
0
 def loadIntegerFloatList(self, font, src, dst):
     values = " ".join(str(val) for val in getattr(font.info, src))
     setattr(self, dst + "Edit", QLineEdit(values, self))
     validator = QRegularExpressionValidator(self)
     validator.setRegularExpression(
         QRegularExpression("(-?\d+(.\d+)?\s*)*"))
     getattr(self, dst + "Edit").setValidator(validator)
Beispiel #26
0
    def __init__(self, redactor):#*args, **kwargs
        super().__init__(redactor)
        """ this is Fanuc turn - milling simulator. If u writing similar one, use it as parent or collateral.
        To add command, create behavior function; add to special_commands list string, color, style. 
        Note, that pattern will be checked one after another, so if u have patternA thant includes patternB as a part, order matters
        """
        #self.k_XYZABC['X'] = 0.5
        #self.ABC_HEAD[2] = False#ax Z belong to table or spindle
        #print('self.k_XYZABC = ', self.k_XYZABC)

        self.update_rules()


        #self.ABC_turning_Zero['A'] =
        #print('k_XYZABC_list = ', self.k_XYZABC_list)
        #n_number = r'^\s*N(\d*)\s*'#херня какая то
        self.special_commands = [
                                [r'\s*G(1[789])\s*', self.change_plane, format('blue', 'bold')],
                                [r'G28\s*(([UVW])\s*0.?\s*)(([UVW])\s*0.?\s*)?(([UVW])\s*0.?\s*)?$', self.G28_U0_V0_W0, format('red', 'bold')],
                                [r'\s*G(9[01])\s*', self.absolut_and_reference_coord_G90_G91, format('blue', 'bold')],
                                #[r'^\s*N(\d*)\s*', self.N_number, format('blue', 'bold')],
                                 ]
        for i in range(0, len(self.special_commands)):
            self.special_commands[i][0] = QRegularExpression(self.special_commands[i][0])
            #look Perl RegularExpressions if u need

        print('self.special_commands = ', self.special_commands)
Beispiel #27
0
    def __init__(self, *, combobox_model, **kwargs):
        super(NewProfileDialog, self).__init__(**kwargs)

        self.setupUi(self)

        self.okbutton = self.buttonBox.button(QDialogButtonBox.Ok)
        self.okbutton.setDisabled(True)

        self.final_name = None
        self.copy_from = None

        self.comboBox.setModel(combobox_model)

        # according to timeit, checking if a word is in a list is
        # faster than checking against a RegExp--even a compiled RE,
        # and even if you pre-process the word to check each time
        # (e.g.: word.lower() in wordlist)
        self.name_list = [p.lower() for p in combobox_model.profiles]
        # self.name_list = [p.name.lower() for p in combobox_model.profiles]

        # this validator ensures that no spaces or invalid characters can be entered.
        # (only letters, numbers, underscores, hyphens, and periods)
        vre_str = r"[\w\d_.-]+"
        self.vre = QRegularExpression(vre_str)
        self.validator = QRegularExpressionValidator(self.vre)

        self.lineEdit.setValidator(self.validator)

        # stylesheet for invalid text
        self.ss_invalid = "QLineEdit { color: red }"

        # tooltip for invalid text
        self.tt_invalid = "Profile names must be unique"
Beispiel #28
0
    def __init__(self, max_bits=-1, bit_group_size=4):
        super().__init__()

        self.max_bits = max_bits
        self.bit_group_size = bit_group_size

        if max_bits == 0:
            self.re_acceptable = QRegularExpression('')
        elif max_bits > 0:
            self.re_acceptable = QRegularExpression(
                '^([0,1](\s[0,1]){0,%d})?$' % (max_bits - 1))
            self.re_intermediate = QRegularExpression('^(\s*[0,1]){0,%d}\s*$' %
                                                      (max_bits))
        else:
            self.re_acceptable = QRegularExpression('^([0,1](\s[0,1])*)?$')
            self.re_intermediate = QRegularExpression('^(\s*[0,1])*\s*$')
    def __init__(self, addon=False, parent=None):
        """
        Constructor
        
        @param addon flag indicating an addon firmware
        @type bool
        @param parent reference to the parent widget
        @type QWidget
        """
        super(EspFirmwareSelectionDialog, self).__init__(parent)
        self.setupUi(self)

        self.__addon = addon

        self.firmwarePicker.setMode(E5PathPickerModes.OpenFileMode)
        self.firmwarePicker.setFilters(
            self.tr("Firmware Files (*.bin);;All Files (*)"))

        self.espComboBox.addItems(["", "ESP32", "ESP8266"])

        if addon:
            self.__validator = QRegularExpressionValidator(
                QRegularExpression(r"[0-9a-fA-F]{0,4}"))
            self.addressEdit.setValidator(self.__validator)
        else:
            self.addressLabel.hide()
            self.addressEdit.hide()

        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())
Beispiel #30
0
class TextFilesProxyModel(QSortFilterProxyModel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._filter = QRegularExpression()

    def setFilter(self, filesFilter: QRegularExpression):
        if self._filter == filesFilter:
            return

        self._filter = filesFilter
        self.invalidateFilter()

    def setUseRegExp(self, useRegExp: bool):
        self._useRegExp = useRegExp
        self.invalidateFilter()

    def filterAcceptsRow(self, sourceRow: int, sourceParent: QModelIndex):
        if self._filter.pattern() == "":
            return True

        index: QModelIndex = self.sourceModel().index(sourceRow, 0, sourceParent)
        file: TextFile = self.sourceModel().data(index, Qt.UserRole).value()
        return file.contains(self._filter, self._useRegExp)

    def filteredFiles(self) -> List[TextFile]:
        files = []
        for i in range(0, self.rowCount()):
            index: QModelIndex = self.mapToSource(self.index(i, 0, QModelIndex()))
            file: TextFile = self.sourceModel().data(index, Qt.UserRole).value()
            files.append(file)
        return files
Beispiel #31
0
    def __init__(self, parent, predicates=None, functions=None):
        super(CLIFSyntaxHighlighter, self).__init__(parent)
        self.setDocument(parent.document())

        self.predicates = [] if predicates is None else predicates
        self.functions = [] if functions is None else functions

        # define formats and rules
        ignore_case = QRegularExpression.CaseInsensitiveOption
        self.rules = []

        # real colors for functions and predicates
        self.format_predicate = QTextCharFormat()
        self.format_predicate.setForeground(get_color("color_predicate"))
        self.format_function = QTextCharFormat()
        self.format_function.setForeground(get_color("color_function"))

        format_equals = QTextCharFormat()
        format_equals.setForeground(get_color("color_equals"))
        self.rules.append((QRegularExpression("="), 0, format_equals))

        format_connective = QTextCharFormat()
        format_connective.setForeground(get_color("color_connective"))
        connectives = ["AND", "OR", "IF", "IFF"]
        for c in connectives:
            self.rules.append(
                (QRegularExpression("\(" + c,
                                    ignore_case), 1, format_connective))

        format_not = QTextCharFormat()
        format_not.setForeground(get_color("color_not"))
        self.rules.append((QRegularExpression("NOT",
                                              ignore_case), 0, format_not))

        format_quantifier = QTextCharFormat()
        format_quantifier.setForeground(get_color("color_quantifier"))
        quantifiers = ["EXISTS", "FORALL"]
        for q in quantifiers:
            self.rules.append(
                (QRegularExpression("\(" + q,
                                    ignore_case), 1, format_quantifier))

        format_parentheses = QTextCharFormat()
        format_parentheses.setForeground(get_color("color_parentheses"))
        parentheses = ["\(", "\)"]
        for p in parentheses:
            self.rules.append((QRegularExpression(p), 0, format_parentheses))
Beispiel #32
0
    def onSearchBarTextChanged(self, text):
        moodleTreeView = self.findChild(QTreeView, "moodleTree")
        searchBar = self.findChild(QLineEdit, "searchBar")

        if not text:
            self.filterModel.setFilterRegularExpression(".*")
            moodleTreeView.collapseAll()
            searchBar.setStyleSheet("")
        else:
            regexp = QRegularExpression(text)
            if regexp.isValid():
                self.filterModel.setFilterRegularExpression(regexp)
                moodleTreeView.expandAll()
                searchBar.setStyleSheet("")
            else:
                log.debug("invalid search regular expression, not searching")
                searchBar.setStyleSheet("QLineEdit { color: red; }")
Beispiel #33
0
class WorkspaceNameValidator(QValidator):
    def __init__(self):
        self.regex = QRegularExpression(r"^.{1,256}$")

    def validate(self, string, pos):
        if self.regex.match(string, pos).hasMatch():
            return QValidator.Acceptable, string, pos
        return QValidator.Invalid, string, pos
def rxValidate(regexp, options):
    """
    Function to validate the given regular expression.
    
    @param regexp regular expression to validate (string)
    @param options list of options (list of string)
    @return tuple of flag indicating validity (boolean), error
        string (string) and error offset (integer)
    """
    try:
        from PyQt5.QtCore import QRegularExpression
        rxOptions = QRegularExpression.NoPatternOption
        if "CaseInsensitiveOption" in options:
            rxOptions |= QRegularExpression.CaseInsensitiveOption
        if "MultilineOption" in options:
            rxOptions |= QRegularExpression.MultilineOption
        if "DotMatchesEverythingOption" in options:
            rxOptions |= QRegularExpression.DotMatchesEverythingOption
        if "ExtendedPatternSyntaxOption" in options:
            rxOptions |= QRegularExpression.ExtendedPatternSyntaxOption
        if "InvertedGreedinessOption" in options:
            rxOptions |= QRegularExpression.InvertedGreedinessOption
        if "UseUnicodePropertiesOption" in options:
            rxOptions |= QRegularExpression.UseUnicodePropertiesOption
        if "DontCaptureOption" in options:
            rxOptions |= QRegularExpression.DontCaptureOption
        
        error = ""
        errorOffset = -1
        re = QRegularExpression(regexp, rxOptions)
        valid = re.isValid()
        if not valid:
            error = re.errorString()
            errorOffset = re.patternErrorOffset()
    except ImportError:
        valid = False
        error = "ImportError"
        errorOffset = 0
    
    return valid, error, errorOffset