Exemplo n.º 1
0
def test_HtmlSH_unclosed_commend():
    txt = '-->'
    doc = QTextDocument(txt)
    sh = HtmlSH(doc, color_scheme='Spyder')
    sh.rehighlightBlock(doc.firstBlock())
    res = [(0, 3, 'normal')]
    compare_formats(doc.firstBlock().layout().additionalFormats(), res, sh)
Exemplo n.º 2
0
    def sizeHint(self, option, index):
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        doc = QTextDocument()
        doc.setHtml(options.text)

        return QSize(doc.idealWidth(), doc.size().height() - 2)
Exemplo n.º 3
0
    def paint(self, painter, option, index):
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        style = (QApplication.style()
                 if options.widget is None else options.widget.style())

        doc = QTextDocument()
        doc.setDocumentMargin(self._margin)
        doc.setHtml(options.text)

        options.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
        painter.save()
        if style.objectName() == 'oxygen':
            painter.translate(textRect.topLeft() + QPoint(5, -9))
        else:
            painter.translate(textRect.topLeft())
            painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Exemplo n.º 4
0
def test_HtmlSH_basic():
    txt = '<p style="color:red;">Foo <!--comment--> bar.</p>'
    doc = QTextDocument(txt)
    sh = HtmlSH(doc, color_scheme='Spyder')
    sh.rehighlightBlock(doc.firstBlock())

    # Expected result as list of tuples (begin, length, format)
    res = [(0, 2, 'builtin'),    # |<p|
           (2, 6, 'keyword'),    # | style|
           (8, 1, 'normal'),     # | |
           (9, 12, 'string'),    # |"color:red;"|
           (21, 1, 'builtin'),   # |>|
           (22, 4, 'normal'),    # |Foo |
           (26, 14, 'comment'),  # |<!--comment-->|
           (40, 5, 'normal'),    # | bar.|
           (45, 4, 'builtin')]   # |</p>|
    compare_formats(doc.firstBlock().layout().additionalFormats(), res, sh)
Exemplo n.º 5
0
def test_HtmlSH_basic():
    txt = '<p style="color:red;">Foo <!--comment--> bar.</p>'
    doc = QTextDocument(txt)
    sh = HtmlSH(doc, color_scheme='Spyder')
    sh.rehighlightBlock(doc.firstBlock())

    # Expected result as list of tuples (begin, length, format)
    res = [(0, 2, 'builtin'),    # |<p|
           (2, 6, 'keyword'),    # | style|
           (8, 1, 'normal'),     # | |
           (9, 12, 'string'),    # |"color:red;"|
           (21, 1, 'builtin'),   # |>|
           (22, 4, 'normal'),    # |Foo |
           (26, 14, 'comment'),  # |<!--comment-->|
           (40, 5, 'normal'),    # | bar.|
           (45, 4, 'builtin')]   # |</p>|
    compare_formats(doc.firstBlock().layout().additionalFormats(), res, sh)
Exemplo n.º 6
0
    def paint(self, painter, option, index):
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        style = (QApplication.style() if options.widget is None
                 else options.widget.style())

        doc = QTextDocument()
        doc.setDocumentMargin(self._margin)
        doc.setHtml(options.text)

        options.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
        painter.save()

        # Adjustments for the file switcher
        if hasattr(options.widget, 'files_list'):
            if style.objectName() in ['oxygen', 'qtcurve', 'breeze']:
                if options.widget.files_list:
                    painter.translate(textRect.topLeft() + QPoint(4, -9))
                else:
                    painter.translate(textRect.topLeft())
            else:
                if options.widget.files_list:
                    painter.translate(textRect.topLeft() + QPoint(4, 4))
                else:
                    painter.translate(textRect.topLeft() + QPoint(2, 4))
        else:
            painter.translate(textRect.topLeft() + QPoint(0, -3))
        doc.documentLayout().draw(painter, ctx)
        painter.restore()
