Example #1
0
    def __init__(self):
        super().__init__('default')

        # override existing formats
        function_format = QTextCharFormat()
        function_format.setForeground(self._get_brush("0000ff"))
        self.formats['function'] = function_format
Example #2
0
 def fmt() -> QTextCharFormat:
     """
     Get text char formatting for this object
     """
     fmt = QTextCharFormat()
     fmt.setForeground(Conf.disasm_view_node_mnemonic_color)
     return fmt
Example #3
0
 def onReceiveLog(self, data: LogMsg):
     format = QTextCharFormat()
     format.setForeground(QBrush(QColor(data.color)))
     self.mainUI.logText.setCurrentCharFormat(format)
     self.mainUI.logText.appendPlainText(data.text)
     format.setForeground(QBrush(
         QColor('black')))  # restore to default color
     self.mainUI.logText.setCurrentCharFormat(format)
Example #4
0
def text_format(color, style=''):
    f = QTextCharFormat()
    f.setForeground(color)
    if 'bold' in style:
        f.setFontWeight(QFont.Bold)
    if 'italic' in style:
        f.setFontItalic(True)
    return f
Example #5
0
 def _formatiraj(self, r, g, b, stil=''):
     #_boja = QColor()
     _boja = QColor.fromRgb(r, g, b, 255)
     _format = QTextCharFormat()
     _format.setForeground(_boja)
     if 'bold' in stil:
         _format.setFontWeight(QFont.Bold)
     if 'italic' in stil:
         _format.setFontItalic(True)
     return _format
Example #6
0
class Highlighter(QSyntaxHighlighter):
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

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

        keywordPatterns = [
            "\\bimport\\b", "\\bcomponent\\b", "\\bcommunications\\b",
            "\\bpublishes\\b", "\\bimplements\\b", "\\bsubscribesTo\\b",
            "\\brequires\\b", "\\blanguage\\b", "\\bgui\\b", "\\boptions\\b",
            "\\binnermodelviewer\\b", "\\bstateMachine\\b", "\\bmodules\\b",
            "\\bagmagent\\b"
        ]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                                  for pattern in keywordPatterns]

        self.multiLineCommentFormat = QTextCharFormat()
        self.multiLineCommentFormat.setForeground(Qt.red)

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")

    def highlightBlock(self, text):
        for pattern, format in self.highlightingRules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)

        startIndex = 0
        if self.previousBlockState() != 1:
            startIndex = self.commentStartExpression.indexIn(text)

        while startIndex >= 0:
            endIndex = self.commentEndExpression.indexIn(text, startIndex)

            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLength = len(text) - startIndex
            else:
                commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength(
                )

            self.setFormat(startIndex, commentLength,
                           self.multiLineCommentFormat)
            startIndex = self.commentStartExpression.indexIn(
                text, startIndex + commentLength)
Example #7
0
    def getTextCharFormat(self, color, style=None):
        """Return a QTextCharFormat with the given attributes."""
        textCharFormat = QTextCharFormat()
        textCharFormat.setForeground(color)
        if style is not None:
            if 'bold' in style:
                textCharFormat.setFontWeight(QFont.Bold)
            if 'italic' in style:
                textCharFormat.setFontItalic(True)

        return textCharFormat
