def paintEvent(self, event):
		"""
		Reimplements the :meth:`QWidget.paintEvent` method.
		
		:param event: Event.
		:type event: QEvent
		"""

		def __setBold(state):
			"""
			Sets the current painter font bold state.

			:return: Definiton success.
			:rtype: bool
			"""

			font = painter.font()
			font.setBold(state)
			painter.setFont(font)
			return True

		painter = QPainter(self)
		painter.fillRect(event.rect(), self.__backgroundColor)

		pen = QPen(QBrush(), self.__separatorWidth)
		pen.setColor(self.__separatorColor)
		painter.setPen(pen)
		topRightCorner = event.rect().topRight()
		bottomRightCorner = event.rect().bottomRight()
		painter.drawLine(topRightCorner.x(), topRightCorner.y(), bottomRightCorner.x(), bottomRightCorner.y())
		painter.setPen(self.__color)

		viewportHeight = self.__editor.viewport().height()
		metrics = QFontMetrics(self.__editor.document().defaultFont())
		currentBlock = self.__editor.document().findBlock(
			self.__editor.textCursor().position())

		block = self.__editor.firstVisibleBlock()
		blockNumber = block.blockNumber()
		painter.setFont(self.__editor.document().defaultFont())

		while block.isValid():
			blockNumber += 1
			position = self.__editor.blockBoundingGeometry(block).topLeft() + self.__editor.contentOffset()
			if position.y() > viewportHeight:
				break

			if not block.isVisible():
				continue

			block == currentBlock and __setBold(True) or __setBold(False)
			painter.drawText(self.width() - metrics.width(foundations.strings.toString(blockNumber)) - self.__margin / 3,
							round(position.y() + metrics.ascent() + metrics.descent() - \
							(self.__editor.blockBoundingRect(block).height() * 8.0 / 100)),
							foundations.strings.toString(blockNumber))
			block = block.next()

		painter.end()
		QWidget.paintEvent(self, event)
 def _drawEntryRow(self, painter, option, index):
     """ Отрисовка строки с записью """
     fontColor = Qt.black
     if option.state & QStyle.State_Selected:
         painter.fillRect(option.rect, option.palette.highlight())
         fontColor = Qt.white
     elif settings.useAlternateRowColors() and index.row() % 2 == 1:
         painter.fillRect(option.rect, QColor('#DDEBFF'))
     indexIsNotLastInCategory = index.sibling(index.row() + 1, index.column()).isValid()
     if indexIsNotLastInCategory:
         painter.setPen(QColor(250, 250, 250))
         painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
     iconHeight = settings.entryIconHeight()
     if settings.oneLineEntry():
         y = (option.rect.height() - iconHeight) / 2
     else:
         y = settings.entryTopBottomMargin()
     iconPoint = QPoint(option.rect.left(), option.rect.top() + y)
     if index.data(Qt.CheckStateRole):
         painter.drawPixmap(iconPoint, QPixmap(":/icons/interesting.svg"))
     else:
         painter.drawPixmap(iconPoint, QPixmap(":/icons/boring.svg"))
     painter.setFont(index.data(Qt.FontRole))
     painter.setPen(fontColor)
     baseLine = (option.rect.height() + option.fontMetrics.ascent()) / 2
     blog, title = tuple(i.strip() for i in index.data().split("/", 1))
     fontMetrics = QFontMetrics(index.data(Qt.FontRole))
     totalWidth = option.rect.width()
     iconWidth = settings.entryIconWidth() + settings.entryLeftMargin()
     blogWidth = fontMetrics.width(blog)
     titleWidth = totalWidth - iconWidth - blogWidth
     if settings.oneLineEntry():
         textY = blogY = option.rect.top() + baseLine
         textX = option.rect.left() + iconWidth
         blogX = option.rect.right() - blogWidth
         elidedTitle = fontMetrics.elidedText(title, Qt.ElideRight, titleWidth)
     else:
         textX = blogX = option.rect.left() + iconWidth
         textY = option.rect.top() + 2 * fontMetrics.ascent()
         blogY = option.rect.top() + fontMetrics.ascent()
         elidedTitle = fontMetrics.elidedText(title, Qt.ElideRight, totalWidth - iconWidth)
     painter.drawText(textX, textY, elidedTitle)
     painter.setPen(Qt.lightGray)
     painter.drawText(blogX, blogY, blog)
Beispiel #3
0
        def paintEvent(self, event):
            contents_y = 0
            page_bottom = self.edit.viewport().height()
            font_metrics = QFontMetrics(self.edit.document().defaultFont())
            current_block = self.edit.document().findBlock(
                self.edit.textCursor().position())

            painter = QPainter(self)
            painter.fillRect(self.rect(), Qt.lightGray)

            block = self.edit.firstVisibleBlock()
            viewport_offset = self.edit.contentOffset()
            line_count = block.blockNumber()
            painter.setFont(self.edit.document().defaultFont())
            while block.isValid():
                line_count += 1
                # The top left position of the block in the document
                position = self.edit.blockBoundingGeometry(
                    block).topLeft() + viewport_offset
                # Check if the position of the block is out side of the visible area
                if position.y() > page_bottom:
                    break

                # We want the line number for the selected line to be bold.
                bold = False
                if block == current_block:
                    bold = True
                    font = painter.font()
                    font.setBold(True)
                    painter.setFont(font)

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(
                    self.width() - font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() +
                    font_metrics.descent() - 1, str(line_count))

                # Remove the bold style if it was set previously.
                if bold:
                    font = painter.font()
                    font.setBold(False)
                    painter.setFont(font)

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
Beispiel #4
0
        def paintEvent(self, event):
            contents_y = 0
            page_bottom = self.edit.viewport().height()
            font_metrics = QFontMetrics(self.edit.document().defaultFont())
            current_block = self.edit.document().findBlock(self.edit.textCursor().position())
 
            painter = QPainter(self)
            painter.fillRect(self.rect(), Qt.lightGray)
            
            block = self.edit.firstVisibleBlock()
            viewport_offset = self.edit.contentOffset()
            line_count = block.blockNumber()
            painter.setFont(self.edit.document().defaultFont())
            while block.isValid():
                line_count += 1
                # The top left position of the block in the document
                position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset
                # Check if the position of the block is out side of the visible area
                if position.y() > page_bottom:
                    break
 
                # We want the line number for the selected line to be bold.
                bold = False
                if block == current_block:
                    bold = True
                    font = painter.font()
                    font.setBold(True)
                    painter.setFont(font)
 
                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(self.width() - font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent()+font_metrics.descent()-1,
                    str(line_count))
 
                # Remove the bold style if it was set previously.
                if bold:
                    font = painter.font()
                    font.setBold(False)
                    painter.setFont(font)
 
                block = block.next()
 
            self.highest_line = line_count
            painter.end()
 
            QWidget.paintEvent(self, event)