Exemplo n.º 7
0
    def paint(self, painter, option, index):
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        style = QApplication.style() if options.widget is None else options.widget.style()

        doc = QTextDocument()
        doc.setDocumentMargin(self._margin)
        doc.setHtml(options.text)

        options.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
        painter.save()
        if style.objectName() == "oxygen":
            painter.translate(textRect.topLeft() + QPoint(5, -9))
        else:
            painter.translate(textRect.topLeft())
            painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Exemplo n.º 8
0
    def findForwardText(self, text):
        flags = QTextDocument.FindFlag()

        if self.find_case:
            flags |= QTextDocument.FindCaseSensitively
        if self.find_words:
            flags |= QTextDocument.FindWholeWords

        found = self.find(text, flags)
Exemplo n.º 9
0
def test_Markdown_basic():
    txt = "Some __random__ **text** with ~~different~~ [styles](link_url)"

    doc = QTextDocument(txt)
    sh = MarkdownSH(doc, color_scheme='Spyder')
    sh.rehighlightBlock(doc.firstBlock())

    res = [(0, 5, 'normal'),  # |Some|
           (5, 10, 'italic'),  # |__random__|
           (15, 1, 'normal'),  # | |
           (16, 8, 'strong'),  # |**text**|
           (24, 6, 'normal'),  # |with|
           (30, 13, 'italic'),  # |~~diferents~~|
           (43, 1, 'normal'),  # | |
           (44, 8, 'string'),  # |[styles]|
           (52, 1, 'normal'),  # |(|
           (53, 8, 'string'),  # |(link_url)|
           (61, 1, 'normal'),  # ||
           ]

    compare_formats(doc.firstBlock().layout().additionalFormats(), res, sh)
Exemplo n.º 10
0
def test_python_string_prefix():
    if PY3:
        prefixes = ("r", "u", "R", "U", "f", "F", "fr", "Fr", "fR", "FR",
                    "rf", "rF", "Rf", "RF", "b", "B", "br", "Br", "bR", "BR",
                    "rb", "rB", "Rb", "RB")
    else:
        prefixes = ("r", "u", "ur", "R", "U", "UR", "Ur", "uR", "b", "B",
                    "br", "Br", "bR", "BR")
    for prefix in prefixes:
        txt = "[%s'test', %s'''test''']" % (prefix, prefix)

        doc = QTextDocument(txt)
        sh = PythonSH(doc, color_scheme='Spyder')
        sh.rehighlightBlock(doc.firstBlock())

        offset = len(prefix)
        res = [(0, 1, 'normal'),                     # |[|
               (1, 6 + offset, 'string'),            # |{prefix}'test'|
               (7 + offset, 2, 'normal'),            # |, |
               (9 + offset, 10 + offset, 'string'),  # |{prefix}'''test'''|
               (19 + 2*offset, 1, 'normal')]         # | |

        compare_formats(doc.firstBlock().layout().additionalFormats(), res, sh)
Exemplo n.º 11
0
    def __init__(self, *args, **kwargs):
        """Frame used in css styling with fade in and fade out effect."""
        super(FrameContentHover, self).__init__(*args, **kwargs)

        self.current_opacity = 0
        self.max_frame = 100
        self.max_opacity = 0.95
        self.button_text = None
        self.label_icon = None
        self.label_text = None
        self.summary = ''

        # Widgets
        self.text_document = QTextDocument(self)
        self.timeline = QTimeLine(500)

        font = QFont()

        if sys.platform == 'darwin':
            font.setPointSize(12)
        elif os.name == 'nt':
            font.setPointSize(9)
        else:
            font.setPointSize(9)

        self.text_document.setDefaultFont(font)
        self.text_document.setMaximumBlockCount(5)
        self.text_document.setDocumentMargin(10)
        # Setup
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAutoFillBackground(True)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setMinimumSize(self.widget_size())
        self.timeline.setFrameRange(0, self.max_frame)

        # Signals
        self.timeline.frameChanged.connect(self.set_opacity)