Example #8
0
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes."""
    _color = eval('getThemeColor(ThemeColor.%s)' % color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
Example #9
0
    def highlightBlock(self, text):
        myClassFormat = QTextCharFormat()
        myClassFormat.setFontWeight(QFont.Bold)

        expression = QRegularExpression(self.pattern)
        i = expression.globalMatch(text)

        while i.hasNext():
            match = i.next()
            myClassFormat.setForeground(
                self.tagColorMap[match.capturedTexts()[0]])
            self.setFormat(match.capturedStart(), match.capturedLength(),
                           myClassFormat)
Example #10
0
class PythonHighlighter(QSyntaxHighlighter):
    def __init__(self, document):
        super(PythonHighlighter, self).__init__(document)

        self.keyword_format = QTextCharFormat()
        self.keyword_format.setForeground(QtGui.QBrush(
            QtGui.QColor("#804515")))
        self.keyword_format.setFontWeight(QFont.Bold)

        self.string_format = QTextCharFormat()
        self.string_format.setForeground(QtGui.QBrush(QtGui.QColor("#116611")))

        self.operator_format = QTextCharFormat()
        self.operator_format.setForeground(
            QtGui.QBrush(QtGui.QColor("#003333")))
        self.operator_format.setFontWeight(QFont.Bold)

        self.comment_format = QTextCharFormat()
        self.comment_format.setForeground(QtGui.QBrush(
            QtGui.QColor("#888888")))

        self.selector_format = QTextCharFormat()
        self.selector_format.setForeground(
            QtGui.QBrush(QtGui.QColor("#003333")))
        self.selector_format.setFontWeight(QFont.Bold)

    def highlightBlock(self, text, *args, **kwargs):
        tokens = tokenize.generate_tokens(StringIO(text).readline)

        if not tokens:
            return

        for token_type, token_string, token_start, token_end, token_line in tokens:
            if token_type == tokenize.STRING:
                self._highlight_token(token_start, token_end,
                                      self.string_format)
            elif token_type == tokenize.COMMENT:
                self._highlight_token(token_start, token_end,
                                      self.comment_format)
            elif token_type == tokenize.OP:
                self._highlight_token(token_start, token_end,
                                      self.operator_format)
            elif token_type == tokenize.NAME and token_string in python_keywords:
                self._highlight_token(token_start, token_end,
                                      self.keyword_format)
            elif token_type == tokenize.NAME and token_string in germaninum_selectors:
                self._highlight_token(token_start, token_end,
                                      self.selector_format)

    def _highlight_token(self, token_start, token_end, format):
        self.setFormat(token_start[1], token_end[1] - token_start[1], format)
Example #11
0
    def highlightBlock(self, text):
        string_format = QTextCharFormat()
        string_format.setForeground(QColor('#E6DB74'))

        number_format = QTextCharFormat()
        number_format.setForeground(QColor('#AE81FF'))

        get_format = QTextCharFormat()
        get_format.setForeground(QColor('#25A86B'))

        post_format = QTextCharFormat()
        post_format.setForeground(QColor('#FDA60A'))

        if text.startswith('GET '):
            self.setFormat(0, len('GET'), get_format)
        if text.startswith('POST '):
            self.setFormat(0, len('POST'), post_format)

        if len(text) == 0 or text[0] not in '{}[] ':
            return

        current = 0
        for tokentype, value in JsonLexer().get_tokens(text):
            if tokentype in Name or tokentype in String:
                self.setFormat(current, len(value), string_format)
            elif tokentype in Number or tokentype in Keyword:
                self.setFormat(current, len(value), number_format)
            current += len(value)
Example #12
0
def txformat(color, style=''):
    """Return a QTextCharFormat with the given attributes.
    """
    _color = QColor()
    _color.setNamedColor(color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
Example #13
0
def txformat(color, style=''):
    """Return a QTextCharFormat with the given attributes.
    """
    _color = QColor()
    _color.setNamedColor(color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
    def __init__(self, parent, color_scheme=None):
        # TODO: Use the color scheme. it's not used right now
        super().__init__(parent, color_scheme=color_scheme)

        self.doc = parent  # type: QCodeDocument

        if FORMATS['keyword'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkBlue)
            f.setFontWeight(QFont.Bold)
            FORMATS['keyword'] = f
        if FORMATS['quotation'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            FORMATS['quotation'] = f
        if FORMATS['function'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.blue)
            f.setFontWeight(QFont.Bold)
            FORMATS['function'] = f
        if FORMATS['comment'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            f.setFontWeight(QFont.Bold)
            FORMATS['comment'] = f
Example #15
0
    def __init__(self, *args):
        super().__init__(*args)

        if FORMATS['keyword'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkBlue)
            f.setFontWeight(QFont.Bold)
            FORMATS['keyword'] = f
        if FORMATS['quotation'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            FORMATS['quotation'] = f
        if FORMATS['function'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.blue)
            f.setFontWeight(QFont.Bold)
            FORMATS['function'] = f
        if FORMATS['comment'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            f.setFontWeight(QFont.Bold)
            FORMATS['comment'] = f
Example #16
0
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes.
    """
    _color = QColor(color[0], color[1], color[2])

    _format = QTextCharFormat()
    _format.setFontFamily("Courier New")
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
Example #17
0
    def get_format(cls, color: str, style='', fontsize=None) -> QTextCharFormat:
        """Return a QTextCharFormat with the given attributes."""
        _color = QColor()
        _color.setNamedColor(color)

        _format = QTextCharFormat()
        _format.setForeground(_color)
        if 'bold' in style:
            _format.setFontWeight(QFont.Bold)
        if 'italic' in style:
            _format.setFontItalic(True)

        if fontsize:
            _format.setFontPointSize(fontsize)

        return _format