Beispiel #5
0
    def paintEvent(self, ev):
        rect = ev.rect()
        s = self._square
        rows = range(rect.top() // s, rect.bottom() // s + 1)
        cols = range(rect.left() // s, rect.right() // s + 1)

        painter = QPainter(self)
        painter.setPen(QPen(self.palette().color(QPalette.Window)))
        painter.setFont(self._font)
        metrics = QFontMetrics(self._font)

        # draw characters on white tiles
        tile = self.palette().color(QPalette.Base)
        selected_tile = self.palette().color(QPalette.Highlight)
        selected_tile.setAlpha(96)
        selected_box = self.palette().color(QPalette.Highlight)

        text_pen = QPen(self.palette().text())
        disabled_pen = QPen(self.palette().color(QPalette.Disabled,
                                                 QPalette.Text))
        selection_pen = QPen(selected_box)
        for row in rows:
            for col in cols:
                char = row * self._column_count + col + self._range[0]
                if char > self._range[1]:
                    break
                printable = self.isprint(char)
                painter.setClipRect(col * s, row * s, s, s)
                if char == self._selected:
                    painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2,
                                     selected_tile)
                    painter.setPen(selection_pen)
                    painter.drawRect(col * s, row * s, s - 1, s - 1)
                elif printable:
                    painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2,
                                     tile)
                painter.setPen(text_pen if printable else disabled_pen)
                t = chr(char)
                x = col * s + s // 2 - metrics.width(t) // 2
                y = row * s + 4 + metrics.ascent()
                painter.drawText(x, y, t)
            else:
                continue
            break
Beispiel #6
0
    def paintEvent(self, event):
        """This method draws a left sidebar

        :param event: QEvent
        """

        bottom = self.editor.viewport().height()
        font_metrics = QFontMetrics(self.editor.document().defaultFont())
        current_line = self.editor.document().findBlock(
            self.editor.textCursor().position()).blockNumber() + 1
        painter = QPainter(self)
        painter.fillRect(self.rect(), QColor("#D0D0D0"))
        block = self.editor.firstVisibleBlock()
        vpoffset = self.editor.contentOffset()
        line = block.blockNumber()
        painter.setFont(self.editor.document().defaultFont())

        while block.isValid():
            line += 1
            pos = self.editor.blockBoundingGeometry(block).topLeft() + vpoffset
            if pos.y() > bottom:
                break

            # Text bold
            font = painter.font()
            if current_line == line:
                font.setBold(True)
            else:
                font.setBold(False)
            painter.setFont(font)

            if block.isVisible():
                fm_ascent = font_metrics.ascent()
                fm_descent = font_metrics.descent()
                painter.drawText(self.width() -
                                 font_metrics.width(str(line)) + 1,
                                 pos.y() + fm_ascent + fm_descent, str(line))

            block = block.next()
        painter.end()
        QFrame.paintEvent(self, event)
Beispiel #7
0
 def paintEvent(self, ev):
     rect = ev.rect()
     s = self._square
     rows = range(rect.top() // s, rect.bottom() // s + 1)
     cols = range(rect.left() // s, rect.right() // s + 1)
     
     painter = QPainter(self)
     painter.setPen(QPen(self.palette().color(QPalette.Window)))
     painter.setFont(self._font)
     metrics = QFontMetrics(self._font)
     
     # draw characters on white tiles
     tile = self.palette().color(QPalette.Base)
     selected_tile = self.palette().color(QPalette.Highlight)
     selected_tile.setAlpha(96)
     selected_box = self.palette().color(QPalette.Highlight)
     
     text_pen = QPen(self.palette().text())
     disabled_pen = QPen(self.palette().color(QPalette.Disabled, QPalette.Text))
     selection_pen = QPen(selected_box)
     for row in rows:
         for col in cols:
             char = row * self._column_count + col + self._range[0]
             if char > self._range[1]:
                 break
             printable = self.isprint(char)
             painter.setClipRect(col * s, row * s, s, s)
             if char == self._selected:
                 painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, selected_tile)
                 painter.setPen(selection_pen)
                 painter.drawRect(col * s, row * s, s - 1, s - 1)
             elif printable:
                 painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, tile)
             painter.setPen(text_pen if printable else disabled_pen)
             t = chr(char)
             x = col * s + s // 2 - metrics.width(t) // 2
             y = row * s + 4 + metrics.ascent()
             painter.drawText(x, y, t)
         else:
             continue
         break