Exemplo n.º 12
0
    def replaceText(self, search, replace):

        flags = QTextDocument.FindFlag()

        if self.find_case:
            flags |= QTextDocument.FindCaseSensitively
        if self.find_words:
            flags |= QTextDocument.FindWholeWords

        found = self.find(search, flags)
        if found:
            cursor = self.textCursor()
            cursor.beginEditBlock()
            if cursor.hasSelection():
                cursor.insertText(replace)
            cursor.endEditBlock()
Exemplo n.º 13
0
    def paint(self, painter, option, index):
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)
        style = (QApplication.style()
                 if options.widget is None else options.widget.style())

        # Set background color for selected and hovered items.
        # Inspired by:
        # - https://stackoverflow.com/a/43253004/438386
        # - https://stackoverflow.com/a/27274233/438386

        # This is commented for now until we find a way to correctly colorize
        # the entire line with a single color.
        # if options.state & QStyle.State_Selected:
        #     # This only applies when the selected item doesn't have focus
        #     if not (options.state & QStyle.State_HasFocus):
        #         options.palette.setBrush(
        #             QPalette.Highlight,
        #             QBrush(self._background_color)
        #         )

        if options.state & QStyle.State_MouseOver:
            painter.fillRect(option.rect, self._background_color)

        # Set text
        doc = QTextDocument()
        text = options.text
        doc.setHtml(text)
        doc.setDocumentMargin(0)

        # This needs to be an empty string to avoid overlapping the
        # normal text of the QTreeWidgetItem
        options.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options,
                                        None)
        painter.save()

        painter.translate(textRect.topLeft() + QPoint(0, 4))
        doc.documentLayout().draw(painter, ctx)
        painter.restore()
Exemplo n.º 14
0
class TestFoldScopeHelper(object):

    test_case = """# -*- coding: utf-8 -*-
def my_add():
    a = 1
    b = 2
    return a + b
"""

    doc = QTextDocument(test_case)
    sh = PythonSH(doc, color_scheme='Spyder')
    sh.fold_detector = IndentFoldDetector()
    sh.rehighlightBlock(doc.firstBlock())
    block = doc.firstBlock()
    block = block.next()
    TextBlockHelper.set_fold_trigger(block, True)
    fold_scope = FoldScope(block)
    oed = block.userData().oedata

    def test_fold_scope_helper(self):
        fsh = cfd.FoldScopeHelper(None, None)
        assert isinstance(fsh, cfd.FoldScopeHelper)

    def test_fold_scope_helper_str(self):
        fsh = cfd.FoldScopeHelper(self.fold_scope, self.oed)
        assert "my_add" in str(fsh)

    def test_fold_scope_helper_str_with_parents(self):
        fsh = cfd.FoldScopeHelper(self.fold_scope, self.oed)
        fsh.parents = ["fake parent list!"]
        assert "parents:" in str(fsh)

    def test_fold_scope_helper_repr(self):
        fsh = cfd.FoldScopeHelper(self.fold_scope, self.oed)
        assert "(at 0x" in repr(fsh)

    def test_fold_scope_helper_properties(self):
        fsh = cfd.FoldScopeHelper(self.fold_scope, self.oed)
        assert fsh.range == (1, 4)
        assert fsh.start_line == 1
        assert fsh.end_line == 4
        assert fsh.name == "my_add"
        assert fsh.line == 1
        assert fsh.def_type == OED.FUNCTION_TOKEN
Exemplo n.º 15
0
    def findAllText(self, text):
        flags = QTextDocument.FindFlag(0)

        if self.find_case:
            flags |= QTextDocument.FindCaseSensitively
        if self.find_words:
            flags |= QTextDocument.FindWholeWords

        searching = True
        cursor = self.textCursor()

        while searching:
            found = self.find(text, flags)
            if found:
                cursor = self.textCursor()
            else:
                searching = False

        if cursor.hasSelection():
            self.setTextCursor(cursor)