Example #18
0
    def set_calendar(self):
        """Setup Calendar widget"""
        calendar = self._window.calendar
        calendar.setGridVisible(True)
        calendar.setMinimumDate(QDate(1900, 1, 1))
        calendar.setMaximumDate(QDate.currentDate())
        calendar.setFirstDayOfWeek(Qt.Thursday)
        weekend_format = QTextCharFormat()
        weekend_format.setForeground(QBrush(Qt.green, Qt.SolidPattern))
        calendar.setWeekdayTextFormat(Qt.Saturday, weekend_format)
        calendar.setWeekdayTextFormat(Qt.Sunday, weekend_format)
        weekend_format.setForeground(QBrush(QColor('#8800BB'),
                                            Qt.SolidPattern))
        calendar.setDateTextFormat(QDate.currentDate(), weekend_format)

        calendar.clicked.connect(self._window.date_edit.setDate)
Example #19
0
    def highlightBlock(self, text):
        string_format = QTextCharFormat()
        string_format.setForeground(QColor('#E6DB74'))

        number_format = QTextCharFormat()
        number_format.setForeground(QColor('#AE81FF'))
        if len(text) == 0:
            return

        current = 0
        for tokentype, value in JsonLexer().get_tokens(text):
            if tokentype in Name or tokentype in String:
                self.setFormat(current, len(value), string_format)
            elif tokentype in Number or tokentype in Keyword:
                self.setFormat(current, len(value), number_format)
            current += len(value)
Example #20
0
 def formatText(cls, color, style=""):
     """
     Return a QTextCharFormat with the given attributes.
     """
     
     clr = QColor(*color)
 
     txt_format = QTextCharFormat()
     txt_format.setForeground(clr)
     
     if "bold" in style:
         txt_format.setFontWeight(QFont.Bold)
         
     if "italic" in style:
         txt_format.setFontItalic(True)
 
     return txt_format    
Example #21
0
def formatColor(color, style=None):
    """Return a QTextCharFormat with the given attributes.
    :param color: float3 rgb
    :type color: tuple
    :param style: the style name eg. 'bold'
    :type style: str or None
    """
    style = style or ""
    _color = QColor(*color)
    _format = QTextCharFormat()
    _format.setForeground(_color)
    if "bold" in style:
        _format.setFontWeight(QFont.Bold)
    if "italic" in style:
        _format.setFontItalic(True)

    return _format
Example #22
0
class ParagonScriptHighlighter(QSyntaxHighlighter):
    def __init__(self, document):
        super().__init__(document)
        self.error_line = None
        self.command_format = QTextCharFormat()
        self.command_format.setForeground(QtCore.Qt.darkMagenta)
        self.error_format = QTextCharFormat()
        self.error_format.setUnderlineColor(QtCore.Qt.darkRed)
        self.error_format.setUnderlineStyle(
            QtGui.QTextCharFormat.SpellCheckUnderline)
        self.error_format.setBackground(QtCore.Qt.red)

    def highlightBlock(self, text: str):
        if text.startswith("$") and not text.startswith(
                "$G") and not text.startswith("$Nu"):
            self.setFormat(0, len(text), self.command_format)
        if self.currentBlock().blockNumber() == self.error_line:
            self.setFormat(0, len(text), self.error_format)