Beispiel #8
0
class ZTextWidget(QWidget):
    upper_buf = []
    upper_buf_height = 0
    upper_win_cursor = [] # Upper win cursor x,y
    lower_win_cursor = 1 # Lower win cursor x (y cannot be changed!)
    fixed_font = None
    fixed_font_metrics = None
    fixed_font_width = 0
    fixed_font_height = 0
    buf = []
    width = 80
    height = 26
    cur_win = 0 # Default win is the lower (1 is for upper win)
    cur_fg = 10
    cur_bg = 2
    cur_style = 0
    max_char = 0
    start_pos = 0
    top_pos = 0
    cur_pos = 0
    input_buf = []
    _cursor_visible = False
    _ostream = None
    returnPressed = pyqtSignal(QString)
    keyPressed = pyqtSignal(int)

    def __init__(self,parent = None,flags = Qt.Widget):
        super(ZTextWidget,self).__init__(parent,flags)
        sp = QSizePolicy()
        sp.setHorizontalPolicy(QSizePolicy.Fixed)
        sp.setVerticalPolicy(QSizePolicy.Fixed)
        self.set_fixed_font("DeJa Vu Sans Mono", 9)
        self.setSizePolicy(sp)
        self.setFocusPolicy(Qt.StrongFocus)
        self._ostream = [ZStream(), ZStream(), ZStream(), ZStream()]
        self._ostream[0].selected = True
        for i in xrange(self.width *  self.height * 4):
            self.buf.append(0)

    def paintEvent(self,e):
        painter = QPainter(self)
        painter.fillRect(0, 0, self.width * self.fixed_font_width + 2, self.height * self.fixed_font_height, Qt.black)
        painter.setPen(Qt.gray)
        painter.setRenderHint(QPainter.TextAntialiasing)
        painter.setFont(self.fixed_font)
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Print main window
        l = self.height
        while (l > 0):
            c = 1
            while (c <= self.width):
                y = self.fixed_font_metrics.ascent() + (l - 1) * self.fixed_font_height
                x = 1 + ((c - 1) * self.fixed_font_width)
                #print "**",l,"**",c
                if self.buf[(((self.height - l) * self.width) + c - 1) * 4] == 0:
                    painter.setPen(self.ztoq_color(self.cur_fg))
                else:
                    painter.setPen(self.ztoq_color(self.buf[(((self.height - l) * self.width) + c - 1) * 4]))
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1] == 0:
                    painter.setBackground(QBrush(self.ztoq_color(self.cur_bg)))
                else:
                    painter.setBackground(QBrush(self.ztoq_color(self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1])))
                # Set appropriate font style
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] == 0:
                    f = painter.font()
                    f.setBold(False)
                    f.setItalic(False)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 1: # Reverse video
                    painter.setPen(self.ztoq_color(self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1]))
                    painter.setBackground(QBrush(self.ztoq_color(self.buf[(((self.height - l) * self.width) + c - 1) * 4])))
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 2: # Bold
                    f = painter.font()
                    f.setBold(True)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 4: # Italic
                    f = painter.font()
                    f.setItalic(True)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 3] <> 0:
                    painter.drawText(x,y,self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 3])
                c += 1
            l -= 1
            c = 1
        # Print upper window
        if self.upper_buf <> []:
            l = 1
            while (l <= self.upper_buf_height):
                c = 1
                while (c <= self.width):
                    y = self.fixed_font_metrics.ascent() + (l - 1) * self.fixed_font_height
                    x = 1 + ((c - 1) * self.fixed_font_width)
                    #print "**",l,"**",c
                    if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 3] <> 0:
                        painter.setPen(self.ztoq_color(self.upper_buf[(((l - 1) * self.width) + c - 1) * 4]))
                        painter.setBackground(QBrush(self.ztoq_color(self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 1])))
                        # Set appropriate font style
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] == 0:
                            f = painter.font()
                            f.setBold(False)
                            f.setItalic(False)
                            painter.setFont(f)
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 1: # Reverse video
                            painter.setPen(self.ztoq_color(self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 1]))
                            painter.setBackground(QBrush(self.ztoq_color(self.upper_buf[(((l - 1) * self.width) + c - 1) * 4])))
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 2: # Bold
                            f = painter.font()
                            f.setBold(True)
                            painter.setFont(f)
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 4: # Italic
                            f = painter.font()
                            f.setItalic(True)
                            painter.setFont(f)
                        painter.drawText(x,y,self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 3])
                    c += 1
                l += 1
        # Print cursor if visible
        if self._cursor_visible:
            self.display_cursor()

    def sizeHint(self):
        size = QSize()
        size.setWidth(self.width * self.fixed_font_width + 2)
        size.setHeight(self.height * self.fixed_font_height)
        return size

    def set_fixed_font(self,name,size):
        self.fixed_font = QFont(name, size)
        self.fixed_font.setFixedPitch(True)
        self.fixed_font.setKerning(False)
        self.fixed_font_metrics = QFontMetrics(self.fixed_font)
        self.fixed_font_width = self.fixed_font_metrics.averageCharWidth()
        self.fixed_font_height = self.fixed_font_metrics.height()
        #print self.fixed_font_width, self.fixed_font_height

    def ztoq_color(self,c):
        if c == 2:
            return Qt.black
        elif c == 3:
            return Qt.red
        elif c == 4:
            return Qt.green
        elif c == 5:
            return Qt.yellow
        elif c == 6:
            return Qt.blue
        elif c == 7:
            return Qt.magenta
        elif c == 8:
            return Qt.cyan
        elif c == 9:
            return Qt.white
        elif c == 10:
            return Qt.lightGray
        elif c == 11:
            return Qt.gray
        elif c == 12:
            return Qt.darkGray

    def set_cursor(self,x,y):
        self.upper_win_cursor = [x,y]

    def set_window(self,w):
        if w < 2:
            self.cur_win = w
        else:
            sys.exit("Unknown window {0}!?!".args(w))

    def prints(self,txt):
        if self._ostream[0].selected:
            if self.cur_win == 0: # Lower win
                # TODO: Buffering
                c = self.lower_win_cursor
                i = 0
                total = len(txt)
                #print "Total -", total
                while (i < total):
                    s = ""
                    while (i < total) and (txt[i] <> '\n') and (c <= self.width):
                        s += txt[i]
                        i += 1
                        c += 1
                    self.print_line(s)
                    #print "--> [i, c, total]", i, c, total, " ++ ", s
                    if c > self.width:
                        self.insert_new_line()
                        self.lower_win_cursor = 1
                        c = 1
                    elif (i < total) and (txt[i] == '\n'):
                        self.insert_new_line()
                        self.lower_win_cursor = 1
                        c = 1
                        i += 1
                    #elif (i == total) and (txt[i-1] <> '\n'):
                    else:
                        self.lower_win_cursor += len(s)
            else:
                i = self.upper_win_cursor[0]
                j = 0
                l = self.upper_win_cursor[1]
                #print "-", i, l, "-", txt
                #print "len upperbuf=", len(self.upper_buf)
                while (i <= self.width) and (j < len(txt)):
                    if txt[j] <> '\n':
                        self.upper_buf[(((l - 1) * self.width) + (i - 1)) * 4] = self.cur_fg
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 1] = self.cur_bg
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 2] = self.cur_style
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 3] = txt[j]
                        i += 1
                        j += 1
                    else:
                        self.upper_win_cursor = [1,l + 1]
                        i = 1
                        l += 1
                        j += 1
                self.upper_win_cursor[0] += j
            self.update()

    def print_line(self,txt):
        col = self.lower_win_cursor
        #print "Column:", col, txt
        if self.cur_win == 0: # Lower win
            for i in xrange(len(txt)):
                self.buf[(col - 1 + i) * 4] = self.cur_fg
                self.buf[((col - 1 + i) * 4) + 1] = self.cur_bg
                self.buf[((col - 1 + i) * 4) + 2] = self.cur_style
                self.buf[((col - 1 + i) * 4) + 3] = txt[i]

    def print_char(self,c):
        col = self.lower_win_cursor
        if self.cur_win == 0: # Lower win
            if c <> '\n':
                self.buf[(col - 1) * 4] = self.cur_fg
                self.buf[((col - 1) * 4) + 1] = self.cur_bg
                self.buf[((col - 1) * 4) + 2] = self.cur_style
                self.buf[((col - 1) * 4) + 3] = c
                self.lower_win_cursor += 1
            if self.lower_win_cursor > self.width: # If we exceed screen width
                #print "I insert a newline"
                self.insert_new_line()
                self.lower_win_cursor = 1
            elif c == '\n':
                self.insert_new_line()
                self.lower_win_cursor = 1
        self.update()

    def set_max_input(self,m):
        self.max_char = m

    def show_cursor(self):
        self.cur_pos = self.lower_win_cursor
        self.top_pos = self.cur_pos
        self.start_pos = self.cur_pos
        self.input_buf = []
        self._cursor_visible = True
        self.update()

    def hide_cursor(self):
        self._cursor_visible = False
        self.update()

    def display_cursor(self):
        painter = QPainter(self)
        col = self.cur_pos
        y = self.fixed_font_metrics.ascent() + ((self.height - 1) * self.fixed_font_height)
        x = 1 + ((col - 1) * self.fixed_font_width)
        painter.setPen(self.ztoq_color(self.cur_fg))
        painter.setBackground(QBrush(self.ztoq_color(self.cur_bg)))
        painter.drawText(x,y,unichr(0x2581))

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Left:
            if self.cur_pos > self.start_pos:
                self.cur_pos -= 1
                self.update()
            e.accept()
            self.keyPressed.emit(131)
        elif e.key() == Qt.Key_Right:
            if self.cur_pos < self.top_pos:
                self.cur_pos += 1
                self.update()
            e.accept()
            self.keyPressed.emit(132)
        elif e.key() == Qt.Key_Up:
            # TODO: Up in history
            e.accept()
            self.keyPressed.emit(129)
            pass
        elif e.key() == Qt.Key_Down:
            # TODO: Down in history
            e.accept()
            self.keyPressed.emit(130)
            pass
        elif e.key() == Qt.Key_Backspace:
            if self.cur_pos > self.start_pos:
                self.cur_pos -= 1
                self.top_pos -= 1
                col = self.cur_pos - 1
                for i in xrange(4):
                    self.buf[col * 4 + i] = 0
                del self.input_buf[self.cur_pos - self.start_pos]
                #print self.input_buf
                self.lower_win_cursor -= 1
                self.update()
            # self.keyPressed.emit() # No keycode available for zscii
            e.accept()
        elif e.key() == Qt.Key_Delete:
            # TODO: Fix it!
            if self.cur_pos < self.top_pos:
                self.top_pos -= 1
                col = self.cur_pos - 1
                for i in xrange(4):
                    self.buf[col * 4 + i] = 0
                del self.input_buf[self.cur_pos - self.start_pos]
                self.lower_win_cursor -= 1
                self.update()
            e.accept()
            self.keyPressed.emit(8)
        elif (e.key() == Qt.Key_Return) or (e.key() == Qt.Key_Enter):
            # TODO: Learn how to properly convert a list of chars to a string. There MUST be another way! >:-S
            text = ""
            for i in xrange(len(self.input_buf)):
                text += self.input_buf[i]
            #print text
            self.print_char('\n')
            self.hide_cursor()
            self.keyPressed.emit(13)
            self.returnPressed.emit(text)
            e.accept()
        elif ((e.key() >= Qt.Key_F1) and (e.key() <= Qt.Key_F12)):
            e.accept()
            self.keyPressed.emit(133 + e.key() - Qt.Key_F1)
        elif e.key() == Qt.Key_Escape:
            e.accept()
            self.keyPressed.emit(27)
        elif e.text().isEmpty() == False:
            #print self.cur_pos, self.start_pos, self.max_char
            if (self.cur_pos - self.start_pos) < self.max_char:
                self.cur_pos += 1
                self.top_pos += 1
                if (self.cur_pos - self.start_pos) <= len(self.input_buf):
                    self.input_buf.insert(self.cur_pos - self.start_pos - 1, unicode(e.text()))
                    #print "CurPos:", self.cur_pos
                    col = self.cur_pos - 2
                    self.buf[col * 4 + 3] = unicode(e.text())
                    self.buf[col * 4 + 2] = 0
                    self.buf[col * 4 + 1] = self.cur_bg
                    self.buf[col * 4] = self.cur_fg
                    self.lower_win_cursor += 1
                else:
                    self.input_buf.append(unicode(e.text()))
                    self.print_char(e.text())
                #print self.input_buf
                self.update()
            e.accept()
            t = ord(str(e.text()))
            if ((t > 31) and (t < 127)) or ((t > 154) and (t <252)):
                self.keyPressed.emit(t)
        else:
            e.ignore()

    def set_text_colour(self,fg):
        self.cur_fg = fg

    def set_text_background_colour(self,bg):
        self.cur_bg = bg

    def set_font_style(self,s):
        if s == 0:
            self.cur_style = 0
        else:
            self.cur_style |= s

    def clear(self):
        for i in xrange(self.width *  self.height * 4):
            self.buf[i] = 0
        self.upper_buf = []
        self.upper_buf_height = 0
        self.upper_win_cursor = [] # Upper win cursor x,y
        self.lower_win_cursor = 1 # Lower win cursor x (y cannot be changed!)
        self.cur_win = 0 # Default win is the lower (1 is for upper win)

    def split_window(self,lines,ver):
        if self.upper_buf_height > lines: # New upper win is smaller. I should copy the rest of the buffer to main buffer
            #print "Copying..."
            l = lines + 1
            while l <= self.upper_buf_height:
                for i in xrange(self.width * 4):
                    self.buf[(((self.height - l + 1) * self.width) * 4) + i] = self.upper_buf[(((l - 1) * self.width) * 4) + i]
                l += 1
        self.upper_buf_height = lines
        if (self.upper_buf == []) or (ver == 3):
            for i in xrange(self.upper_buf_height*self.width*4): # It isn't necessary to occupy that much memory but it helps to be prepared! :-P
                self.upper_buf.append(0)
        if (self.upper_win_cursor == []) or (self.upper_win_cursor[1] > lines):
            self.upper_win_cursor = [1,1]

    def select_ostream(self,n):
        if n <> 0:
            self._ostream[n - 1].selected = True

    def deselect_ostream(self,n):
        self._ostream[n - 1].selected = False

    def insert_new_line(self):
        #print "New line"
        # TODO: Not just insert new lines but also remove old unwanted ones
        for i in xrange(self.width * 4):
            self.buf.insert(0, 0)

    def read_line(self, callback):
        QObject.connect(self, SIGNAL("returnPressed(QString)"), callback)

    def disconnect_read_line(self, callback):
        QObject.disconnect(self, SIGNAL("returnPressed(QString)"), callback)

    def read_char(self, callback):
        QObject.connect(self, SIGNAL("keyPressed(int)"), callback)
        print 'Connect char'

    def disconnect_read_char(self, callback):
        QObject.disconnect(self, SIGNAL("keyPressed(int)"), callback)
        print 'Disconnect char'

    def selected_ostreams(self):
        s = []
        for i in xrange(4):
            if self._ostream[i].selected == True:
                s.append(i+1)
        return s

    def new_line(self):
        if self._ostream[0].selected:
            if self.cur_win == 0: # Lower win
                self.insert_new_line()
                self.lower_win_cursor = 1
            else: # Upper win
                l = self.upper_win_cursor[1]
                self.upper_win_cursor = [1,l + 1]
