Beispiel #1
0
    def highlightItem(self, id):
        '''Inform the view that it must highlight an Item.

        Argument(s):
        id (str): ID of the node we want to highlight
        '''
        cursor = self.textCursor()
        fmt = self.textCursor().charFormat()

        # Set BackgroundColor of all text in white
        cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        fmt.setBackground(QBrush(QColor(0, 0, 0, 0)))
        cursor.mergeCharFormat(fmt)

        # Highlight item
        infoPos = self.findPosItem(id)
        cursor.setPosition(infoPos[0], QTextCursor.MoveAnchor)
        cursor.setPosition(infoPos[1], QTextCursor.KeepAnchor)
        # If subgraph in statement
        if re.match("\s*(subgraph)*\s*.*\{", cursor.selectedText()):
            indItem = cursor.selectedText().find(id)
            cursor.setPosition(infoPos[0] + indItem, QTextCursor.MoveAnchor)
            cursor.setPosition(infoPos[1], QTextCursor.KeepAnchor)
        format = QTextCharFormat()
        format.setBackground(QBrush(QColor(190, 180, 0, 80)))
        cursor.mergeCharFormat(format)
        self.setCurrentCharFormat(fmt)
Beispiel #2
0
class XmlSyntaxHighlighter(QSyntaxHighlighter):

    def __init__(self, parent=None):
        super(XmlSyntaxHighlighter, self).__init__(parent)

        self.highlightingRules = []

        # Tag format.
        format = QTextCharFormat()
        format.setForeground(Qt.darkBlue)
        format.setFontWeight(QFont.Bold)
        pattern = QRegExp("(<[a-zA-Z:]+\\b|<\\?[a-zA-Z:]+\\b|\\?>|>|/>|</[a-zA-Z:]+>)")
        self.highlightingRules.append((pattern, format))

        # Attribute format.
        format = QTextCharFormat()
        format.setForeground(Qt.darkGreen)
        pattern = QRegExp("[a-zA-Z:]+=")
        self.highlightingRules.append((pattern, format))

        # Attribute content format.
        format = QTextCharFormat()
        format.setForeground(Qt.red)
        pattern = QRegExp("(\"[^\"]*\"|'[^']*')")
        self.highlightingRules.append((pattern, format))

        # Comment format.
        self.commentFormat = QTextCharFormat()
        self.commentFormat.setForeground(Qt.lightGray)
        self.commentFormat.setFontItalic(True)

        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 = text.length() - startIndex
            else:
                commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()

            self.setFormat(startIndex, commentLength, self.commentFormat)
            startIndex = self.commentStartExpression.indexIn(text,
                    startIndex + commentLength)
Beispiel #3
0
class FormatChoice( ChoiceWidget ) :
    # combobox value
    def __init__( self, title, explainer ) :
        super().__init__( title, explainer )
        #Current color and line style are kept in this QTextCharFormat
        self.text_format = QTextCharFormat()
        # Set up the underline menu
        self.ul_menu = QComboBox()
        self.ul_menu.addItems( list( UNDERLINES.values() ) )
        self.ul_menu.currentIndexChanged[int].connect(self.ul_change)
        self.layout().addWidget( self.ul_menu, 0 )
        # Set up the color swatch
        self.swatch = Swatch( self )
        self.layout().addWidget( self.swatch, 0 )
        self.swatch.clicked.connect( self.color_change )
        # Set up the text sample
        self.sample = Sample()
        self.layout().addWidget( self.sample )
        self.reset() # set widgets to current value

    # Combine the underline choice and swatch color into a QTextCharFormat.
    def make_format( self, ul_index, qc ) :
        qtcf = QTextCharFormat()
        qtcf.setUnderlineStyle( ul_index )
        if ul_index == QTextCharFormat.NoUnderline :
            qtcf.setBackground(QBrush(qc))
        else :
            qtcf.setUnderlineColor(qc) # underline color gets a QColor
            qtcf.clearBackground()
        return qtcf

    # Parse self.text_format and display it in the swatch and combobox.
    def show_format( self ) :
        un = self.text_format.underlineStyle()
        if un == QTextCharFormat.NoUnderline :
            qc = self.text_format.background().color()
        else :
            qc = self.text_format.underlineColor()
        self.swatch.set_color( qc )
        self.ul_menu.setCurrentIndex( un )
        self.sample.change_format(self.text_format)

    # Handle a change in selection of the underline popup
    def ul_change( self, index ) :
        self.text_format = self.make_format( index, self.swatch.qc )
        self.show_format()

    # Handle a click on the color swatch. Show the color dialog. After it
    # ends, the Preferences dialog will be behind the main window. Why? Who
    # knows! But raise it back up to visibility.
    def color_change(self) :
        qc = colors.choose_color(
            _TR('Browse dialog for color preference',
                'Choose a color for scanno marking'),
            self.swatch.qc )
        BIG_FAT_KLUDGE.raise_()
        if qc is not None :
            self.text_format = self.make_format( self.ul_menu.currentIndex(), qc )
            self.show_format()
    def _get_underline(self):
        _format = QTextCharFormat()
        if self.textCursor().charFormat().font().underline():
            _format.setFontUnderline(False)
        else:
            _format.setFontUnderline(True)

        return _format
    def _get_cursive(self):
        _format = QTextCharFormat()
        if self.textCursor().charFormat().font().italic():
            _format.setFontItalic(False)
        else:
            _format.setFontItalic(True)

        return _format
    def _get_bold(self):
        _format = QTextCharFormat()
        if self.textCursor().charFormat().font().bold():
            _format.setFontWeight(QFont.Normal)
        else:
            _format.setFontWeight(QFont.Bold)

        return _format
Beispiel #7
0
 def removeHighlighting(self):
     """ Remove all the highlightings from the page content.
     """
     cursor = self.pageContent.textCursor()
     textFormat = QTextCharFormat()
     cursor.select(QTextCursor.Document)
     textFormat.setBackground(QBrush(QColor("transparent")))
     cursor.mergeCharFormat(textFormat)
Beispiel #8
0
 def __post_execution_message(self):
     """Print post execution message."""
     self.output.textCursor().insertText('\n\n')
     format_ = QTextCharFormat()
     format_.setAnchor(True)
     format_.setForeground(Qt.green)
     self.output.textCursor().insertText(
         _translate("RunWidget", "Post Execution Script Successfully executed."), format_)
Beispiel #9
0
def highlight(begin, end, color, qtextedit):
    form = QTextCharFormat()
    form.setBackground(Qt.red)

    cursor = QTextCursor(qtextedit.document())
    cursor.setPosition(begin, QTextCursor.MoveAnchor)
    cursor.setPosition(end, QTextCursor.KeepAnchor)
    cursor.setCharFormat(form)
Beispiel #10
0
 def setBold(self):
     format = QTextCharFormat()
     if self.boldAct.isChecked():
         weight = QFont.Bold
     else:
         weight = QFont.Normal
     format.setFontWeight(weight)
     self.setFormat(format)
Beispiel #11
0
    def textColor(self):
        col = QColorDialog.getColor(self.textEdit.textColor(), self)
        if not col.isValid():
            return

        fmt = QTextCharFormat()
        fmt.setForeground(col)
        self.mergeFormatOnWordOrSelection(fmt)
        self.colorChanged(col)