Example #23
0
    def __init__(self, document, **options):
        Formatter.__init__(self, **options)

        self.document = document

        # Prepare format by styles
        self.styles = {}
        for token, style in self.style:
            format = QTextCharFormat()
            if style['color']:
                format.setForeground(QColor('#' + style['color']))
            if style['bold']:
                format.setFontWeight(QFont.Bold)
            if style['italic']:
                format.setFontItalic(True)
            if style['underline']:
                format.setFontUnderline(True)
            self.styles[token] = format
Example #24
0
def format(color, style=''):
    """
    Return a QTextCharFormat with the given attributes.
    """
    _color = QColor()
    if type(color) is not str:
        _color.setRgb(color[0], color[1], color[2])
    else:
        _color.setNamedColor(color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(QColor("#00CCFF"))
        keywordFormat.setFontCapitalization(QFont.AllUppercase)

        keywordPatterns = ["\\bSELECT\\b", "\\bFROM\\b", "\\bWHERE\\b",
                "\\bselect\\b", "\\bfrom\\b", "\\bwhere\\b", 
                "\\bTABLE\\b", "\\btable\\b", "\\bON\\b", "\\bon\\b",
                "\\bORDER\\b", "\\border\\b", "\\bBY\\b", "\\bby\\b",
                "\\bLIMIT\\b", "\\blimit\\b", "\\bBETWEEN\\b",
                "\\bbetween\\b", "\\bLIKE\\b", "\\blike\\b", "\\bTO\\b", "\\bto\\b",
                "\\bINNER\\b", "\\inner\\b", "\\bJOIN\\b", "\\bjoin\\b", 
                "\\bAND\\b", "\\and\\b", "\\bOR\\b", "\\bor\\b", 
                ]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                for pattern in keywordPatterns]
        
        keyword2Format = QTextCharFormat()
        keyword2Format.setForeground(QColor("#DE0000"))
        keyword2Format.setFontCapitalization(QFont.AllUppercase)

        keyword2Patterns = ["\\bCREATE\\b", "\\bcreate\\b",
                 "\\bINSERT\\b", "\\binsert\\b", "\\bUPDATE\\b", "\\bupdate\\b",
                "\\bDELETE\\b","\\bdelete\\b", "\\bREPLACE\\b", "\\breplace\\b",
                "\\bDROP\\b", "\\bdrop\\b", "\\bRENAME\\b", "\\rename\\b",
                "\\bALTER\\b", "\\alter\\b",
                "\\bSET\\b", "\\bset\\b"
                ]


        self.highlightingRules.extend([(QRegExp(pattern), keyword2Format)
                for pattern in keyword2Patterns])
        
        table_name_format = QTextCharFormat()
        table_name_format.setForeground(QColor("#00FF7F"))
        table_name_format.setFontWeight(QFont.Bold)
        table_name_patterns = ["\\b{tn}\\b".format(tn=table.name) for table in Tables]
        ex_tables = ["\\b{tn}\\b".format(tn=table.name) for table in ExclusiveDbTables]
        table_name_patterns.extend(ex_tables)
        self.highlightingRules.extend([(QRegExp(pattern), table_name_format) for pattern in table_name_patterns])

        field_name_format = QTextCharFormat()
        field_name_format.setForeground(QColor("#00FF7F"))
        field_names = []
        for table in Tables:
            field_names.extend(getFieldNames(table.name))
        for table in ExclusiveDbTables:
            field_names.extend(getAllFieldNames(table.name, False))
        field_name_patterns = ["\\b{fn}\\b".format(fn=field_name) for field_name in field_names]
        self.highlightingRules.extend([(QRegExp(pattern), field_name_format) for pattern in field_name_patterns])
Example #26
0
    def updateRules(self):
        try:
            keywordFormat = QTextCharFormat()
            keywordFormat.setForeground(QColor("#000099"))
            keywordFormat.setFontWeight(QFont.Bold)
            keywordFormat.setFontUnderline(True)
            keywordFormat.setAnchor(True)

            dict_words = self._database.getAllDictWords()
            keywordPatterns = ["\\b" + word + "\\b" for word in dict_words]
            keywordPatterns.extend(
                ["\\b" + word.upper() + "\\b" for word in dict_words])
            keywordPatterns.extend(
                ["\\b" + word.lower() + "\\b" for word in dict_words])
            self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                                      for pattern in keywordPatterns]

        except Exception as e:
            print("Failed to update the highlighting rules:", e)