def gen_font(font_configs,
             font_type=FONT_TYPES.font01,
             img_width=1024,
             draw_outlines=False):
    img_height = HEIGHT_FACTOR

    seen_chars = []

    game_font = GameFont(width=img_width)
    painter = QPainter(game_font.trans)

    text_brush = QtGui.QBrush(QColor(255, 255, 255, 255))
    painter.setBrush(text_brush)

    outline_brush = QtGui.QBrush()
    outline_pen = QtGui.QPen(QColor(255, 0, 0, 255),
                             1,
                             style=Qt.Qt.DotLine,
                             join=Qt.Qt.MiterJoin)

    x_pos = 0
    y_pos = 0

    line_height = LINE_HEIGHT[font_type]

    for config in font_configs:
        font = QFont(config.family, config.size, config.weight, italic=False)
        font.setKerning(False)
        metric = QFontMetrics(font)

        painter.setFont(font)
        painter.setRenderHint(QPainter.TextAntialiasing, True)
        painter.setRenderHint(QPainter.Antialiasing, True)

        text_pen = painter.pen()
        text_pen.setBrush(QColor(255, 255, 255, 255))
        text_pen.setWidthF(config.pen_size)
        text_pen.setCapStyle(config.pen_cap)
        text_pen.setJoinStyle(config.pen_join)
        text_pen.setStyle(Qt.Qt.SolidLine if config.use_pen else Qt.Qt.NoPen)
        painter.setPen(text_pen)

        for char in sorted(config.chars):

            if char in seen_chars:
                continue
            else:
                seen_chars.append(char)

            # If we want a character to represent something it's not.
            char_to_print = char

            if char in config.subs:
                char_to_print = config.subs[char]

            char_w = metric.width(char_to_print)

            if x_pos + char_w > img_width:
                x_pos = 0
                y_pos += line_height + config.y_margin

            if y_pos < 0:
                y_pos = 0

            if y_pos + line_height > MAX_HEIGHT:
                _LOGGER.warning(
                    "Ran out of vertical space. Generated font does not include all characters."
                )
                break

            game_font.font_data.data.append({
                'char': char,
                'x': x_pos,
                'y': y_pos,
                'w': char_w,
                'h': line_height,
                'y_shift': config.y_shift
            })

            path = QPainterPath()
            path.addText(x_pos + config.x_offset,
                         y_pos + metric.ascent() + config.y_offset, font,
                         char_to_print)
            painter.drawPath(path)

            if draw_outlines:
                painter.setBrush(outline_brush)
                painter.setPen(outline_pen)
                painter.setRenderHint(QPainter.Antialiasing, False)

                painter.drawRect(x_pos, y_pos, char_w, line_height)

                painter.setRenderHint(QPainter.Antialiasing, True)
                painter.setBrush(text_brush)
                painter.setPen(text_pen)

            x_pos += char_w + config.x_margin

    painter.end()

    painter = QPainter(game_font.opaque)
    painter.drawImage(game_font.opaque.rect(), game_font.trans,
                      game_font.trans.rect())
    painter.end()

    # Crop our images so they only take up as much space as they need.
    final_height = int(
        math.ceil(float(y_pos + line_height) / float(HEIGHT_FACTOR)) *
        HEIGHT_FACTOR)
    game_font.trans = game_font.trans.copy(0, 0, img_width, final_height)
    game_font.opaque = game_font.opaque.copy(0, 0, img_width, final_height)

    return game_font