Exemplo n.º 16
0
class FrameContentHover(FrameBase):
    """Frame used in css styling with fade in and fade out effect."""

    sig_clicked = Signal()
    sig_entered = Signal()
    sig_left = Signal()

    def __init__(self, *args, **kwargs):
        """Frame used in css styling with fade in and fade out effect."""
        super(FrameContentHover, self).__init__(*args, **kwargs)

        self.current_opacity = 0
        self.max_frame = 100
        self.max_opacity = 0.95
        self.button_text = None
        self.label_icon = None
        self.label_text = None
        self.summary = ''

        # Widgets
        self.text_document = QTextDocument(self)
        self.timeline = QTimeLine(500)

        font = QFont()

        if sys.platform == 'darwin':
            font.setPointSize(12)
        elif os.name == 'nt':
            font.setPointSize(9)
        else:
            font.setPointSize(9)

        self.text_document.setDefaultFont(font)
        self.text_document.setMaximumBlockCount(5)
        self.text_document.setDocumentMargin(10)
        # Setup
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAutoFillBackground(True)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setMinimumSize(self.widget_size())
        self.timeline.setFrameRange(0, self.max_frame)

        # Signals
        self.timeline.frameChanged.connect(self.set_opacity)

    def set_opacity(self, val):
        """Set the opacity via timeline."""
        self.current_opacity = (val * 1.0 / self.max_frame) * self.max_opacity
        self.update()

    def widget_size(self):
        """Return hover frame size."""
        bheight = 40 if self.button_text is None else self.button_text.height()

        width = SASS_VARIABLES.WIDGET_CONTENT_TOTAL_WIDTH
        height = SASS_VARIABLES.WIDGET_CONTENT_TOTAL_HEIGHT
        padding = SASS_VARIABLES.WIDGET_CONTENT_PADDING
        margin = 0  # SASS_VARIABLES.WIDGET_CONTENT_MARGIN
        return QSize(
            width - 2 * (padding + margin), height - 2 * margin - bheight
        )

    def fade_in(self):
        """Fade in hover card with text."""
        self.raise_()
        self.timeline.stop()
        self.timeline.setDirection(QTimeLine.Forward)
        self.timeline.start()

    def fade_out(self):
        """Fade out hover card with text."""
        self.timeline.stop()
        self.timeline.setDirection(QTimeLine.Backward)
        self.timeline.start()

    def enterEvent(self, event):
        """Override Qt method."""
        super(FrameContentHover, self).enterEvent(event)
        self.fade_in()
        self.sig_entered.emit()

    def leaveEvent(self, event):
        """Override Qt method."""
        super(FrameContentHover, self).leaveEvent(event)
        self.fade_out()
        self.sig_left.emit()

    def mousePressEvent(self, event):
        """Override Qt method."""
        self.sig_clicked.emit()

    def paintEvent(self, event):
        """Override Qt method."""
        painter = QPainter(self)
        painter.setOpacity(self.current_opacity)

        max_width = (
            SASS_VARIABLES.WIDGET_CONTENT_TOTAL_WIDTH - 2 *
            SASS_VARIABLES.WIDGET_CONTENT_PADDING - 2 *
            SASS_VARIABLES.WIDGET_CONTENT_MARGIN
        )

        # Hover top
        br = self.label_icon.rect().bottomRight()
        tl = self.label_icon.rect().topLeft() + QPoint(1, 1)
        y = br.y() + self.label_text.height() - 2
        #        br_new = QPoint(br.x() + 2, y) - QPoint(1, 1)
        br_new = QPoint(max_width - 1, y) - QPoint(1, 1)
        rect_hover = QRect(tl, br_new)  # 2 is the border

        pen = QPen(Qt.NoPen)
        brush = QBrush(Qt.SolidPattern)
        brush.setColor(QColor('#fff'))
        painter.setBrush(brush)
        painter.setPen(pen)
        painter.drawRect(rect_hover)

        font = self.font()
        font.setPointSize(10)
        painter.setFont(font)
        pen = QPen()
        pen.setColor(QColor('black'))
        painter.setPen(pen)
        td = self.text_document
        td.setPageSize(QSizeF(rect_hover.size()))
        td.setHtml(self.summary)
        td.drawContents(painter)

        self.raise_()