Beispiel #12
0
    def weekendFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
                Qt.GlobalColor(
                        self.weekendColorCombo.itemData(
                                self.weekendColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Saturday, format)
        self.calendar.setWeekdayTextFormat(Qt.Sunday, format)
Beispiel #13
0
 def addTestResult(self, results):
     textCharFormat = QTextCharFormat()
     if results[0]:
         textCharFormat.setFontWeight(QFont.Bold)
     elif results[1] == False:
         textCharFormat.setForeground(Qt.yellow)
     self.plainTextEdit_methodResults.textCursor().insertText(results[2] + "\n", textCharFormat)
     self.plainTextEdit_methodResults.verticalScrollBar().setValue(
         self.plainTextEdit_methodResults.verticalScrollBar().maximum())
Beispiel #14
0
class Matcher(gadgets.matcher.Matcher):
    def __init__(self, edit):
        super(Matcher, self).__init__(edit)
        self.readSettings()
        app.settingsChanged.connect(self.readSettings)

    def readSettings(self):
        self.format = QTextCharFormat()
        self.format.setBackground(textformats.formatData('editor').baseColors['match'])
Beispiel #15
0
 def fixFormat(self):
     try:
         cursor_clear = self.__textEditor.textCursor()
         format_clear = QTextCharFormat()
         format_clear.setBackground(QBrush(QColor(30, 30, 30)))
         cursor_clear.setPosition(0)
         cursor_clear.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
         cursor_clear.mergeCharFormat(format_clear)
     except Exception as e:
         print("something  didn't work with fixFormat: ", e)
Beispiel #16
0
    def __init__(self):
        super(PugdebugFormatter, self).__init__()

        for token, style in self.style:
            format = QTextCharFormat()

            if style["color"]:
                color = QColor("#" + style["color"])
                format.setForeground(color)

            self.styles[str(token)] = format
Beispiel #17
0
    def textFormat(self, name):
        """(Internal) Returns a QTextCharFormat setup according to the preferences.

        For bookmarks and the current line, FullWidthSelection is automatically enabled.

        """
        f = QTextCharFormat()
        f.setBackground(self._baseColors[name])
        if name in ('current', 'mark', 'error'):
            f.setProperty(QTextFormat.FullWidthSelection, True)
        return f
Beispiel #18
0
    def weekdayFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
                Qt.GlobalColor(
                        self.weekdayColorCombo.itemData(
                                self.weekdayColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Monday, format)
        self.calendar.setWeekdayTextFormat(Qt.Tuesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Wednesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Thursday, format)
        self.calendar.setWeekdayTextFormat(Qt.Friday, format)
Beispiel #19
0
 def make_format( self, ul_index, qc ) :
     qtcf = QTextCharFormat()
     qtcf.setUnderlineStyle( ul_index )
     if ul_index == QTextCharFormat.NoUnderline :
         qtcf.setBackground(QBrush(qc))
     else :
         qtcf.setUnderlineColor(qc) # underline color gets a QColor
         qtcf.clearBackground()
     return qtcf
    def __init__(self, items, parent):
        super().__init__(parent)

        self.rules = []
        self.items = items

        brush = QBrush(QColor(69, 160, 163), Qt.SolidPattern)
        self.item_keywords = QTextCharFormat()
        self.item_keywords.setForeground(brush)
        self.item_keywords.setFontWeight(QFont.Bold)

        self.keywords = QTextCharFormat()
        self.keywords.setForeground(brush)
Beispiel #21
0
class _Highlighter(QSyntaxHighlighter):

    def __init__(self, doc, pattern, color):
        super().__init__(doc)
        self._format = QTextCharFormat()
        self._format.setForeground(color)
        self._pattern = pattern

    def highlightBlock(self, text):
        """Override highlightBlock for custom highlighting."""
        for match in re.finditer(self._pattern, text, re.IGNORECASE):
            start, end = match.span()
            length = end - start
            self.setFormat(start, length, self._format)
Beispiel #22
0
 def process_error(self, error):
     """Listen to the error signals from the running process."""
     self.lblInput.hide()
     self.input.hide()
     self._proc.kill()
     format_ = QTextCharFormat()
     format_.setAnchor(True)
     format_.setForeground(QBrush(QColor(resources.CUSTOM_SCHEME.get(
         "error-underline", resources.COLOR_SCHEME["error-underline"]))))
     if error == 0:
         self.output.textCursor().insertText(_translate("RunWidget", 'Failed to start'),
             format_)
     else:
         self.output.textCursor().insertText(
             (_translate("RunWidget", 'Error during execution, QProcess error: %d') % error),
             format_)
Beispiel #23
0
 def __init__(self, parent):
     QSyntaxHighlighter.__init__(self, parent)
     self.parent = parent
     self.format = QTextCharFormat()
     self.format.setForeground(QBrush(styles.INVALID_DNA_COLOR))
     if styles.UNDERLINE_INVALID_DNA:
         self.format.setFontUnderline(True)
         self.format.setUnderlineColor(styles.INVALID_DNA_COLOR)
Beispiel #24
0
 def updateDisplay(self):
     data = self.data[self.scheme.currentScheme()]
     
     with qutil.signalsBlocked(self.fontChooser, self.fontSize):
         self.fontChooser.setCurrentFont(data.font)
         self.fontSize.setValue(data.font.pointSizeF())
     
     with qutil.signalsBlocked(self):
         # update base colors
         for name in textformats.baseColors:
             self.baseColorsWidget.color[name].setColor(data.baseColors[name])
     
     # update base colors for whole treewidget
     p = QApplication.palette()
     p.setColor(QPalette.Base, data.baseColors['background'])
     p.setColor(QPalette.Text, data.baseColors['text'])
     p.setColor(QPalette.Highlight, data.baseColors['selectionbackground'])
     p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext'])
     self.tree.setPalette(p)
     
     def setItemTextFormat(item, f):
         font = QFont(data.font)
         if f.hasProperty(QTextFormat.ForegroundBrush):
             item.setForeground(0, f.foreground().color())
         else:
             item.setForeground(0, data.baseColors['text'])
         if f.hasProperty(QTextFormat.BackgroundBrush):
             item.setBackground(0, f.background().color())
         else:
             item.setBackground(0, QBrush())
         font.setWeight(f.fontWeight())
         font.setItalic(f.fontItalic())
         font.setUnderline(f.fontUnderline())
         item.setFont(0, font)
         
     # update looks of default styles
     for name in textformats.defaultStyles:
         setItemTextFormat(self.defaultStyles[name], data.defaultStyles[name])
     
     # update looks of all the specific styles
     for group, styles in ly.colorize.default_mapping():
         children = self.allStyles[group][1]
         for name, inherit, clss in styles:
             f = QTextCharFormat(data.defaultStyles[inherit]) if inherit else QTextCharFormat()
             f.merge(data.allStyles[group][name])
             setItemTextFormat(children[name], f)
Beispiel #25
0
    def insertImage(self, image):
        cursor = self.textCursor()

        page = self.parent().page
        fileName = page.saveImage(image)        # returns the file name inside the page's directory
        
        imageObject = ImageObject()
        imagePath = os.path.join(page.getPageDir(), fileName)
        imageObject.setName(imagePath)

        imageObjectFormat = QTextCharFormat()
        imageObjectFormat.setObjectType(QTextFormat.UserObject + 1)
        imageObjectFormat.setProperty(QTextFormat.UserProperty + 1, imageObject)
        cursor.insertText('\ufffc', imageObjectFormat);

        # Make sure that the image is also part of the page
        page.save()
Beispiel #26
0
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes."""
    _color = QColor()
    _color.setNamedColor(color)

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

    return _format
Beispiel #27
0
def html_copy(cursor, scheme='editor', number_lines=False):
    """Return a new QTextDocument with highlighting set as HTML textcharformats.

    The cursor is a cursor of a document.Document instance. If the cursor
    has a selection, only the selection is put in the new document.

    If number_lines is True, line numbers are added.

    """
    data = textformats.formatData(scheme)
    doc = QTextDocument()
    doc.setDefaultFont(data.font)
    doc.setPlainText(cursor.document().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document())))
    if cursor.hasSelection():
        # cut out not selected text
        start, end = cursor.selectionStart(), cursor.selectionEnd()
        cur1 = QTextCursor(doc)
        cur1.setPosition(start, QTextCursor.KeepAnchor)
        cur2 = QTextCursor(doc)
        cur2.setPosition(end)
        cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        cur2.removeSelectedText()
        cur1.removeSelectedText()
    if number_lines:
        c = QTextCursor(doc)
        f = QTextCharFormat()
        f.setBackground(QColor('#eeeeee'))
        if cursor.hasSelection():
            num = cursor.document().findBlock(cursor.selectionStart()).blockNumber() + 1
            last = cursor.document().findBlock(cursor.selectionEnd())
        else:
            num = 1
            last = cursor.document().lastBlock()
        lastnum = last.blockNumber() + 1
        padding = len(format(lastnum))
        block = doc.firstBlock()
        while block.isValid():
            c.setPosition(block.position())
            c.setCharFormat(f)
            c.insertText('{0:>{1}d} '.format(num, padding))
            block = block.next()
            num += 1
    return doc
Beispiel #28
0
 def __init__(self, parent):
     super(View, self).__init__(parent)
     self._highlightFormat = QTextCharFormat()
     self.jslink = JSLink(self)
     self.loadFinished.connect(self.svgLoaded)
     self.mainwindow().aboutToClose.connect(self.cleanupForClose)
     app.settingsChanged.connect(self.readSettings)
     self.readSettings()
     self.load(self.defaulturl)
    def __init__(self, parent=None):
        super(FeatureCodeHighlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(QColor(45, 95, 235))
        self.addRule("\\b(?<!\\\\)(%s)\\b" % ("|".join(keywordPatterns)),
                     keywordFormat)

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(QColor(112, 128, 144))
        self.addRule("#[^\n]*", singleLineCommentFormat)

        groupFormat = QTextCharFormat()
        groupFormat.setForeground(QColor(255, 27, 147))
        self.addRule("@[A-Za-z0-9_.]+", groupFormat)
Beispiel #30
0
    def gray_out_old_text(self):
        """Puts the old text in gray"""

        cursor = self.textCursor()
        end_format = cursor.charFormat()
        cursor.select(QTextCursor.Document)
        format_ = QTextCharFormat()
        backcolor = self.palette().base().color()
        forecolor = self.palette().text().color()
        backfactor = .5
        forefactor = 1 - backfactor
        red = backfactor * backcolor.red() + forefactor * forecolor.red()
        green = backfactor * backcolor.green() + forefactor * forecolor.green()
        blue = backfactor * backcolor.blue() + forefactor * forecolor.blue()
        format_.setForeground(QColor(red, green, blue))
        cursor.mergeCharFormat(format_)
        cursor.movePosition(QTextCursor.End)
        cursor.setCharFormat(end_format)
        cursor.insertBlock(QTextBlockFormat())
Beispiel #31
0
    def highlightMatch(self, searchText='', regExpObj=None, cellNum=0,
                       skipMatches=0):
        """Highlight a specific search result.

        Arguments:
            searchText -- the text to find in a non-regexp search
            regExpObj -- the regular expression to find if searchText is blank
            cellNum -- the vertical position (field number) of the cell
            skipMatches -- number of previous matches to skip in this field
        """
        backColor = self.palette().brush(QPalette.Active,
                                         QPalette.Highlight)
        foreColor = self.palette().brush(QPalette.Active,
                                         QPalette.HighlightedText)
        charFormat = QTextCharFormat()
        charFormat.setBackground(backColor)
        charFormat.setForeground(foreColor)
        cellNum += 1    # skip title line
        cell = self.item(cellNum, 1)
        highlighter = MatchHighlighter(cell.doc, charFormat, searchText,
                                       regExpObj, skipMatches)
class SyntaxHighlighter(QSyntaxHighlighter):
    def __init__(self, items, parent):
        super().__init__(parent)

        self.rules = []
        self.items = items

        brush = QBrush(QColor(69, 160, 163), Qt.SolidPattern)
        self.item_keywords = QTextCharFormat()
        self.item_keywords.setForeground(brush)
        self.item_keywords.setFontWeight(QFont.Bold)

        self.keywords = QTextCharFormat()
        self.keywords.setForeground(brush)

    def set_rules(self, item):
        self.rules = []
        for each in self.items:
            if each.id == item.id:
                format_ = self.item_keywords
            else:
                format_ = self.keywords

            for w in map(_, each.keys()):
                pattern = QRegExp(r"\{%s.%s\}" % (_(each.name), w))
                self.rules.append({'pattern': pattern, 'format': format_})

        self.rehighlight()

    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 insertTextObject(self):
        fileName = self.fileNameLineEdit.text()
        file = QFile(fileName)

        if not file.open(QIODevice.ReadOnly):
            QMessageBox.warning(self, "Error Opening File",
                                "Could not open '%s'" % fileName)

        svgData = file.readAll()

        svgCharFormat = QTextCharFormat()
        svgCharFormat.setObjectType(Window.SvgTextFormat)
        svgCharFormat.setProperty(Window.SvgData, svgData)

        try:
            # Python v2.
            orc = unichr(0xfffc)
        except NameError:
            # Python v3.
            orc = chr(0xfffc)

        cursor = self.textEdit.textCursor()
        cursor.insertText(orc, svgCharFormat)
        self.textEdit.setTextCursor(cursor)
Beispiel #34
0
    def process_error(self, error):
        """Listen to the error signals from the running process"""

        self.lblInput.hide()
        self.input.hide()
        self._proc.kill()
        format_ = QTextCharFormat()
        format_.setAnchor(True)
        font = settings.FONT
        # format_.setFont(font)
        format_.setForeground(
            QBrush(
                QColor(
                    resources.CUSTOM_SCHEME.get(
                        "ErrorUnderline",
                        resources.COLOR_SCHEME["ErrorUnderline"]))))
        if error == 0:
            # self.output.textCursor().insertText(self.tr('Failed to start'),
            #
            # pass                                 format_)

            print('ERROR')
        else:
            print('ERRoR2')
Beispiel #35
0
    def spellCheck(self, text, Rule1, Rule2):
        """
        Method defines to underline text if word not in Rules

        Args:
             text (str):  current text block to search
             Rule1 (list): GROMHighlighter.Red_Rules contains all words
             Rule2 (list ) GROMHighlighter.Algorithm_Rules only Algorithm rules
        """

        #: Underline words color yellow
        format_under = QTextCharFormat()
        format_under.setUnderlineColor(Qt.yellow)
        format_under.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

        #: Underlines word if not in Rules
        for word_object in re.finditer(self.WORDS, text, re.IGNORECASE):
            comment_location = text.find(';')
            word = word_object.group()
            if (word not in Rule1 or word in Rule2
                    or text[:comment_location].count(str(word)) > 1):
                self.setFormat(word_object.start(),
                               word_object.end() - word_object.start(),
                               format_under)
Beispiel #36
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

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

        keywordPatterns = [
            """</?\w+\s+[^>]*>""",
            "<[/]?(html|body|head|title|div|a|br|form|input|b|p|i|center|span|font|table|tr|td|h[1-6])[/]?>"
        ]

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

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

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat))

        moreKeyWords = QTextCharFormat()
        moreKeyWords.setForeground(Qt.darkMagenta)
        moreKeyWords.setFontWeight(QFont.Bold)
        self.highlightingRules.append((QRegExp(
            "(id|class|src|border|width|height|style|name|type|value)="),
                                       moreKeyWords))

        self.commentStartExpression = QRegExp("<!--")
        self.commentEndExpression = QRegExp("-->")
Beispiel #37
0
	def highlightBlock(self, text):
		# Syntax highlighter
		if self.docType in self.patternsDict:
			for number in self.patternsDict[self.docType]:
				pattern = self.patterns[number]
				for match in pattern[0].finditer(text):
					for i, formatter in enumerate(pattern[1:]):
						charFormat = QTextCharFormat()
						formatter.format(charFormat)
						self.setFormat(QString_length(text[:match.start(i)]),
						               QString_length(match.group(i)),
						               charFormat)
		for match in reSpacesOnEnd.finditer(text):
			charFormat = QTextCharFormat()
			charFormat.setBackground(colorScheme['whitespaceOnEnd'])
			self.setFormat(QString_length(text[:match.start()]),
			               QString_length(match.group(0)),
			               charFormat)
		# Spell checker
		if self.dictionary:
			charFormat = QTextCharFormat()
			charFormat.setUnderlineColor(Qt.red)
			charFormat.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
			for match in reWords.finditer(text):
				finalFormat = QTextCharFormat()
				finalFormat.merge(charFormat)
				finalFormat.merge(self.format(match.start()))
				if not self.dictionary.check(match.group(0)):
					self.setFormat(QString_length(text[:match.start()]),
					               QString_length(match.group(0)),
					               finalFormat)
Beispiel #38
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.setupUi(self)
     self._translation_char_format = QTextCharFormat()
     self._strokes_char_format = QTextCharFormat()
     self._strokes_char_format.font().setStyleHint(QFont.Monospace)
Beispiel #39
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 = [
            """</?\w+\s+[^>]*>""",
            "<[/]?(html|body|head|title|div|a|br|form|input|b|p|i|center|span|font|table|tr|td|h[1-6])[/]?>"
        ]

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

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

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat))

        moreKeyWords = QTextCharFormat()
        moreKeyWords.setForeground(Qt.darkMagenta)
        moreKeyWords.setFontWeight(QFont.Bold)
        self.highlightingRules.append((QRegExp(
            "(id|class|src|border|width|height|style|name|type|value)="),
                                       moreKeyWords))

        self.commentStartExpression = QRegExp("<!--")
        self.commentEndExpression = QRegExp("-->")

    def highlightBlock(self, text):
        for pattern, formats in self.highlightingRules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, formats)
                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)
 def __init__(self, doc, pattern, color):
     super().__init__(doc)
     self._format = QTextCharFormat()
     self._format.setForeground(color)
     self._pattern = pattern
Beispiel #41
0
    def __init__(self, parent=None):

        super(XMLHighlighter, self).__init__(parent)

        self.highlightingRules = []

        xmlElementFormat = QTextCharFormat()
        xmlElementFormat.setForeground(QColor("#3d9cf5"))  # dark magenta
        # self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=[\s/>])"), xmlElementFormat))
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=[\/>])"), xmlElementFormat))
        xmlAttributeFormat = QTextCharFormat()
        xmlAttributeFormat.setFontItalic(True)
        xmlAttributeFormat.setForeground(QColor("#11e4f7"))  # magenta
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\=)"), xmlAttributeFormat))
        self.highlightingRules.append((QRegExp("="), xmlAttributeFormat))

        self.valueFormat = QTextCharFormat()
        self.valueFormat.setForeground(QColor("#e35e00"))  # orange
        self.valueStartExpression = QRegExp("\"")
        self.valueEndExpression = QRegExp("\"(?=[\s></])")
        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(QColor("#228030"))  # green
        self.highlightingRules.append((QRegExp("<!--[^\n]*-->"), singleLineCommentFormat))

        textFormat = QTextCharFormat()
        textFormat.setForeground(QColor("#ebf7e9"))  # light green
        # (?<=...)  - lookbehind is not supported
        self.highlightingRules.append((QRegExp(">(.+)(?=</)"), textFormat))

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(QColor("#686968"))  # grey
        keywordFormat.setFontWeight(QFont.Bold)
        keywordPatterns = ["<\\?", "\\b?xml\\b", "/>", ">", "<", "</", "\\b?\\>"]
        self.highlightingRules += [(QRegExp(pattern), keywordFormat)
                                   for pattern in keywordPatterns]
Beispiel #42
0
 def setItalic(self):
     format = QTextCharFormat()
     #format.setFontItalic(self.__italic.isChecked())
     format.setFontItalic(self.italicAct.isChecked())
     self.setFormat(format)
Beispiel #43
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 = [
            "\\bchar\\b", "\\bclass\\b", "\\bconst\\b", "\\bdouble\\b",
            "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b", "\\binline\\b",
            "\\bint\\b", "\\blong\\b", "\\bnamespace\\b", "\\boperator\\b",
            "\\bprivate\\b", "\\bprotected\\b", "\\bpublic\\b", "\\bshort\\b",
            "\\bsignals\\b", "\\bsigned\\b", "\\bslots\\b", "\\bstatic\\b",
            "\\bstruct\\b", "\\btemplate\\b", "\\btypedef\\b",
            "\\btypename\\b", "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b",
            "\\bvoid\\b", "\\bvolatile\\b"
        ]

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

        classFormat = QTextCharFormat()
        classFormat.setFontWeight(QFont.Bold)
        classFormat.setForeground(Qt.darkMagenta)
        self.highlightingRules.append(
            (QRegExp("\\bQ[A-Za-z]+\\b"), classFormat))

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(Qt.red)
        self.highlightingRules.append(
            (QRegExp("//[^\n]*"), singleLineCommentFormat))

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

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat))

        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)
Beispiel #44
0
 def initializeFormats():
     baseFormat = QTextCharFormat()
     baseFormat.setFontFamily("consolas")
     baseFormat.setFontPointSize(12)
     for name, color in (("normal", Qt.black),
             ("keyword", Qt.blue), ("builtin", Qt.darkRed),
             ("constant", Qt.darkGreen),
             ("decorator", Qt.darkBlue), ("comment", Qt.green),
             ("string", Qt.darkGreen), ("number", Qt.darkMagenta),
             ("error", Qt.darkRed), ("pyqt", Qt.darkCyan)):
         format = QTextCharFormat(baseFormat)
         format.setForeground(QColor(color))
         if name in ("keyword", "decorator"):
             format.setFontWeight(QFont.Bold)
         if name == "comment":
             format.setFontItalic(True)
         PythonHighlighter.Formats[name] = format
Beispiel #45
0
class BasicHighlighter(QSyntaxHighlighter):
    def __init__(self, editor):
        QSyntaxHighlighter.__init__(self, editor.document())

        self.editor = editor
        self._defaultBlockFormat = QTextBlockFormat()
        self._defaultCharFormat = QTextCharFormat()
        self.defaultTextColor = QColor(S.text)
        self.backgroundColor = QColor(S.base)
        self.markupColor = QColor(S.textLight)
        self.linkColor = QColor(S.link)
        self.spellingErrorColor = QColor(Qt.red)

        # Matches during checking can be separated by their type (all of them listed here):
        # https://languagetool.org/development/api/org/languagetool/rules/ITSIssueType.html
        #
        # These are the colors for actual spell-, grammar- and style-checking:
        self._errorColors = {
            'addition' : QColor(255, 215, 0),               # gold
            'characters' : QColor(135, 206, 235),           # sky blue
            'duplication' : QColor(0, 255, 255),            # cyan / aqua
            'formatting' : QColor(0, 128, 128),             # teal
            'grammar' : QColor(0, 0, 255),                  # blue
            'inconsistency' : QColor(128, 128, 0),          # olive
            'inconsistententities' : QColor(46, 139, 87),   # sea green
            'internationalization' : QColor(255, 165, 0),   # orange
            'legal' : QColor(255, 69, 0),                   # orange red
            'length' : QColor(47, 79, 79),                  # dark slate gray
            'localespecificcontent' : QColor(188, 143, 143),# rosy brown
            'localeviolation' : QColor(128, 0, 0),          # maroon
            'markup' : QColor(128, 0, 128),                 # purple
            'misspelling' : QColor(255, 0, 0),              # red
            'mistranslation' : QColor(255, 0, 255),         # magenta / fuchsia
            'nonconformance' : QColor(255, 218, 185),       # peach puff
            'numbers' : QColor(65, 105, 225),               # royal blue
            'omission' : QColor(255, 20, 147),              # deep pink
            'other' : QColor(138, 43, 226),                 # blue violet
            'patternproblem' : QColor(0, 128, 0),           # green
            'register' : QColor(112,128,144),               # slate gray
            'style' : QColor(0, 255, 0),                    # lime
            'terminology' : QColor(0, 0, 128),              # navy
            'typographical' : QColor(255, 255, 0),          # yellow
            'uncategorized' : QColor(128, 128, 128),        # gray
            'untranslated' : QColor(210, 105, 30),          # chocolate
            'whitespace' : QColor(192, 192, 192)            # silver
        }

    def setDefaultBlockFormat(self, bf):
        self._defaultBlockFormat = bf
        self.rehighlight()

    def setDefaultCharFormat(self, cf):
        self._defaultCharFormat = cf
        self.rehighlight()

    def setMisspelledColor(self, color):
        self._errorColors['misspelled'] = color

    def updateColorScheme(self, rehighlight=True):
        """
        Generates a base set of colors that will take account of user
        preferences, and use system style.
        """

        # Reading user settings
        opt = settings.textEditor

        if not self.editor._fromTheme or not self.editor._themeData:

            self.defaultTextColor = QColor(opt["fontColor"])
            self.backgroundColor = (QColor(opt["background"])
                                    if not opt["backgroundTransparent"]
                                    else QColor(S.window))
            self.markupColor = F.mixColors(self.defaultTextColor,
                                           self.backgroundColor,
                                           .3)
            self.linkColor = QColor(S.link)
            self.spellingErrorColor = QColor(opt["misspelled"])
            self._defaultCharFormat.setForeground(QBrush(self.defaultTextColor))

        # FullscreenEditor probably
        else:
            opt = self.editor._themeData
            self.defaultTextColor = QColor(opt["Text/Color"])
            self.backgroundColor =  F.mixColors(
                QColor(opt["Foreground/Color"]),
                QColor(opt["Background/Color"]),
                int(opt["Foreground/Opacity"])/100.)
            self.markupColor = F.mixColors(self.defaultTextColor,
                                           self.backgroundColor,
                                           .3)
            self.linkColor = QColor(S.link)
            self.spellingErrorColor = QColor(opt["Text/Misspelled"])

        if rehighlight:
            self.rehighlight()

    def highlightBlock(self, text):
        """Apply syntax highlighting to the given block of text.
        """
        self.highlightBlockBefore(text)
        self.doHighlightBlock(text)
        self.highlightBlockAfter(text)

    def doHighlightBlock(self, text):
        """
        Virtual function to subclass.
        """
        pass

    def highlightBlockBefore(self, text):
        """Highlighting to do before anything else.

        When subclassing BasicHighlighter, you must call highlightBlockBefore
        before you do any custom highlighting. Or implement doHighlightBlock.
        """

        #LOGGER.debug("undoSteps before: %s", self.currentBlock().document().availableUndoSteps())
        c = QTextCursor(self.currentBlock())
        #c.joinPreviousEditBlock()
        bf = QTextBlockFormat(self._defaultBlockFormat)
        if bf != c.blockFormat():
            c.setBlockFormat(bf)
        #c.endEditBlock()
        #LOGGER.debug("undoSteps after: %s", self.currentBlock().document().availableUndoSteps())

        # self.setFormat(0, len(text), self._defaultCharFormat)

    def highlightBlockAfter(self, text):
        """Highlighting to do after everything else.

        When subclassing BasicHighlighter, you must call highlightBlockAfter
        after your custom highlighting. Or implement doHighlightBlock.
        """

        # References
        for txt in re.finditer(Ref.RegEx, text):
            fmt = self.format(txt.start())
            fmt.setFontFixedPitch(True)
            fmt.setFontWeight(QFont.DemiBold)

            if txt.group(1) == Ref.TextLetter:
                fmt.setBackground(QBrush(Ref.TextHighlightColor))
            elif txt.group(1) == Ref.CharacterLetter:
                fmt.setBackground(QBrush(Ref.CharacterHighlightColor))
            elif txt.group(1) == Ref.PlotLetter:
                fmt.setBackground(QBrush(Ref.PlotHighlightColor))
            elif txt.group(1) == Ref.WorldLetter:
                fmt.setBackground(QBrush(Ref.WorldHighlightColor))

            self.setFormat(txt.start(),
                           txt.end() - txt.start(),
                           fmt)

        if hasattr(self.editor, "spellcheck") and self.editor.spellcheck and self.editor._dict:
            # Spell checking

            # Following algorithm would not check words at the end of line.
            # This hacks adds a space to every line where the text cursor is not
            # So that it doesn't spellcheck while typing, but still spellchecks at
            # end of lines. See github's issue #166.
            textedText = text
            if self.currentBlock().position() + len(text) != \
               self.editor.textCursor().position():
                textedText = text + " "

            # The text should only be checked once as a whole
            for match in self.editor._dict.checkText(textedText):
                if match.locqualityissuetype in self._errorColors:
                    highlight_color = self._errorColors[match.locqualityissuetype]

                    format = self.format(match.start)
                    format.setUnderlineColor(highlight_color)
                    # SpellCheckUnderline fails with some fonts
                    format.setUnderlineStyle(QTextCharFormat.WaveUnderline)
                    self.setFormat(match.start, match.end - match.start, format)
    def update_io(self):
        inputs_header_text = _("Inputs") + ' (%d)' % len(self.tx.inputs())
        if not self.finalized:
            selected_coins = self.main_window.get_manually_selected_coins()
            if selected_coins is not None:
                inputs_header_text += f"  -  " + _(
                    "Coin selection active ({} UTXOs selected)").format(
                        len(selected_coins))
        self.inputs_header.setText(inputs_header_text)
        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(ColorScheme.GREEN.as_color(background=True)))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(ColorScheme.YELLOW.as_color(background=True)))
        chg.setToolTip(_("Wallet change address"))
        twofactor = QTextCharFormat()
        twofactor.setBackground(
            QBrush(ColorScheme.BLUE.as_color(background=True)))
        twofactor.setToolTip(
            _("TrustedCoin (2FA) fee for the next batch of transactions"))

        def text_format(addr):
            if self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            elif self.wallet.is_billing_address(addr):
                return twofactor
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text = self.inputs_textedit
        i_text.clear()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        cursor = i_text.textCursor()
        for txin in self.tx.inputs():
            if txin.is_coinbase_input():
                cursor.insertText('coinbase')
            else:
                prevout_hash = txin.prevout.txid.hex()
                prevout_n = txin.prevout.out_idx
                cursor.insertText(prevout_hash + ":%-4d " % prevout_n, ext)
                addr = self.wallet.get_txin_address(txin)
                if addr is None:
                    addr = ''
                cursor.insertText(addr, text_format(addr))
                if isinstance(
                        txin,
                        PartialTxInput) and txin.value_sats() is not None:
                    cursor.insertText(format_amount(txin.value_sats()), ext)
            cursor.insertBlock()

        self.outputs_header.setText(
            _("Outputs") + ' (%d)' % len(self.tx.outputs()))
        o_text = self.outputs_textedit
        o_text.clear()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        cursor = o_text.textCursor()
        for o in self.tx.outputs():
            addr, v = o.get_ui_address_str(), o.value
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                cursor.insertText('\t', ext)
                cursor.insertText(format_amount(v), ext)
            cursor.insertBlock()
Beispiel #47
0
    def __init__(self, parent=None):
        super(GROMHighlighter, self).__init__(parent)

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

        #: adds all dictionary content to Rules
        for section in Total:
            keys = list(section.keys())
            for i in keys:
                list_is = section[i]
                GROMHighlighter.Red_Rules.append(i[2:-2])
                if len(list_is) > 0:
                    for element in list_is:
                        text = r"\b%s\b" % (element[2:-2])
                        GROMHighlighter.Red_Rules.append(text)
                        GROMHighlighter.Algorithm_Rules.append(text)
                        GROMHighlighter.Rules.append(
                            (QRegularExpression(
                                text,
                                QRegularExpression.CaseInsensitiveOption),
                             keywordFormat))  # testing for underline yellow

        topolFormat = QTextCharFormat()
        topolFormat.setForeground(Qt.yellow)
        topolFormat.setFontWeight(QFont.Bold)
        for pattern_top in ((r"\[ defaults \]", r"\[ moleculetype \]",
                             r"\[ atoms \]", r"\[ atomtypes \]",
                             r"\[ bonds \]", r"\[ pairs \]", r"\[ angles \]",
                             r"\[ dihedrals \]", r"\[ system \]",
                             r"\[ molecules \]",
                             r"\[ position_restraints \]")):
            GROMHighlighter.Rules.append(
                (QRegularExpression(pattern_top), topolFormat))

        # --> Rule for 'N' to color red
        NoFormat = QTextCharFormat()
        NoFormat.setForeground(Qt.red)
        NoFormat.setFontWeight(QFont.Bold)
        pattern_No = r"\bN\b"
        GROMHighlighter.Rules.append(
            (QRegularExpression(pattern_No), NoFormat))

        # --> Rule for 'Y' to color green
        YesFormat = QTextCharFormat()
        YesFormat.setForeground(Qt.green)
        YesFormat.setFontWeight(QFont.Bold)
        pattern_Yes = r"\bY\b"
        GROMHighlighter.Rules.append(
            (QRegularExpression(pattern_Yes), YesFormat))

        # --> Rules for number patterns  to color orange
        number = QTextCharFormat()
        number.setForeground(QColor(255, 165, 0))
        number.setFontWeight(QFont.Bold)
        patternNum1 = QRegularExpression(
            r'\s[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?')
        patternNum2 = QRegularExpression(
            r'\s[+-]?[0-9]+[lL]?\s",r"\s[+-]?[0-9]+[lL]?\n')
        patternNum3 = QRegularExpression(r"\s[+-]?0[xX][0-9A-Fa-f]+[lL]?\s")
        patternNum4 = QRegularExpression(
            r"\s[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\s")
        GROMHighlighter.Rules.append((patternNum1, number))
        GROMHighlighter.Rules.append((patternNum2, number))
        GROMHighlighter.Rules.append((patternNum3, number))
        GROMHighlighter.Rules.append((patternNum4, number))

        #: --> Rule to color #include to darkCyan
        keywordInclude = QTextCharFormat()
        keywordInclude.setForeground(Qt.darkCyan)
        keywordInclude.setFontWeight(QFont.Bold)
        patternkeyGroIncl = QRegularExpression(r"(#include).*$")
        GROMHighlighter.Rules.append((patternkeyGroIncl, keywordInclude))

        #: --> Rule to color #ifdef and #endif
        keywordIf = QTextCharFormat()  # Here My Modif
        keywordIf.setForeground(QColor(180, 202, 138, 220))
        keywordIf.setFontWeight(QFont.Bold)
        patternkeyGroIf = QRegularExpression(r"(#ifdef).*$" r"|(#endif).*$")
        GROMHighlighter.Rules.append((patternkeyGroIf, keywordIf))

        #: --> Rule to color POSRE
        POSREformat = QTextCharFormat()
        POSREformat.setForeground(QColor(255, 85, 0))
        POSREformat.setFontWeight(QFont.Bold)
        patternPOSRE = QRegularExpression(r"(-DPOSRE).*$")
        GROMHighlighter.Rules.append((patternPOSRE, POSREformat))

        #: --> Rule to color title to yellow
        titleFormat = QTextCharFormat()
        titleFormat.setForeground(QColor(3, 168, 250))
        titleFormat.setFontItalic(True)
        titleFormat.setFontWeight(QFont.Bold)
        GROMHighlighter.Rules.append(
            (QRegularExpression(r"title[^\n]*"), titleFormat))

        #: --> Rule for Gromacs comment to color green
        commentFormat = QTextCharFormat()
        commentFormat.setForeground(QColor(0, 127, 0))
        commentFormat.setFontItalic(True)
        commentFormat.setFontWeight(QFont.Bold)
        GROMHighlighter.Rules.append(
            (QRegularExpression(r";[^\n]*"), commentFormat))
Beispiel #48
0
def css2fmt(d, f=None):
    """Convert a css dictionary to a QTextCharFormat."""
    if f is None:
        f = QTextCharFormat()
    v = d.get('font-style')
    if v:
        f.setFontItalic(v in ('oblique', 'italic'))
    v = d.get('font-weight')
    if v:
        if v == 'bold':
            f.setFontWeight(QFont.Bold)
        elif v == 'normal':
            f.setFontWeight(QFont.Normal)
        elif v.isdigit():
            f.setFontWeight(int(v) / 10)
    v = d.get('color')
    if v:
        f.setForeground(QColor(v))
    v = d.get('background')
    if v:
        f.setBackground(QColor(v))
    v = d.get('text-decoration')
    if v:
        f.setFontUnderline(v == 'underline')
    v = d.get('text-decoration-color')
    if v:
        f.setUnderlineColor(QColor(v))
    return f
Beispiel #49
0
    def __init__(self, keywords, parent=None):
        super(JsHighlighter, self).__init__(parent)

        self.keyword_color = QColor('#C678DD')
        self.comment_color = QColor('#5C6370')
        self.function_color = QColor('#61AFEF')
        self.string_color = QColor('#98C379')
        self.number_color = QColor('#e06c75')
        self.constant_color = QColor('#D19A66')

        self._keywords = [
            "break", "case", "catch", "class", "const", "continue", "debugger",
            "default", "delete", "do", "else", "export", "extends", "false",
            "finally", "for", "function", "if", "import", "in", "instanceof",
            "new", "null", "return", "super", "switch", "this", "throw",
            "true", "try", "typeof", "var", "void", "while", "with", "yield"
        ]

        self._known_m = keywords

        self._known = [
            'log',
            'addWatcher',
            'deleteHook',
            'enumerateJavaClasses',
            'enumerateJavaMethods',
            'findExport',
            'getAddressTs',
            'hookAllJavaMethods',
            'hookJava',
            'hookNative',
            'hookNativeOnLoad',
            'javaBacktrace',
            'isAddressWatched',
            'nativeBacktrace',
            'release',
            'resume',
            'removeWatcher',
            'restart',
            'setData',
            'startNativeTracer',
            'stopNativeTracer',
            "prototype",
            "create",
            "defineProperty",
            "defineProperties",
            "getOwnPropertyDescriptor",
            "keys",
            "getOwnPropertyNames",
            "constructor",
            "__parent__",
            "__proto__",
            "__defineGetter__",
            "__defineSetter__",
            "eval",
            "hasOwnProperty",
            "isPrototypeOf",
            "__lookupGetter__",
            "__lookupSetter__",
            "__noSuchMethod__",
            "propertyIsEnumerable",
            "toSource",
            "toLocaleString",
            "toString",
            "unwatch",
            "valueOf",
            "watch",
            "arguments",
            "arity",
            "caller",
            "constructor",
            "length",
            "name",
            "apply",
            "bind",
            "call",
            "String",
            "fromCharCode",
            "length",
            "charAt",
            "charCodeAt",
            "concat",
            "indexOf",
            "lastIndexOf",
            "localCompare",
            "match",
            "quote",
            "replace",
            "search",
            "slice",
            "split",
            "substr",
            "substring",
            "toLocaleLowerCase",
            "toLocaleUpperCase",
            "toLowerCase",
            "toUpperCase",
            "trim",
            "trimLeft",
            "trimRight",
            "Array",
            "isArray",
            "index",
            "input",
            "pop",
            "push",
            "reverse",
            "shift",
            "sort",
            "splice",
            "unshift",
            "concat",
            "join",
            "filter",
            "forEach",
            "every",
            "map",
            "some",
            "reduce",
            "reduceRight",
            "RegExp",
            "global",
            "ignoreCase",
            "lastIndex",
            "multiline",
            "source",
            "exec",
            "test",
            "parse",
            "stringify",
            "decodeURI",
            "decodeURIComponent",
            "encodeURI",
            "encodeURIComponent",
            "eval",
            "isFinite",
            "isNaN",
            "parseFloat",
            "parseInt",
            "Infinity",
            "NaN",
            "undefined",
            "Math",
            "E",
            "LN2",
            "LN10",
            "LOG2E",
            "LOG10E",
            "PI",
            "SQRT1_2",
            "SQRT2",
            "abs",
            "acos",
            "asin",
            "atan",
            "atan2",
            "ceil",
            "cos",
            "exp",
            "floor",
            "log",
            "max",
            "min",
            "pow",
            "random",
            "round",
            "sin",
            "sqrt",
            "tan",
            "document",
            "window",
            "navigator",
            "userAgent",
        ]

        self.highlightingRules = []

        classFormat = QTextCharFormat()
        classFormat.setFontWeight(QFont.Bold)
        classFormat.setForeground(self.constant_color)
        self.highlightingRules.append(
            (QRegExp("\\bnew [A-Za-z]+\\b"), classFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setForeground(self.function_color)
        self.highlightingRules.append(
            (QRegExp("(?!function)\\b[A-Za-z0-9_]+(?=\\()"), functionFormat))
Beispiel #50
0
 def setUnderline(self):
     format = QTextCharFormat()
     format.setFontUnderline(self.__underline.isChecked())
     self.setFormat(format)
Beispiel #51
0
    def _makeFormat(self, fmtCol=None, fmtStyle=None, fmtSize=None):
        """Generate a valid character format to be applied to the text
        that is to be highlighted.
        """
        theFormat = QTextCharFormat()

        if fmtCol is not None:
            theFormat.setForeground(fmtCol)

        if fmtStyle is not None:
            if "bold" in fmtStyle:
                theFormat.setFontWeight(QFont.Bold)
            if "italic" in fmtStyle:
                theFormat.setFontItalic(True)
            if "strike" in fmtStyle:
                theFormat.setFontStrikeOut(True)
            if "underline" in fmtStyle:
                theFormat.setFontUnderline(True)
            if "background" in fmtStyle:
                theFormat.setBackground(QBrush(fmtCol, Qt.SolidPattern))

        if fmtSize is not None:
            theFormat.setFontPointSize(
                int(round(fmtSize * self.mainConf.textSize)))

        return theFormat
Beispiel #52
0
    def formatConverterFunction(format):
        if format == qutepart.syntax.TextFormat():
            return None  # Do not apply default format. Performance optimization

        qtFormat = QTextCharFormat()

        foregroundColor = QColor(format.color)
        backgroundColor = QColor(format.background)

        if foregroundColor != Qt.black:
            qtFormat.setForeground(foregroundColor)

        if backgroundColor != Qt.white:
            qtFormat.setBackground(backgroundColor)

        qtFormat.setFontItalic(format.italic)
        qtFormat.setFontWeight(QFont.Bold if format.bold else QFont.Normal)
        qtFormat.setFontUnderline(format.underline)
        qtFormat.setFontStrikeOut(format.strikeOut)

        return qtFormat
Beispiel #53
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

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

        keywordPatterns = [
            "\\bchar\\b", "\\bclass\\b", "\\bconst\\b", "\\bdouble\\b",
            "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b", "\\binline\\b",
            "\\bint\\b", "\\blong\\b", "\\bnamespace\\b", "\\boperator\\b",
            "\\bprivate\\b", "\\bprotected\\b", "\\bpublic\\b", "\\bshort\\b",
            "\\bsignals\\b", "\\bsigned\\b", "\\bslots\\b", "\\bstatic\\b",
            "\\bstruct\\b", "\\btemplate\\b", "\\btypedef\\b",
            "\\btypename\\b", "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b",
            "\\bvoid\\b", "\\bvolatile\\b"
        ]

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

        classFormat = QTextCharFormat()
        classFormat.setFontWeight(QFont.Bold)
        classFormat.setForeground(Qt.darkMagenta)
        self.highlightingRules.append(
            (QRegExp("\\bQ[A-Za-z]+\\b"), classFormat))

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(Qt.red)
        self.highlightingRules.append(
            (QRegExp("//[^\n]*"), singleLineCommentFormat))

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

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat))

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")
Beispiel #54
0
class SuggestionsWidget(QWidget, Ui_SuggestionsWidget):

    STYLE_TRANSLATION, STYLE_STROKES = range(2)

    # Anatomy of the text document:
    # - "root":
    #  - 0+ "suggestions" blocks
    #   - 1+ "translation" blocks
    #    - 1-10 "strokes" blocks

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self._translation_char_format = QTextCharFormat()
        self._strokes_char_format = QTextCharFormat()
        self._strokes_char_format.font().setStyleHint(QFont.Monospace)

    def append(self, suggestion_list, keep_position=False):
        scrollbar = self.suggestions.verticalScrollBar()
        scroll_at_end = scrollbar.value() == scrollbar.maximum()
        cursor = self.suggestions.textCursor()
        cursor.movePosition(QTextCursor.End)
        for suggestion in suggestion_list:
            cursor.insertBlock()
            cursor.setCharFormat(self._translation_char_format)
            cursor.block().setUserState(self.STYLE_TRANSLATION)
            cursor.insertText(escape_translation(suggestion.text) + ':')
            if not suggestion.steno_list:
                cursor.insertText(' ' + _('no suggestions'))
                continue
            for strokes in suggestion.steno_list[:10]:
                cursor.insertBlock()
                cursor.setCharFormat(self._strokes_char_format)
                cursor.block().setUserState(self.STYLE_STROKES)
                cursor.insertText('   ' + strokes)
        cursor.insertText('\n')
        # Keep current position when not at the end of the document, or if the argument says so
        # Otherwise, scroll the window down to keep the new suggestions in view
        if scroll_at_end and not keep_position:
            scrollbar.setValue(scrollbar.maximum())

    def clear(self):
        self.suggestions.clear()

    def _reformat(self):
        document = self.suggestions.document()
        cursor = self.suggestions.textCursor()
        block = document.begin()
        style_format = {
            self.STYLE_TRANSLATION: self._translation_char_format,
            self.STYLE_STROKES: self._strokes_char_format,
        }
        while block != document.end():
            style = block.userState()
            fmt = style_format.get(style)
            if fmt is not None:
                cursor.setPosition(block.position())
                cursor.select(QTextCursor.BlockUnderCursor)
                cursor.setCharFormat(fmt)
            block = block.next()

    @property
    def text_font(self):
        return self._translation_char_format.font()

    @text_font.setter
    def text_font(self, font):
        self._translation_char_format.setFont(font)
        self._reformat()

    @property
    def strokes_font(self):
        return self._strokes_char_format.font()

    @strokes_font.setter
    def strokes_font(self, font):
        self._strokes_char_format.setFont(font)
        self._reformat()
Beispiel #55
0
class TextEditor(QPlainTextEdit):

    FileStrucutreUpdated = pyqtSignal(dict)

    def __init__(self, parent, display_widget: QWebEngineView,
                 settings_manager, thread_manager: ThreadManager,
                 filename: str):

        super().__init__(parent)

        # Set attributes
        self.display_widget = display_widget
        self.SettingsManager = settings_manager
        self.ThreadManager = thread_manager

        self.lineNumberArea = LineNumberArea(self)
        self.InputTimer = QTimer(self)
        self.DocumentParsingTimer = QTimer(self)
        self.highlighter = MarkdownHighlighter(self.document(),
                                               self.SettingsManager)
        self.char_format = QTextCharFormat(self.currentCharFormat())

        self.text_changed_since_save = False
        self.text_changed_since_render = False
        self.setMouseTracking(True)
        self.is_current_editor = False
        self.is_parsing_document = False
        self.filename = ""
        self.rendered_html = ""
        self.set_filename(filename)

        self.document_structure: dict = copy.deepcopy(
            defaults.document_info_template)
        self.ColorSchema = self.SettingsManager.color_schema

        # Connect signals to slots
        self.document().blockCountChanged.connect(
            self.updateLineNumberAreaWidth)
        self.updateRequest.connect(self.updateLineNumberArea)
        self.cursorPositionChanged.connect(self.on_TextEditor_CursorMoved)
        self.textChanged.connect(self.on_TextEditor_textChanged)
        self.selectionChanged.connect(self.on_TextEditor_CursorMoved)
        self.InputTimer.timeout.connect(self.on_InputTimer_timeout)
        self.DocumentParsingTimer.timeout.connect(
            self.on_DocumentParsingTimer_timeout)

        self.updateLineNumberAreaWidth(0)
        self.InputTimer.setSingleShot(True)
        self.DocumentParsingTimer.setSingleShot(True)
        self.read_settings()

        # Trigger it to highlight current line, when the editor is first opened
        self.on_TextEditor_CursorMoved()

    def lineNumberAreaWidth(self) -> int:
        """Returns the width of the line number area depending on the number of digits that need to be displayed"""

        digits = 1
        line_count = max(1, self.document().blockCount())
        while line_count >= 10:
            line_count /= 10
            digits += 1

        if digits < 4:
            digits = 4

        space = 10 + self.fontMetrics().width('9') * digits
        return space

    def updateLineNumberAreaWidth(self, _) -> None:
        """Updates the width of line number area when the number of lines in the document changes"""
        self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)

    def updateLineNumberArea(self, rect, dy) -> None:
        """Updates line number are when the user scrolls or something else happens (not sure how it works)"""

        if dy:
            self.lineNumberArea.scroll(0, dy)
        else:
            self.lineNumberArea.update(0, rect.y(),
                                       self.lineNumberArea.width(),
                                       rect.height())

        if rect.contains(self.viewport().rect()):
            self.updateLineNumberAreaWidth(0)

    def resizeEvent(self, event) -> None:
        """Updates line numbers area when the editor is resized"""

        super().resizeEvent(event)

        cr = self.contentsRect()
        self.lineNumberArea.setGeometry(
            QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(),
                  cr.height()))

    def lineNumberAreaPaintEvent(self, event) -> None:
        """Paints the line number area of the editor"""

        painter = QPainter(self.lineNumberArea)
        color = QColor(
            self.ColorSchema["Editor_colors"]["linenumber_area"]["color"])
        painter.fillRect(event.rect(), color)

        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = self.blockBoundingGeometry(block).translated(
            self.contentOffset()).top()
        bottom = top + self.blockBoundingRect(block).height()

        height = self.fontMetrics().height()
        while block.isValid() and (top <= event.rect().bottom()):
            if block.isVisible() and (bottom >= event.rect().top()):
                number = str(blockNumber + 1)
                color = QColor(self.ColorSchema["Editor_colors"]
                               ["linenumber_text"]["color"])
                painter.setPen(color)
                painter.drawText(5, top, self.lineNumberArea.width(), height,
                                 Qt.AlignLeft, number)

            block = block.next()
            top = bottom
            bottom = top + self.blockBoundingRect(block).height()
            blockNumber += 1

    def on_TextEditor_CursorMoved(self) -> None:
        """Highlights the current line and shows a tooltip if a citation or an image is under text cursor"""

        # Display tool tip for image or citation
        point = self.viewport().mapToGlobal(self.cursorRect().topLeft())
        cursor = self.textCursor()
        if self.is_markdown_file():
            self.display_tooltips_for_cursor(cursor, point)

        # Don't highlight if multiple lines are selected
        extraSelections = []

        selection_start = cursor.selectionStart()
        selection_end = cursor.selectionEnd()
        cursor.setPosition(selection_start)
        start_line_number = cursor.blockNumber()
        cursor.setPosition(selection_end)
        end_line_number = cursor.blockNumber()

        if start_line_number != end_line_number:
            self.setExtraSelections([QTextEdit.ExtraSelection()])
            return

        # Highlight current line
        selection = QTextEdit.ExtraSelection()

        lineColor = QColor(
            self.ColorSchema["Editor_colors"]["current_line"]["color"])

        selection.format.setBackground(lineColor)
        selection.format.setProperty(QTextFormat.FullWidthSelection, True)
        selection.cursor = self.textCursor()
        selection.cursor.clearSelection()
        extraSelections.append(selection)

        self.setExtraSelections(extraSelections)

    def on_TextEditor_textChanged(self) -> None:
        """Set text_changed property to True and start InputTimer. When the timer finishes, the document will be
        rendered, if the settings do not say otherwise (disable autorender)"""

        self.text_changed_since_save = True
        self.text_changed_since_render = True
        if self.SettingsManager.get_setting_value("Render/Autorender"):
            self.InputTimer.start(
                self.SettingsManager.get_setting_value(
                    "Render/Autorender delay"))

    def set_filename(self, filename: str) -> None:
        """Sets the filename field, rehighlights the document according to the new extension"""
        self.filename = filename

        # Remove md syntax highlighting if new file is not markdown
        prevent_highlighting = not self.is_markdown_file()
        self.highlighter.prevent_highlighting(prevent_highlighting)

    def is_markdown_file(self) -> bool:
        """Determines if current file can or cannot be treated as markdown based on file extension"""
        # Return True if there is no file extension or it is a markdown extension
        if "." not in self.filename or self.filename.endswith(
            (".md", ".markdown")):
            return True
        else:
            return False

    def is_html_file(self) -> bool:
        """Determines if current file can or cannot be treated as html based on the file extension"""
        if self.filename.endswith((".html", ".htm")):
            return True
        else:
            return False

    def insert_text_at_cursor(self, text: str, move_center=False) -> None:
        """Inserts text at current cursor position. If move_center is set to True, moves cursor to the center of
        inserted string after insertion"""

        initial_pos = self.textCursor().position()
        self.textCursor().insertText(text)

        if move_center:
            cursor = self.textCursor()
            cursor.setPosition(initial_pos + int(len(text) / 2))
            self.setTextCursor(cursor)

    def insert_text_at_line_beginning(self, text: str) -> None:
        """Inserts text at the beginning of the current line. Tries to keep the cursor position in the string the
        same"""

        init_pos = self.textCursor().position()
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine)
        self.setTextCursor(cursor)
        cursor.insertText(text)

        cursor.setPosition(init_pos + len(text))
        self.setTextCursor(cursor)

    def insert_text_at_selection_bound(self, text: str) -> None:
        """Inserts given text at the beginning and at the end of the current selection"""

        start = self.textCursor().selectionStart()
        end = self.textCursor().selectionEnd()
        self.textCursor().clearSelection()

        cursor = self.textCursor()
        cursor.setPosition(end)
        self.setTextCursor(cursor)
        cursor.insertText(text)

        cursor = self.textCursor()
        cursor.setPosition(start)
        self.setTextCursor(cursor)
        cursor.insertText(text)

    def insert_text_at_empty_paragraph(self, text: str) -> None:
        """Inserts text in an empty paragraph"""

        line_number = self.textCursor().blockNumber()
        if line_number:
            previous_line = self.document().findBlockByNumber(line_number -
                                                              1).text()
        else:
            previous_line = ""

        if self.textCursor().block().text() == "" and previous_line == "":
            self.textCursor().insertText(text)
        elif self.textCursor().block().text() == "" and previous_line != "":
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.EndOfLine)
            cursor.insertText("\n{}".format(text))
        else:
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.EndOfLine)
            cursor.insertText("\n\n{}".format(text))

    def insert_double_tag(self, tag: str) -> None:
        """Inserts a double tag in the text (i.e. italic, bold, etc). Inserts at cursor if no text is selected, or at
        the selection boundaries if there is a selection"""

        if len(self.textCursor().selection().toPlainText()) == 0:
            self.insert_text_at_cursor(tag * 2, move_center=True)
        else:
            self.insert_text_at_selection_bound(tag)

    def move_cursor_to_block(self, block_number: int) -> None:
        """Moves cursor to specified block_number"""
        cursor = QTextCursor(self.document().findBlockByNumber(block_number))
        self.setTextCursor(cursor)

    def display_tooltips_for_cursor(self, cursor: QTextCursor,
                                    display_point: QPoint) -> None:
        """Displays a tooltip at current cursor position if a citation tag or an image tag is under cursor. Hides
        the tooltip if no tags are under cursor"""
        def is_inside_tag(tag, cursor_pos) -> bool:
            """Returns True if given cursor position is inside tag boundaries"""
            return tag[0] <= cursor_pos < (tag[1] + tag[0])

        show_citation_tooltips = self.SettingsManager.get_setting_value(
            "Editor/Show citation tooltips")
        show_image_tooltips = self.SettingsManager.get_setting_value(
            "Editor/Show image tooltips")
        hide_tooltip = True
        current_line_text = cursor.block().text()
        current_line_tags = self.highlighter.get_tags(current_line_text)
        cursor_pos = cursor.positionInBlock()

        for tag in current_line_tags:
            tag_text = current_line_text[tag[0]:tag[0] + tag[1]]

            if show_citation_tooltips and tag[
                    2] == "citation" and is_inside_tag(tag, cursor_pos):
                # Remove brackets and @ symbol from the tag text
                citation_identifier = components.extractors.citation_extractor(
                    tag_text)[0]

                # If the citekey is not in self.document_info["citations"] or doesn't have a citation text yet, show
                # placeholder
                if citation_identifier not in self.document_structure[
                        "citations"]:
                    QToolTip.showText(display_point,
                                      "Fetching citation info...", self,
                                      QRect(), 5000)
                    hide_tooltip = False

                elif citation_identifier in self.document_structure[
                        "citations"] and self.document_structure["citations"][
                            citation_identifier]["citation"] == "":
                    QToolTip.showText(display_point,
                                      "Fetching citation info...", self,
                                      QRect(), 5000)
                    hide_tooltip = False

                # If the citekey is in self.document_info["citations"] and citation show citation info
                else:
                    QToolTip.showText(
                        display_point, self.document_structure["citations"]
                        [citation_identifier]["citation"], self, QRect(), 5000)
                    hide_tooltip = False

            elif show_image_tooltips and tag[2] == "image" and is_inside_tag(
                    tag, cursor_pos):
                # Do nothing
                if not self.SettingsManager.get_setting_value(
                        "Editor/Show citation tooltips"):
                    return

                path = tag_text[tag_text.find("(") + 1:tag_text.find(")")]
                width = self.SettingsManager.get_setting_value(
                    "Editor/Image tooltip width")
                height = self.SettingsManager.get_setting_value(
                    "Editor/Image tooltip height")
                QToolTip.showText(
                    display_point,
                    f"<img src='{path}' width='{width}' height='{height}'>",
                    self, QRect(), 5000)
                hide_tooltip = False

        # Hide tooltip if no image or citation is under cursor
        if hide_tooltip:
            QToolTip.hideText()

    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        """Displays tooltips if citation or image tags are under mouse cursor"""

        pos = event.pos()
        pos.setX(pos.x() - self.viewportMargins().left())
        pos.setY(pos.y() - self.viewportMargins().top())
        cursor = self.cursorForPosition(pos)
        if self.is_markdown_file():
            self.display_tooltips_for_cursor(cursor, event.globalPos())
        super(TextEditor, self).mouseMoveEvent(event)

    def render_to_html(self) -> None:
        """Asks thread manager to render document contents to html"""
        # Load previously rendered output to display widget if text hasn't changed since last render
        if not self.text_changed_since_render:
            self.on_pandoc_thread_finished(self.rendered_html)

        # Render if current filename is markdown
        if self.is_markdown_file():
            self.ThreadManager.perform_operation(
                "render_file",
                self.on_pandoc_thread_finished,
                source=self.toPlainText())
        # Just load text in preview if filename is html
        elif self.is_html_file():
            self.on_pandoc_thread_finished(self.toPlainText())
        # Clear preview othrewise
        else:
            # Send empty strings to display widget to clear it
            self.on_pandoc_thread_finished("")

    def read_settings(self) -> None:
        """Read settings and apply them"""

        font = QFont(
            self.SettingsManager.get_setting_value("Editor/Font name"))
        font.setPointSize(
            self.SettingsManager.get_setting_value("Editor/Font size"))
        self.setFont(font)

        if self.ColorSchema:
            bg_color = self.ColorSchema['Editor_colors']['background']['color']
            text_color = self.ColorSchema['Editor_colors']['text']['color']

            self.setStyleSheet(
                f"QPlainTextEdit {{background-color: {bg_color}; color: {text_color}}}"
            )
            self.char_format.setForeground(
                QColor(self.ColorSchema['Editor_colors']['text']['color']))

    # NOT CURRENTLY USED
    def apply_format_to_line(self,
                             line_number: int,
                             format: QTextCharFormat,
                             block_state: int = None) -> None:
        """Applies given format and block state to the line at given block number"""
        cursor = self.textCursor()
        cursor.setPosition(
            self.document().findBlockByNumber(line_number).position())
        cursor.select(QTextCursor.LineUnderCursor)
        self.setTextCursor(cursor)

        cursor.mergeCharFormat(format)

        if block_state is not None:
            self.document().findBlockByNumber(line_number).setUserState(
                block_state)

    def parse_document(self) -> None:
        """Asks ThreadManager to parse the document for structure if the document isn't already being parsed"""
        if not self.is_parsing_document:
            self.ThreadManager.perform_operation(
                "parse_file",
                self.on_parsing_document_finished,
                disobey_thread_limit=True,
                document=self.document())
            self.is_parsing_document = True

    def is_cursor_in_sentence(self) -> bool:
        """Determines if the cursor is inside a sentence. For example to determine if next word should be
        title-cased."""
        line_number = self.textCursor().blockNumber()
        current_line = self.document().findBlockByNumber(line_number).text()
        cursor_pos = self.textCursor().positionInBlock()

        if not current_line:
            return False

        in_sentence = True
        for index in range(cursor_pos - 1, -1, -1):
            current_symbol = current_line[index]

            if current_symbol in (" ", "\t"):
                continue
            if current_symbol in {".", "!", "?"}:
                in_sentence = False

            break

        return in_sentence

    @pyqtSlot(str)
    def on_pandoc_thread_finished(self, html: str) -> None:
        """Updates document preview when pandoc thread finishes"""
        # TODO: Change to use value from settings
        self.rendered_html = html
        self.text_changed_since_render = False
        self.display_widget.setHtml(
            html,
            QUrl("file:///home/lasest/Working folder/manuwrite/style.css"))

    @pyqtSlot()
    def on_InputTimer_timeout(self) -> None:
        """Renders document to html when the user stops typing if settings allow this"""

        self.render_to_html()

    @pyqtSlot(str, str)
    def on_manubot_thread_finished(self, citation_info: dict) -> None:
        """Adds the citation returned by manubot thread to the self.citations dictionary when the thread is finished"""
        citekey = citation_info["citekey"]
        citation = citation_info["citation"]

        self.document_structure["citations"][citekey]["citation"] = citation

    @pyqtSlot(dict)
    def on_parsing_document_finished(self, data: dict) -> None:
        """Updates self.document_structure with newly parsed data and emits FileStrucutreUpdated so that the main
        window could update the ProjectManager's information about current project structure or display the structure"""
        self.is_parsing_document = False
        parsing_interval = self.SettingsManager.get_setting_value(
            "General/Document_parsing_interval")
        self.DocumentParsingTimer.start(parsing_interval)

        for citation in self.document_structure["citations"].items():
            if citation[0] in data["citations"]:
                data["citations"][
                    citation[0]]["citation"] = citation[1]["citation"]

        for citation in data["citations"].items():
            if citation[1]["citation"] == "":
                self.ThreadManager.perform_operation(
                    "get_citation",
                    self.on_manubot_thread_finished,
                    citekey=citation[0])

        self.document_structure = data

        self.FileStrucutreUpdated.emit(data)

    @pyqtSlot()
    def on_DocumentParsingTimer_timeout(self) -> None:
        """Starts parsing the document structure is this is the currently selected editor"""

        if self.is_current_editor:
            self.parse_document()
Beispiel #56
0
class XMLHighlighter(QSyntaxHighlighter):
    '''
    Class for highlighting xml text inherited from QSyntaxHighlighter
    reference:
        http://www.yasinuludag.com/blog/?p=49
    '''

    def __init__(self, parent=None):

        super(XMLHighlighter, self).__init__(parent)

        self.highlightingRules = []

        xmlElementFormat = QTextCharFormat()
        xmlElementFormat.setForeground(QColor("#3d9cf5"))  # dark magenta
        # self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=[\s/>])"), xmlElementFormat))
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=[\/>])"), xmlElementFormat))
        xmlAttributeFormat = QTextCharFormat()
        xmlAttributeFormat.setFontItalic(True)
        xmlAttributeFormat.setForeground(QColor("#11e4f7"))  # magenta
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\=)"), xmlAttributeFormat))
        self.highlightingRules.append((QRegExp("="), xmlAttributeFormat))

        self.valueFormat = QTextCharFormat()
        self.valueFormat.setForeground(QColor("#e35e00"))  # orange
        self.valueStartExpression = QRegExp("\"")
        self.valueEndExpression = QRegExp("\"(?=[\s></])")
        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(QColor("#228030"))  # green
        self.highlightingRules.append((QRegExp("<!--[^\n]*-->"), singleLineCommentFormat))

        textFormat = QTextCharFormat()
        textFormat.setForeground(QColor("#ebf7e9"))  # light green
        # (?<=...)  - lookbehind is not supported
        self.highlightingRules.append((QRegExp(">(.+)(?=</)"), textFormat))

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(QColor("#686968"))  # grey
        keywordFormat.setFontWeight(QFont.Bold)
        keywordPatterns = ["<\\?", "\\b?xml\\b", "/>", ">", "<", "</", "\\b?\\>"]
        self.highlightingRules += [(QRegExp(pattern), keywordFormat)
                                   for pattern in keywordPatterns]

    # VIRTUAL FUNCTION WE OVERRIDE THAT DOES ALL THE COLLORING
    def highlightBlock(self, text):
        # for every pattern
        for pattern, format in self.highlightingRules:
            # Create a regular expression from the retrieved pattern
            expression = QRegExp(pattern)
            # Check what index that expression occurs at with the ENTIRE text
            index = expression.indexIn(text)
            # While the index is greater than 0
            while index >= 0:
                # Get the length of how long the expression is true, set the format from the start to the length with the text format
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                # Set index to where the expression ends in the text
                index = expression.indexIn(text, index + length)

                # HANDLE QUOTATION MARKS NOW.. WE WANT TO START WITH " AND END WITH ".. A THIRD " SHOULD NOT CAUSE THE WORDS INBETWEEN SECOND AND THIRD TO BE COLORED
        self.setCurrentBlockState(0)
        startIndex = 0
        if self.previousBlockState() != 1:
            startIndex = self.valueStartExpression.indexIn(text)
        while startIndex >= 0:
            endIndex = self.valueEndExpression.indexIn(text, startIndex)
            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLength = len(text) - startIndex
            else:
                commentLength = endIndex - startIndex + self.valueEndExpression.matchedLength()
            self.setFormat(startIndex, commentLength, self.valueFormat)
            startIndex = self.valueStartExpression.indexIn(text, startIndex + commentLength);
    def add_io(self, vbox):
        vbox.addWidget(QLabel(_("Inputs") + ' (%d)' % len(self.tx.inputs())))
        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(ColorScheme.GREEN.as_color(background=True)))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(ColorScheme.YELLOW.as_color(background=True)))
        chg.setToolTip(_("Wallet change address"))
        twofactor = QTextCharFormat()
        twofactor.setBackground(
            QBrush(ColorScheme.BLUE.as_color(background=True)))
        twofactor.setToolTip(
            _("TrustedCoin (2FA) fee for the next batch of transactions"))

        def text_format(addr):
            if self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            elif self.wallet.is_billing_address(addr):
                return twofactor
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text = QTextEditWithDefaultSize()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        cursor = i_text.textCursor()
        for x in self.tx.inputs():
            if x['type'] == 'coinbase':
                cursor.insertText('coinbase')
            else:
                prevout_hash = x.get('prevout_hash')
                prevout_n = x.get('prevout_n')
                cursor.insertText(prevout_hash + ":%-4d " % prevout_n, ext)
                addr = self.wallet.get_txin_address(x)
                if addr is None:
                    addr = ''
                cursor.insertText(addr, text_format(addr))
                if x.get('value'):
                    cursor.insertText(format_amount(x['value']), ext)
            cursor.insertBlock()

        vbox.addWidget(i_text)
        vbox.addWidget(QLabel(_("Outputs") + ' (%d)' % len(self.tx.outputs())))
        o_text = QTextEditWithDefaultSize()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        cursor = o_text.textCursor()
        for o in self.tx.get_outputs_for_UI():
            addr, name, v = o.address, o.name, o.value
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                if name:
                    cursor.insertText('\t', ext)
                    cursor.insertText(name, ext)
                cursor.insertText('\t', ext)
                cursor.insertText(format_amount(v), ext)
            cursor.insertBlock()
        vbox.addWidget(o_text)
    def update_io(self):
        inputs_header_text = _("Inputs") + ' (%d)' % len(self.tx.inputs())
        if not self.finalized:
            selected_coins = self.main_window.get_manually_selected_coins()
            if selected_coins is not None:
                inputs_header_text += f"  -  " + _(
                    "Coin selection active ({} UTXOs selected)").format(
                        len(selected_coins))
        self.inputs_header.setText(inputs_header_text)

        ext = QTextCharFormat()
        tf_used_recv, tf_used_change = False, False

        def text_format(addr):
            nonlocal tf_used_recv, tf_used_change
            if self.wallet.is_mine(addr):
                if self.wallet.is_change(addr):
                    tf_used_change = True
                    return self.txo_color_change.text_char_format
                else:
                    tf_used_recv = True
                    return self.txo_color_recv.text_char_format
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text = self.inputs_textedit
        i_text.clear()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        cursor = i_text.textCursor()
        for txin in self.tx.inputs():
            if txin.is_coinbase_input():
                cursor.insertText(self.get_coinbase_tx_type(txin))
            else:
                prevout_hash = txin.prevout.txid.hex()
                prevout_n = txin.prevout.out_idx
                cursor.insertText(prevout_hash + ":%-4d " % prevout_n, ext)
                addr = self.wallet.get_txin_address(txin)
                if addr is None:
                    addr = ''
                cursor.insertText(addr, text_format(addr))
                txin_value = self.wallet.get_txin_value(txin)
                if txin_value is not None:
                    cursor.insertText(format_amount(txin_value), ext)
            cursor.insertBlock()

        self.outputs_header.setText(
            _("Outputs") + ' (%d)' % len(self.tx.outputs()))
        o_text = self.outputs_textedit
        o_text.clear()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        cursor = o_text.textCursor()
        for o in self.tx.outputs():
            addr, v = o.get_ui_address_str(), o.value
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                cursor.insertText('\t', ext)
                cursor.insertText(format_amount(v), ext)
            cursor.insertBlock()

        self.txo_color_recv.legend_label.setVisible(tf_used_recv)
        self.txo_color_change.legend_label.setVisible(tf_used_change)
    def __init__(self, parent=None):
        super(JavaScriptHighlighter, self).__init__(parent)

        self.highlightingRules = []

        keyword0Format = QTextCharFormat()
        keyword0Format.setForeground(QColor(51, 255, 255))
        keyword0Format.setFontWeight(QFont.Bold)

        keyword0Patterns = ['\\bif\\b','\\belse\\b','\\bcase\\b','\\bswitch\\b','\\bdefault\\b',]

        for pattern in keyword0Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword0Format))

        keyword1Format = QTextCharFormat()
        keyword1Format.setForeground(QColor(102, 205, 170))
        keyword1Format.setFontWeight(QFont.Bold)

        keyword1Patterns = ['\\bclass\\b','\\bsuper\\b','\\bprivate\\b','\\bprotected\\b','\\bpublic\\b',]

        for pattern in keyword1Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword1Format))

        keyword2Format = QTextCharFormat()
        keyword2Format.setForeground(QColor(255,218,185))
        keyword2Format.setFontWeight(QFont.Bold)

        keyword2Patterns = ['\\btrue\\b','\\bfalse\\b',]

        for pattern in keyword2Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword2Format))

        keyword3Format = QTextCharFormat()
        keyword3Format.setForeground(QColor(124,252,0))
        keyword3Format.setFontWeight(QFont.Bold)

        keyword3Patterns = ['\\bdelete\\b','\\bfunction\\b','\\bin\\b','\\binstanceof\\b','\\bnew\\b','\\bthis\\b','\\btypeof\\b',]

        for pattern in keyword3Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword3Format))
        
        keyword4Format = QTextCharFormat()
        keyword4Format.setForeground(QColor(205,133,63))
        keyword4Format.setFontWeight(QFont.Bold)

        keyword4Patterns = ['\\btry\\b', 'throw\\b','\\bcatch\\b',]

        for pattern in keyword4Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword4Format))
        
        keyword5Format = QTextCharFormat()
        keyword5Format.setForeground(QColor(70, 130, 180))
        keyword5Format.setFontWeight(QFont.Bold)

        keyword5Patterns = ['\\bbreak\\b','\\bcontinue\\b',]

        for pattern in keyword5Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword5Format))
        
        keyword6Format = QTextCharFormat()
        keyword6Format.setForeground(QColor(212, 175, 55))
        keyword6Format.setFontWeight(QFont.Bold)

        keyword6Patterns = ['\\bdo\\b','\\bwhile\\b','\\bfor\\b',]

        for pattern in keyword6Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword6Format))
        
        keyword7Format = QTextCharFormat()
        keyword7Format.setForeground(QColor(123,104,238))
        keyword7Format.setFontWeight(QFont.Bold)

        keyword7Patterns = ['\\bconst\\b','\\bvar\\b','\\blet\\b',]

        for pattern in keyword7Patterns:
                self.highlightingRules.append((QRegExp(pattern), keyword7Format))

        bracesFormat = QTextCharFormat()
        bracesFormat.setForeground(QColor(QColor(169,169,169)))
        bracesFormat.setFontWeight(QFont.Bold)

        bracesPatterns = ['\\b\{\\b', '\\b}\\b', '\\b(\\b', '\\b)\\b', '\\b[\\b', '\\b]\\b']

        for pattern in bracesPatterns:
                self.highlightingRules.append((QRegExp(pattern), bracesFormat))

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(Qt.red)
        self.highlightingRules.append((QRegExp("//[^\n]*"),
                singleLineCommentFormat))


        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(QColor(135,206,235))
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
                functionFormat))

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")
    def update_io(self, i_text, o_text):
        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(ColorScheme.GREEN.as_color(background=True)))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(QColor("yellow")))
        chg.setToolTip(_("Wallet change address"))

        def text_format(addr):
            if isinstance(addr, Address) and self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text.clear()
        cursor = i_text.textCursor()
        for txin in self.tx.inputs:
            if txin.is_coinbase():
                cursor.insertText('coinbase')
            else:
                prev_hash = hash_to_hex_str(txin.prev_hash)
                prev_idx = txin.prev_idx
                cursor.insertText(f'{prev_hash}:{prev_idx:<6d}', ext)
                addr = txin.address
                if isinstance(addr, PublicKey):
                    addr = addr.toAddress()
                if addr is None:
                    addr_text = _('unknown')
                else:
                    addr_text = addr.to_string()
                cursor.insertText(addr_text, text_format(addr))
                if txin.value is not None:
                    cursor.insertText(format_amount(txin.value), ext)
            cursor.insertBlock()

        o_text.clear()
        cursor = o_text.textCursor()
        for tx_output in self.tx.outputs:
            text, kind = tx_output_to_display_text(tx_output)
            cursor.insertText(text, text_format(kind))

            if len(text) > 42:  # for long outputs, make a linebreak.
                cursor.insertBlock()
                text = '\u21b3'
                cursor.insertText(text, ext)
            # insert enough spaces until column 43, to line up amounts
            cursor.insertText(' ' * (43 - len(text)), ext)
            cursor.insertText(format_amount(tx_output.value), ext)
            cursor.insertBlock()