# if __name__ == '__main__':

# app = QtGui.QApplication(sys.argv)

# chars = load_text(CHAR_LIST)
# We can't have dupes, and why not put them in order while we're at it?
# chars = sorted(make_unique(chars))

# game_font = gen_font(chars)
# game_font.save(SAVE_AS)

### EOF ###
Beispiel #10
0
    def paintEvent(self, event):
        page_bottom = self.edit.viewport().height()
        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())
        pattern = self.pat if self.edit.lang == "python" else self.patNotPython

        painter = QPainter(self)
        background = resources.CUSTOM_SCHEME.get('sidebar-background',
            resources.COLOR_SCHEME['sidebar-background'])
        foreground = resources.CUSTOM_SCHEME.get('sidebar-foreground',
            resources.COLOR_SCHEME['sidebar-foreground'])
        painter.fillRect(self.rect(), QColor(background))

        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())
        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + \
                viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            painter.setPen(QColor(foreground))
            error = False
            checkers = sorted(self._neditable.registered_checkers,
                key=lambda x: x[2], reverse=True)
            for items in checkers:
                checker, color, _ = items
                if (line_count - 1) in checker.checks:
                    painter.setPen(QColor(color))
                    font = painter.font()
                    font.setItalic(True)
                    font.setUnderline(True)
                    painter.setFont(font)
                    error = True
                    break

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(self.width() - self.foldArea -
                    font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() +
                    font_metrics.descent() - 1,
                    str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        #Code Folding
        xofs = self.width() - self.foldArea
        painter.fillRect(xofs, 0, self.foldArea, self.height(),
                QColor(resources.CUSTOM_SCHEME.get('fold-area',
                resources.COLOR_SCHEME['fold-area'])))
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            self.calculate_docstring_block_fold()

        block = self.edit.firstVisibleBlock()
        while block.isValid():
            position = self.edit.blockBoundingGeometry(
                block).topLeft() + viewport_offset
            #Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            if pattern.match(block.text()) and block.isVisible():
                can_fold = True
                if self.patComment.match(block.text()) and \
                   (block.blockNumber() in self._endDocstringBlocks):
                    can_fold = False

                if can_fold:
                    if block.blockNumber() in self.foldedBlocks:
                        painter.drawPixmap(xofs, round(position.y()),
                            self.rightArrowIcon)
                    else:
                        painter.drawPixmap(xofs, round(position.y()),
                            self.downArrowIcon)
            #Add Bookmarks and Breakpoint
            if block.blockNumber() in self.breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 1, self.foldArea - 1)
            elif block.blockNumber() in self.bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 2, self.foldArea - 1,
                    3, 3)

            block = block.next()

        painter.end()
        QWidget.paintEvent(self, event)
Beispiel #11
0
    def paintEvent(self, event):
        page_bottom = self.edit.viewport().height()
        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())
        pattern = self.pat if self.edit.lang == "python" else self.patNotPython

        painter = QPainter(self)
        background = resources.CUSTOM_SCHEME.get('sidebar-background',
            resources.COLOR_SCHEME['sidebar-background'])
        foreground = resources.CUSTOM_SCHEME.get('sidebar-foreground',
            resources.COLOR_SCHEME['sidebar-foreground'])
        pep8color = resources.CUSTOM_SCHEME.get('pep8-underline',
            resources.COLOR_SCHEME['pep8-underline'])
        errorcolor = resources.CUSTOM_SCHEME.get('error-underline',
            resources.COLOR_SCHEME['error-underline'])
        painter.fillRect(self.rect(), QColor(background))

        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())
        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + \
                viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            error = False
            if settings.CHECK_STYLE and \
               ((line_count - 1) in self._pep8Lines):
                painter.setPen(QColor(pep8color))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.FIND_ERRORS and \
                 ((line_count - 1) in self._errorsLines):
                painter.setPen(QColor(errorcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            else:
                painter.setPen(QColor(foreground))

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(self.width() - self.foldArea -
                    font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() +
                    font_metrics.descent() - 1,
                    str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        #Code Folding
        xofs = self.width() - self.foldArea
        painter.fillRect(xofs, 0, self.foldArea, self.height(),
                QColor(resources.CUSTOM_SCHEME.get('fold-area',
                resources.COLOR_SCHEME['fold-area'])))
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

        block = self.edit.firstVisibleBlock()
        while block.isValid():
            position = self.edit.blockBoundingGeometry(
                block).topLeft() + viewport_offset
            #Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            if pattern.match(block.text()) and block.isVisible():
                if block.blockNumber() in self._foldedBlocks:
                    painter.drawPixmap(xofs, round(position.y()),
                        self.rightArrowIcon)
                else:
                    painter.drawPixmap(xofs, round(position.y()),
                        self.downArrowIcon)
            #Add Bookmarks and Breakpoint
            elif block.blockNumber() in self._breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 1, self.foldArea - 1)
            elif block.blockNumber() in self._bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 2, self.foldArea - 1,
                    3, 3)

            block = block.next()

        painter.end()
        QWidget.paintEvent(self, event)
Beispiel #12
0
    def paintEvent(self, event):
        page_bottom = self.edit.viewport().height()
        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())

        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.lightGray)

        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())
        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + \
                viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            error = False
            if settings.CHECK_STYLE and \
               ((line_count - 1) in self._pep8Lines):
                painter.setPen(Qt.darkYellow)
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.FIND_ERRORS and \
                 ((line_count - 1) in self._errorsLines):
                painter.setPen(Qt.red)
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            else:
                painter.setPen(Qt.black)

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(self.width() - self.foldArea - \
                    font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() + \
                    font_metrics.descent() - 1,
                    str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        #Code Folding
        xofs = self.width() - self.foldArea
        painter.fillRect(xofs, 0, self.foldArea, self.height(),
                QColor(resources.CUSTOM_SCHEME.get('fold-area',
                resources.COLOR_SCHEME['fold-area'])))
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

        block = self.edit.firstVisibleBlock()
        while block.isValid():
            position = self.edit.blockBoundingGeometry(
                block).topLeft() + viewport_offset
            #Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            if self.pat.match(unicode(block.text())) and block.isVisible():
                if block.blockNumber() in self._foldedBlocks:
                    painter.drawPixmap(xofs, round(position.y()),
                        self.rightArrowIcon)
                else:
                    painter.drawPixmap(xofs, round(position.y()),
                        self.downArrowIcon)
            #Add Bookmarks and Breakpoint
            elif block.blockNumber() in self._breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 1, self.foldArea - 1)
            elif block.blockNumber() in self._bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 2, self.foldArea - 1,
                    3, 3)

            block = block.next()

        painter.end()
        QWidget.paintEvent(self, event)