Example #27
0
    def get_format(self, color, style=''):
        """
        Returns a QTextCharFormat with the given attributes
        :param color:
        :param style:
        :return:
        """
        c = QColor()
        c.setNamedColor(color)

        f = QTextCharFormat()
        f.setForeground(c)

        if 'bold' in style:
            f.setFontWeight(QFont.Bold)

        if 'italic' in style:
            f.setFontItalic(True)

        return f
Example #28
0
    def log(self, text, level=MessageType.INFO):
        if level is MessageType.INFO:
            color = "000000"
        elif level is MessageType.WARNING:
            color = "#9ece2f"
        elif level is MessageType.ERROR:
            color = "#ed2d2d"
        elif level is MessageType.SUCCESS:
            color = "#4dd30a"
        else:
            raise UndefinedMessageType(
                "Undefined message type: {type}.".format(type=level))

        line_format = QTextCharFormat()
        line_format.setForeground(QBrush(QColor(color)))
        self.text_cursor.setCharFormat(line_format)

        self.text_cursor.insertText(text + "\n")
        self.textbox.verticalScrollBar().setValue(
            self.textbox.verticalScrollBar().maximum())
Example #29
0
    def on_log_received(self, data):
        time_info = datetime.fromtimestamp((data['time'] / 1000)).isoformat()
        log_message = '%s: %s : %s' % (time_info, data['level'],
                                       data['message'])
        message_document = self.document()
        cursor_to_add = QTextCursor(message_document)
        cursor_to_add.movePosition(cursor_to_add.End)
        cursor_to_add.insertText(log_message + '\n')

        if data['level'] in COLORS:
            fmt = QTextCharFormat()
            fmt.setForeground(COLORS[data['level']])
            cursor_to_add.movePosition(cursor_to_add.PreviousBlock)
            log_lvl_data = LogLevelData(log_levels[data['level'].upper()])
            cursor_to_add.block().setUserData(log_lvl_data)
            cursor_to_add_fmt = message_document.find(data['level'],
                                                      cursor_to_add.position())
            cursor_to_add_fmt.mergeCharFormat(fmt)
            if log_levels[data['level']] > self.log_lvl:
                cursor_to_add.block().setVisible(False)
        self.ensureCursorVisible()
    def setup_editor(self):
        variable_format = QTextCharFormat()
        variable_format.setFontWeight(QFont.Bold)
        variable_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\\b[A-Z_]+\\b", variable_format)

        single_line_comment_format = QTextCharFormat()
        single_line_comment_format.setBackground(QColor("#77ff77"))
        self._highlighter.add_mapping("#[^\n]*", single_line_comment_format)

        quotation_format = QTextCharFormat()
        quotation_format.setBackground(Qt.cyan)
        quotation_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\".*\"", quotation_format)

        function_format = QTextCharFormat()
        function_format.setFontItalic(True)
        function_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\\b[a-z0-9_]+\\(.*\\)", function_format)

        font = QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self._editor = QPlainTextEdit()
        self._editor.setFont(font)
        self._highlighter.setDocument(self._editor.document())
Example #31
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

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

        keywordPatterns = [
            "\\bimport\\b", "\\bcomponent\\b", "\\bcommunications\\b",
            "\\bpublishes\\b", "\\bimplements\\b", "\\bsubscribesTo\\b",
            "\\brequires\\b", "\\blanguage\\b", "\\bgui\\b", "\\boptions\\b",
            "\\binnermodelviewer\\b", "\\bstateMachine\\b", "\\bmodules\\b",
            "\\bagmagent\\b"
        ]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                                  for pattern in keywordPatterns]

        self.multiLineCommentFormat = QTextCharFormat()
        self.multiLineCommentFormat.setForeground(Qt.red)

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")