Beispiel #13
0
    def paintEvent(self, event):

        page_bottom = self.edit.viewport().height()

        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(self.edit.textCursor().position())

        if self._firstPaintEvent is True:
            self.jumpedUP = False
            self.strings = self.edit.toPlainText().split("\n")
            self._originalTotalLine = len(self.strings)
            self.edit.jump_to_line(len(self.strings) - 2)
        elif self.jumpedUP is False:
            self.edit.jump_to_line(1)
            self.edit.verticalScrollBar().setValue(0)
            self.jumpedUP = True
            return

        pattern = self.pat if self.edit.lang == "python" else self.patNotPython

        painter = QPainter(self)
        background = resources.CUSTOM_SCHEME.get("sidebar-background", resources.COLOR_SCHEME["sidebar-background"])
        foreground = resources.CUSTOM_SCHEME.get("sidebar-foreground", resources.COLOR_SCHEME["sidebar-foreground"])
        pep8color = resources.CUSTOM_SCHEME.get("pep8-underline", resources.COLOR_SCHEME["pep8-underline"])
        errorcolor = resources.CUSTOM_SCHEME.get("error-underline", resources.COLOR_SCHEME["error-underline"])
        migrationcolor = resources.CUSTOM_SCHEME.get(
            "migration-underline", resources.COLOR_SCHEME["migration-underline"]
        )
        painter.fillRect(self.rect(), QColor(background))

        """
        if self._firstPaintEvent is True:
            block = self.edit.document().findBlock(0)
        else:
            block = self.edit.firstVisibleBlock()
        """
        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())

        pat = re.compile("\s*#AppObject:")
        patAlexaAppImage = re.compile("\s*#AppImage:")
        patAlexaAppText = re.compile("\s*#AppText:")
        patAlexaLog = re.compile("\s*#Alexa Log")

        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            error = False
            if settings.CHECK_STYLE and ((line_count - 1) in self._pep8Lines):
                painter.setPen(QColor(pep8color))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.FIND_ERRORS and ((line_count - 1) in self._errorsLines):
                painter.setPen(QColor(errorcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.SHOW_MIGRATION_TIPS and ((line_count - 1) in self._migrationLines):
                painter.setPen(QColor(migrationcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            else:
                painter.setPen(QColor(foreground))

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(
                    self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1,
                    str(line_count),
                )

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        # Code Folding
        xofs = self.width() - self.foldArea
        painter.fillRect(
            xofs,
            0,
            self.foldArea,
            self.height(),
            QColor(resources.CUSTOM_SCHEME.get("fold-area", resources.COLOR_SCHEME["fold-area"])),
        )
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(
                QColor(resources.CUSTOM_SCHEME.get("fold-arrow", resources.COLOR_SCHEME["fold-arrow"]))
            )
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(
                QColor(resources.CUSTOM_SCHEME.get("fold-arrow", resources.COLOR_SCHEME["fold-arrow"]))
            )
            iconPainter.drawPolygon(polygon)

        if self._firstPaintEvent is True:
            block = self.edit.document().findBlock(0)
        else:
            block = self.edit.firstVisibleBlock()
        # block = self.edit.firstVisibleBlock()
        line_count = block.blockNumber()
        while block.isValid():
            # while line_count < 5000:
            line_count += 1
            position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # block.isVisible() and
            if block.isVisible() and pat.match(block.text()) and block not in self._foldedAlexaObject:
                self._fold(line_count)
                self._foldedAlexaObject.append(block)
                self._alexaObjectsPresent = True
            elif block.isVisible() and patAlexaAppImage.match(block.text()) and block not in self._foldedAlexaImage:
                self._fold(line_count)
                self._foldedAlexaImage.append(block)
                self._alexaObjectsPresent = True
            elif block.isVisible() and patAlexaAppText.match(block.text()) and block not in self._foldedAlexaText:
                self._fold(line_count)
                self._foldedAlexaText.append(block)
                self._alexaObjectsPresent = True
            elif block.isVisible() and patAlexaLog.match(block.text()) and block not in self._foldedAlexaLog:
                self._fold(line_count)
                self._foldedAlexaLog.append(block)
                self._alexaObjectsPresent = True
            elif pattern.match(block.text()) and block.isVisible():
                if block.blockNumber() in self._foldedBlocks:
                    painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon)
                else:
                    # block.setVisible(True)
                    painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon)
            # Add Bookmarks and Breakpoint
            elif block.blockNumber() in self._breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea
                )
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1)
            elif block.blockNumber() in self._bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea
                )
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3)

            block = block.next()

        block = self.edit.document().findBlock(0)
        line_count = 0
        line_hidden = 0
        while block.isValid():
            line_count += 1
            if not block.isVisible():
                line_hidden += 1
            block = block.next()
        endScrollBar = line_count - line_hidden
        self.edit.verticalScrollBar().setRange(0, endScrollBar)

        if self._firstPaintEvent is True:
            self._firstPaintEvent = False

        # self.updateAlexaAppObjCoords()
        # self.updateAlexaLogCoords()
        painter.end()

        """
        #self.edit.update()
        if self.edit.verticalScrollBar().value() != self._oldVerticalScrollbarPosition and self._alexaObjectsPresent is True:
            self._oldVerticalScrollbarPosition = self.edit.verticalScrollBar().value()
            self.updateAlexaCoords()
            self.edit.update()  # in this way we can refresh alexa icon position

        if self.edit.horizontalScrollBar().value() != self._oldHorizontalScrollbarPosition and self._alexaObjectsPresent is True:
            self._oldHorizontalScrollbarPosition = self.edit.horizontalScrollBar().value()
            self.updateAlexaCoords()
            self.edit.update()  # in this way we can refresh alexa icon position
        """

        self.strings = self.edit.toPlainText().split("\n")
        self._currentTotalLine = len(self.strings)

        if self._currentTotalLine != self._originalTotalLine:
            self._originalTotalLine = self._currentTotalLine
            self.updateAlexaCoords()
            self.edit.update()

        """
        if self._returnPressed is True:
            self._returnPressed = False
            self.updateAlexaAppObjCoords()
            self.updateAlexaLogCoords()
            self.edit.update()

        if self._backspacePressed is True:
            self._backspacePressed = False
            self.strings = self.edit.toPlainText().split('\n')
            self._currentTotalLine = len(self.strings)
            if self._currentTotalLine != self._originalTotalLine:
                self.updateAlexaAppObjCoords()
                self.updateAlexaLogCoords()
                self.edit.update()
        """

        if self.edit._alexaAppObjIconsCoords != self._oldAlexaAppObjIconsCoords:
            self._oldAlexaAppObjIconsCoords = copy.deepcopy(self.edit._alexaAppObjIconsCoords)
            self.edit.update()

        if self.edit._alexaAppImgIconsCoords != self._oldAlexaAppImgIconsCoords:
            self._oldAlexaAppImgIconsCoords = copy.deepcopy(self.edit._alexaAppImgIconsCoords)
            self.edit.update()

        if self.edit._alexaAppTextIconsCoords != self._oldAlexaAppTextIconsCoords:
            self._oldAlexaAppTextIconsCoords = copy.deepcopy(self.edit._alexaAppTextIconsCoords)
            self.edit.update()

        if self.edit._alexaLogIconsCoords != self._oldAlexaLogIconsCoords:
            self._oldAlexaLogIconsCoords = copy.deepcopy(self.edit._alexaLogIconsCoords)
            self.edit.update()

        selectedLine = self.edit.textCursor().selectedText()
        textAtCursorPos = self.edit.textCursor().block().text()

        try:
            # tmp = selectedLine.index("#   AppObject")
            if (
                pat.match(selectedLine)
                or patAlexaLog.match(selectedLine)
                or pat.match(textAtCursorPos)
                or patAlexaLog.match(textAtCursorPos)
                or patAlexaAppImage.match(selectedLine)
                or patAlexaAppImage.match(textAtCursorPos)
                or patAlexaAppText.match(selectedLine)
                or patAlexaAppText.match(textAtCursorPos)
            ) and self._keypress is True:
                self._keypress = False
                self.updateAlexaCoords()
        except:
            pass

        QWidget.paintEvent(self, event)

        """
def gen_font(font_configs, font_type = FONT_TYPES.font01, img_width = 1024, draw_outlines = False):
  img_height = HEIGHT_FACTOR
  
  seen_chars = []
  
  game_font = GameFont(width = img_width)
  painter = QPainter(game_font.trans)
  
  text_brush = QtGui.QBrush(QColor(255, 255, 255, 255))
  painter.setBrush(text_brush)
  
  outline_brush = QtGui.QBrush()
  outline_pen   = QtGui.QPen(QColor(255, 0, 0, 255), 1, style = Qt.Qt.DotLine, join = Qt.Qt.MiterJoin)
  
  x_pos = 0
  y_pos = 0
  
  line_height = LINE_HEIGHT[font_type]
  
  for config in font_configs:
    font = QFont(config.family, config.size, config.weight, italic = False)
    font.setKerning(False)
    metric = QFontMetrics(font)
    
    painter.setFont(font)
    painter.setRenderHint(QPainter.TextAntialiasing, True)
    painter.setRenderHint(QPainter.Antialiasing, True)
    
    text_pen = painter.pen()
    text_pen.setBrush(QColor(255, 255, 255, 255))
    text_pen.setWidthF(config.pen_size)
    text_pen.setCapStyle(config.pen_cap)
    text_pen.setJoinStyle(config.pen_join)
    text_pen.setStyle(Qt.Qt.SolidLine if config.use_pen else Qt.Qt.NoPen)
    painter.setPen(text_pen)
    
    for char in sorted(config.chars):
      
      if char in seen_chars:
        continue
      else:
        seen_chars.append(char)
      
      # If we want a character to represent something it's not.
      char_to_print = char
      
      if char in config.subs:
        char_to_print = config.subs[char]
      
      char_w = metric.width(char_to_print)
      
      if x_pos + char_w > img_width:
        x_pos = 0
        y_pos += line_height + config.y_margin
      
      if y_pos < 0:
        y_pos = 0
    
      if y_pos + line_height > MAX_HEIGHT:
        _LOGGER.warning("Ran out of vertical space. Generated font does not include all characters.")
        break
    
      game_font.font_data.data.append({'char': char, 'x': x_pos, 'y': y_pos, 'w': char_w, 'h': line_height, 'y_shift': config.y_shift})
      
      path = QPainterPath()
      path.addText(x_pos + config.x_offset, y_pos + metric.ascent() + config.y_offset, font, char_to_print)
      painter.drawPath(path)
      
      if draw_outlines:
        painter.setBrush(outline_brush)
        painter.setPen(outline_pen)
        painter.setRenderHint(QPainter.Antialiasing, False)
        
        painter.drawRect(x_pos, y_pos, char_w, line_height)
        
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setBrush(text_brush)
        painter.setPen(text_pen)
      
      x_pos += char_w + config.x_margin
  
  painter.end()
  
  painter = QPainter(game_font.opaque)
  painter.drawImage(game_font.opaque.rect(), game_font.trans, game_font.trans.rect())
  painter.end()
  
  # Crop our images so they only take up as much space as they need.
  final_height = int(math.ceil(float(y_pos + line_height) / float(HEIGHT_FACTOR)) * HEIGHT_FACTOR)
  game_font.trans   = game_font.trans.copy(0, 0, img_width, final_height)
  game_font.opaque  = game_font.opaque.copy(0, 0, img_width, final_height)
  
  return game_font

# if __name__ == '__main__':
  
  # app = QtGui.QApplication(sys.argv)
  
  # chars = load_text(CHAR_LIST)
  # We can't have dupes, and why not put them in order while we're at it?
  # chars = sorted(make_unique(chars))
  
  # game_font = gen_font(chars)
  # game_font.save(SAVE_AS)

### EOF ###
    def paintEvent(self, event):

        page_bottom = self.edit.viewport().height()

        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())

        if self._firstPaintEvent is True:
            self.jumpedUP = False
            self.strings = self.edit.toPlainText().split('\n')
            self._originalTotalLine = len(self.strings)
            self.edit.jump_to_line(len(self.strings) - 2)
        elif self.jumpedUP is False:
            self.edit.jump_to_line(1)
            self.edit.verticalScrollBar().setValue(0)
            self.jumpedUP = True
            return

        pattern = self.pat if self.edit.lang == "python" else self.patNotPython

        painter = QPainter(self)
        background = resources.CUSTOM_SCHEME.get(
            'sidebar-background', resources.COLOR_SCHEME['sidebar-background'])
        foreground = resources.CUSTOM_SCHEME.get(
            'sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground'])
        pep8color = resources.CUSTOM_SCHEME.get(
            'pep8-underline', resources.COLOR_SCHEME['pep8-underline'])
        errorcolor = resources.CUSTOM_SCHEME.get(
            'error-underline', resources.COLOR_SCHEME['error-underline'])
        migrationcolor = resources.CUSTOM_SCHEME.get(
            'migration-underline',
            resources.COLOR_SCHEME['migration-underline'])
        painter.fillRect(self.rect(), QColor(background))
        '''
        if self._firstPaintEvent is True:
            block = self.edit.document().findBlock(0)
        else:
            block = self.edit.firstVisibleBlock()
        '''
        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())

        pat = re.compile('\s*#.*AppObject:')
        patAlexaAppImage = re.compile('\s*#.*AppImage:')
        patAlexaAppText = re.compile('\s*#.*AppText:')
        patAlexaLog = re.compile('\s*##.*Alexa Log')

        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + \
                viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            error = False
            if settings.CHECK_STYLE and \
               ((line_count - 1) in self._pep8Lines):
                painter.setPen(QColor(pep8color))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.FIND_ERRORS and \
                 ((line_count - 1) in self._errorsLines):
                painter.setPen(QColor(errorcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.SHOW_MIGRATION_TIPS and \
                 ((line_count - 1) in self._migrationLines):
                painter.setPen(QColor(migrationcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            else:
                painter.setPen(QColor(foreground))

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(
                    self.width() - self.foldArea -
                    font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() +
                    font_metrics.descent() - 1, str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        #Code Folding
        xofs = self.width() - self.foldArea
        painter.fillRect(
            xofs, 0, self.foldArea, self.height(),
            QColor(
                resources.CUSTOM_SCHEME.get(
                    'fold-area', resources.COLOR_SCHEME['fold-area'])))
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(
                QColor(
                    resources.CUSTOM_SCHEME.get(
                        'fold-arrow', resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(
                QColor(
                    resources.CUSTOM_SCHEME.get(
                        'fold-arrow', resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

        if self._firstPaintEvent is True:
            block = self.edit.document().findBlock(0)
        else:
            block = self.edit.firstVisibleBlock()
        #block = self.edit.firstVisibleBlock()
        line_count = block.blockNumber()
        while block.isValid():
            #while line_count < 5000:
            line_count += 1
            position = self.edit.blockBoundingGeometry(
                block).topLeft() + viewport_offset
            #Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            #block.isVisible() and
            if block.isVisible() and pat.match(
                    block.text()) and block not in self._foldedAlexaObject:
                self._fold(line_count)
                self._foldedAlexaObject.append(block)
                self._alexaObjectsPresent = True
            elif block.isVisible() and patAlexaAppImage.match(
                    block.text()) and block not in self._foldedAlexaImage:
                self._fold(line_count)
                self._foldedAlexaImage.append(block)
                self._alexaObjectsPresent = True
            elif block.isVisible() and patAlexaAppText.match(
                    block.text()) and block not in self._foldedAlexaText:
                self._fold(line_count)
                self._foldedAlexaText.append(block)
                self._alexaObjectsPresent = True
            elif block.isVisible() and patAlexaLog.match(
                    block.text()) and block not in self._foldedAlexaLog:
                self._fold(line_count)
                self._foldedAlexaLog.append(block)
                self._alexaObjectsPresent = True
            elif pattern.match(block.text()) and block.isVisible():
                if block.blockNumber() in self._foldedBlocks:
                    painter.drawPixmap(xofs, round(position.y()),
                                       self.rightArrowIcon)
                else:
                    #block.setVisible(True)
                    painter.drawPixmap(xofs, round(position.y()),
                                       self.downArrowIcon)
            #Add Bookmarks and Breakpoint
            elif block.blockNumber() in self._breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()), xofs + self.foldArea,
                    round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(xofs + 1,
                                    round(position.y()) + 6, self.foldArea - 1,
                                    self.foldArea - 1)
            elif block.blockNumber() in self._bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()), xofs + self.foldArea,
                    round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(xofs + 1,
                                        round(position.y()) + 6,
                                        self.foldArea - 2, self.foldArea - 1,
                                        3, 3)

            block = block.next()

        block = self.edit.document().findBlock(0)
        line_count = 0
        line_hidden = 0
        while block.isValid():
            line_count += 1
            if not block.isVisible():
                line_hidden += 1
            block = block.next()
        endScrollBar = line_count - line_hidden
        self.edit.verticalScrollBar().setRange(0, endScrollBar)

        if self._firstPaintEvent is True:
            self._firstPaintEvent = False

        #self.updateAlexaAppObjCoords()
        #self.updateAlexaLogCoords()
        painter.end()
        '''
        #self.edit.update()
        if self.edit.verticalScrollBar().value() != self._oldVerticalScrollbarPosition and self._alexaObjectsPresent is True:
            self._oldVerticalScrollbarPosition = self.edit.verticalScrollBar().value()
            self.updateAlexaCoords()
            self.edit.update()  # in this way we can refresh alexa icon position

        if self.edit.horizontalScrollBar().value() != self._oldHorizontalScrollbarPosition and self._alexaObjectsPresent is True:
            self._oldHorizontalScrollbarPosition = self.edit.horizontalScrollBar().value()
            self.updateAlexaCoords()
            self.edit.update()  # in this way we can refresh alexa icon position
        '''

        self.strings = self.edit.toPlainText().split('\n')
        self._currentTotalLine = len(self.strings)

        if self._currentTotalLine != self._originalTotalLine:
            self._originalTotalLine = self._currentTotalLine
            self.updateAlexaCoords()
            self.edit.update()
        '''
        if self._returnPressed is True:
            self._returnPressed = False
            self.updateAlexaAppObjCoords()
            self.updateAlexaLogCoords()
            self.edit.update()

        if self._backspacePressed is True:
            self._backspacePressed = False
            self.strings = self.edit.toPlainText().split('\n')
            self._currentTotalLine = len(self.strings)
            if self._currentTotalLine != self._originalTotalLine:
                self.updateAlexaAppObjCoords()
                self.updateAlexaLogCoords()
                self.edit.update()
        '''

        if self.edit._alexaAppObjIconsCoords != self._oldAlexaAppObjIconsCoords:
            self._oldAlexaAppObjIconsCoords = copy.deepcopy(
                self.edit._alexaAppObjIconsCoords)
            self.edit.update()

        if self.edit._alexaAppImgIconsCoords != self._oldAlexaAppImgIconsCoords:
            self._oldAlexaAppImgIconsCoords = copy.deepcopy(
                self.edit._alexaAppImgIconsCoords)
            self.edit.update()

        if self.edit._alexaAppTextIconsCoords != self._oldAlexaAppTextIconsCoords:
            self._oldAlexaAppTextIconsCoords = copy.deepcopy(
                self.edit._alexaAppTextIconsCoords)
            self.edit.update()

        if self.edit._alexaLogIconsCoords != self._oldAlexaLogIconsCoords:
            self._oldAlexaLogIconsCoords = copy.deepcopy(
                self.edit._alexaLogIconsCoords)
            self.edit.update()

        selectedLine = self.edit.textCursor().selectedText()
        textAtCursorPos = self.edit.textCursor().block().text()

        try:
            #tmp = selectedLine.index("#   AppObject")
            if (pat.match(selectedLine) or patAlexaLog.match(selectedLine) or \
            pat.match(textAtCursorPos) or patAlexaLog.match(textAtCursorPos) or \
            patAlexaAppImage.match(selectedLine) or patAlexaAppImage.match(textAtCursorPos) or\
            patAlexaAppText.match(selectedLine) or patAlexaAppText.match(textAtCursorPos)) and \
            self._keypress is True:
                self._keypress = False
                self.updateAlexaCoords()
        except:
            pass

        QWidget.paintEvent(self, event)
        '''