Beispiel #1
0
 def __init__(self, parent):
     points = QPolygonF()
     self._mediator = ArrowMediator()
     for poly in (QPointF(7,0), QPointF(-7,7), QPointF(-5,2), QPointF(-11,2),
                  QPointF(-11,-2), QPointF(-5,-2), QPointF(-7,-7)):
         points.append(poly)
     QGraphicsPolygonItem.__init__(self, points, parent)
     self.setPen(Qt.darkCyan)
     self.setBrush(Qt.cyan)
Beispiel #2
0
 def _draw_polygon(self, painter, xMap, yMap, range_tuple):
     # range_tuple might contain more then four values !
     rtmin, rtmax, mzmin, mzmax = range_tuple[:4]
     points = QPolygonF()
     points.append(QPointF(xMap.transform(rtmin), yMap.transform(mzmin)))
     points.append(QPointF(xMap.transform(rtmin), yMap.transform(mzmax)))
     points.append(QPointF(xMap.transform(rtmax), yMap.transform(mzmax)))
     points.append(QPointF(xMap.transform(rtmax), yMap.transform(mzmin)))
     painter.drawPolygon(points)
     return points
Beispiel #3
0
 def _paintPolygon(self, painter, polygon):
     path = QPainterPath()
     for line in polygon:
         ring = QPolygonF()
         for point in line:
             cur = self.toCanvasCoordinates(point) - self.pos()
             ring.append(cur)
         ring.append(ring[0])
         path.addPolygon(ring)
     painter.drawPath(path)
Beispiel #4
0
 def calculate_polygon_points(self):
     # QPolygonF nesnesi oluşturup tüm köşe noktalarının
     # x ve y değerlerini hesaplıyoruz. Sonrasında x,y
     # değerleriyle QPointF nesnesi oluşturup QPolygon'a
     # bu noktaları ekliyoruz.
     p = QPolygonF()
     angle = self.calculate_angle()
     for i in range(self.edge_count):
         x = cos(angle * i) * self.radius
         y = sin(angle * i) * self.radius
         p.append(QPointF(x, y))
     return p
Beispiel #5
0
    def sample_interpolate(self, x, y):
        spline = QwtSpline()
        points = QPolygonF()

        for point in zip(x, y):
            points.append(QPointF(*point))

        spline.setSplineType(QwtSpline.Natural)
        spline.setPoints(points)

        px = range(0, 2**12, DistanceIR.DIVIDER)
        py = []

        for X in px:
            py.append(spline.value(X))

        for i in range(x[0]/DistanceIR.DIVIDER):
            py[i] = y[0]
            
        for i in range(x[-1]/DistanceIR.DIVIDER, 2**12/DistanceIR.DIVIDER):
            py[i] = y[-1]
            
        for i in range(len(py)):
            if py[i] > y[0]:
                py[i] = y[0]
            if py[i] < y[-1]:
                py[i] = y[-1]
            
        try:
            old_text = self.sample_edit.text()
            for i in range(DistanceIR.NUM_VALUES):
                value = int(round(py[i]*100))
                self.dist.set_sampling_point(i, value)
                set_value = self.dist.get_sampling_point(i)
                if set_value != value:
                    self.sample_edit.setText("Error while writing sample point " + str(i))
                    
                self.sample_edit.setText("writing sample point, value: " +  str((i, value)))
                    
                QApplication.processEvents()
            self.sample_edit.setText(old_text)
        except ip_connection.Error:
            return
Beispiel #6
0
 def __init__(self, *args):
       self.seleccionado = False
       self.velocity = random.randint(1,10)
       QGraphicsPixmapItem.__init__(self, *args)
       self.setPixmap(QPixmap("sprites/"+str(random.randint(1,45))+".png"))
       self.setTransformOriginPoint(self.boundingRect().width()/2.0,self.boundingRect().height()/2.0)
       self.setZValue(10)
       ##menu contextual
       self.menu = QMenu()
       self.Actions =[] #arreglo de acciones 
       self.Actions.append( self.menu.addAction("Seguir") )
       self.Actions.append( self.menu.addAction("Editar") )
       self.Actions.append( self.menu.addAction("girar clockwise") )
       self.Actions.append( self.menu.addAction("girar anti-clockwise") )
       self.Actions.append( self.menu.addAction("Colisiones") )
       self.Actions.append( self.menu.addAction("Duplicar") )
       self.Actions.append( self.menu.addAction("Eliminar") )
       self.menu.triggered[QAction].connect(self.test)
       ##offset para el arrastre
       self.offset= QPointF(0,0)
       ##poligono de vision
       poligono = QPolygonF()
       poligono.append(QPointF(-1,10))
       poligono.append(QPointF(-1,20))
       poligono.append(QPointF(-30,40))
       poligono.append(QPointF(-40,15))
       poligono.append(QPointF(-30,-10))
       self.vision = QGraphicsPolygonItem(poligono,self,self.scene())
       self.vision.setBrush(QColor(255, 255, 0,100))
       self.vision.setPen(QColor(255, 255, 0))
    def create_polygon_pie(self, outer_radius, inner_raduis, start, lenght):
        polygon_pie = QPolygonF()
        n = 360     # angle steps size for full circle
        # changing n value will causes drawing issues
        w = 360 / n   # angle per step
        # create outer circle line from "start"-angle to "start + lenght"-angle
        x = 0
        y = 0

        for i in range(lenght+1):                                              # add the points of polygon
            t = w * i + start - self.angle_offset
            x = outer_radius * math.cos(math.radians(t))
            y = outer_radius * math.sin(math.radians(t))
            polygon_pie.append(QPointF(x, y))
        # create inner circle line from "start + lenght"-angle to "start"-angle
        for i in range(lenght+1):                                              # add the points of polygon
            # print("2 " + str(i))
            t = w * (lenght - i) + start - self.angle_offset
            x = inner_raduis * math.cos(math.radians(t))
            y = inner_raduis * math.sin(math.radians(t))
            polygon_pie.append(QPointF(x, y))

        # close outer line
        polygon_pie.append(QPointF(x, y))
        return polygon_pie
Beispiel #8
0
 def __init__(self, *args):
     self.seleccionado = False
     self.velocity = random.randint(1, 10)
     QGraphicsPixmapItem.__init__(self, *args)
     self.setPixmap(
         QPixmap("sprites/" + str(random.randint(1, 45)) + ".png"))
     self.setTransformOriginPoint(self.boundingRect().width() / 2.0,
                                  self.boundingRect().height() / 2.0)
     self.setZValue(10)
     ##menu contextual
     self.menu = QMenu()
     self.Actions = []  #arreglo de acciones
     self.Actions.append(self.menu.addAction("Seguir"))
     self.Actions.append(self.menu.addAction("Editar"))
     self.Actions.append(self.menu.addAction("girar clockwise"))
     self.Actions.append(self.menu.addAction("girar anti-clockwise"))
     self.Actions.append(self.menu.addAction("Colisiones"))
     self.Actions.append(self.menu.addAction("Duplicar"))
     self.Actions.append(self.menu.addAction("Eliminar"))
     self.menu.triggered[QAction].connect(self.test)
     ##offset para el arrastre
     self.offset = QPointF(0, 0)
     ##poligono de vision
     poligono = QPolygonF()
     poligono.append(QPointF(-1, 10))
     poligono.append(QPointF(-1, 20))
     poligono.append(QPointF(-30, 40))
     poligono.append(QPointF(-40, 15))
     poligono.append(QPointF(-30, -10))
     self.vision = QGraphicsPolygonItem(poligono, self, self.scene())
     self.vision.setBrush(QColor(255, 255, 0, 100))
     self.vision.setPen(QColor(255, 255, 0))
Beispiel #9
0
 def item(self):
     if self.item_ is None:
         num_pts = len(self.pts_)
         if num_pts == 1:
             # draw a point          
             item = QGraphicsEllipseItem(self.pts_[0][0]-self.radius_,
                                         self.pts_[0][1]-self.radius_,
                                         2*self.radius_,
                                         2*self.radius_)
             item.setBrush(self.qcolor)
         elif num_pts == 2:
             item = QGraphicsLineItem(self.pts_[0][0], self.pts_[0][1],
                                      self.pts_[1][0], self.pts_[1][1])
         else:
             poly = QPolygonF()
             for p in self.pts_:
                 poly.append(QPointF(p[0],p[1]))
             item = QGraphicsPolygonItem(poly)
         item.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable)
         item.setPen(self.qcolor)
         item.setEnabled(True)
         item.setActive(True)
         self.item_ = item
     return self.item_
Beispiel #10
0
class _DiamondItem(QGraphicsPolygonItem):
    def __init__(self, width, height, label, color='#0000FF'):

        self.pol = QPolygonF()

        self.pol = QPolygonF()
        self.pol.append(QPointF(width / 2.0, 0))
        self.pol.append(QPointF(width, height / 2.0))
        self.pol.append(QPointF(width / 2.0, height))
        self.pol.append(QPointF(0, height / 2.0))
        self.pol.append(QPointF(width / 2.0, 0))

        self.label = label
        QGraphicsPolygonItem.__init__(self, self.pol)

        self.setBrush(QBrush(QColor(color)))
        self.setPen(QPen(QColor(color)))

    def paint(self, p, option, widget):
        super(_DiamondItem, self).paint(p, option, widget)
        ete3.treeview.faces._label_painter(self, p, option, widget)
    def create_polygon_pie(self, outer_radius, inner_raduis, start, lenght):
        """
        Args:
            outer_radius:
            inner_raduis:
            start:
            lenght:
        """
        polygon_pie = QPolygonF()
        # start = self.scale_angle_start_value
        # start = 0
        # lenght = self.scale_angle_size
        # lenght = 180
        # inner_raduis = self.width()/4
        # print(start)
        n = 360  # angle steps size for full circle
        # changing n value will causes drawing issues
        w = 360 / n  # angle per step
        # create outer circle line from "start"-angle to "start + lenght"-angle
        x = 0
        y = 0

        # todo enable/disable bar graf here
        if not self.enable_barGraph:
            # float_value = ((lenght / (self.value_max - self.value_min)) * (self.value - self.value_min))
            lenght = int(
                round((lenght / (self.value_max - self.value_min)) *
                      (self.value - self.value_min)))
            # print("f: %s, l: %s" %(float_value, lenght))
            pass

        # mymax = 0

        for i in range(lenght + 1):  # add the points of polygon
            t = w * i + start - self.angle_offset
            x = outer_radius * math.cos(math.radians(t))
            y = outer_radius * math.sin(math.radians(t))
            polygon_pie.append(QPointF(x, y))
        # create inner circle line from "start + lenght"-angle to "start"-angle
        for i in range(lenght + 1):  # add the points of polygon
            # print("2 " + str(i))
            t = w * (lenght - i) + start - self.angle_offset
            x = inner_raduis * math.cos(math.radians(t))
            y = inner_raduis * math.sin(math.radians(t))
            polygon_pie.append(QPointF(x, y))

        # close outer line
        polygon_pie.append(QPointF(x, y))
        return polygon_pie
 def setSpinBoxDownIcon(self, opacity=0.6):
     self.buttonStyle = "spinDown"
     self.setToolTip("- 1")
     pixmap = QPixmap(250, 250)
     pixmap.fill(self.backgroundColor)
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setOpacity(opacity)
     brush = QBrush(self.foregroundColor)
     painter.setBrush(brush)
     pen = QPen(self.foregroundColor)
     painter.setPen(pen)
     points = QPolygonF()
     points.append(QPointF(125.0, 200.0))
     points.append(QPointF(200.0, 70.0))
     points.append(QPointF(50.0, 70.0))
     painter.drawPolygon(points)
     painter.end()
     pixmap = pixmap.scaled(QSize(self.pixmapWidth, self.pixmapHeight),Qt.KeepAspectRatio, Qt.SmoothTransformation)
     self.setPixmap(pixmap)
    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)
        '''
Beispiel #14
0
	def __init__(self, world):

		QGraphicsPolygonItem.__init__(self)
		
		#############################
		### Build graph
		#############################

		graph = pydot.Dot()
		graph.set_node_defaults(color = 'red', fontcolor = 'red', label = '\<orphan\>')
		graph.set('overlap', 'prism')
		
		# build adjacency graph from world
		for area in world.areas:
		
			# create node for each room
			node = pydot.Node(area.id)
			node.set( 'label', area.name )
			if area == world.player.currentArea:
				node.set( 'color', 'blue' )
				node.set( 'fontcolor', 'blue' )
			else:
				node.set( 'color', 'black' )
				node.set( 'fontcolor', 'black' )

			graph.add_node(node)

			# link to adjacent rooms
			for feature in area.features:
				for action in feature.actions:
					finalEvent = None
					for event in action.events:
						if type(event) == events.PlayerMoveEvent:
							finalEvent = pydot.Edge( src=area.id, dst=event.properties['destination'] )

					if finalEvent is not None:
						graph.add_edge( finalEvent )
	
		################################
		### Generate SVG from graph
		################################

		ps = graph.create_svg(prog='neato')

		#########################################
		### Build graphics items from SVG
		#########################################

		# build xml tree
		ns = {'svg': 'http://www.w3.org/2000/svg'}
		doc = ET.fromstring(ps)

		# grab the root node properties
		rootNode = doc.xpath('/svg:svg/svg:g[1]', namespaces=ns)[0]
		polygon = rootNode.xpath('./svg:polygon', namespaces=ns)[0]
		pointStr = polygon.xpath('./@points', namespaces=ns)[0]
		penColor = QString(polygon.xpath('./@stroke', namespaces=ns)[0])
		fillColor = QString(polygon.xpath('./@fill', namespaces=ns)[0])

		# parse root polygon path
		path = QPolygonF()
		for pair in pointStr.split(' '):
			dims = pair.split(',')
			point = QPointF( float(dims[0]), float(dims[1]) )
			path.append(point)
		self.setPolygon(path)

		# fill in root node colors
		if QColor.isValidColor(penColor):
			self.setPen( QColor(penColor) )
		if QColor.isValidColor(fillColor):
			self.setBrush( QColor(fillColor) )

		# build each graph node
		for xmlNode in rootNode.xpath('./svg:g', namespaces=ns):

			group = QGraphicsRectItem(self)
			group.setPen( Qt.transparent )
			group.setBrush( Qt.transparent )


			if xmlNode.attrib['class'] == 'node':

				# find the area object
				name = xmlNode.xpath('./svg:title', namespaces=ns)[0].text
				group.setData( 0, QString(world.areas[world.areaLookup[name]].id) )
				
				# get the ellipse info
				ellipseNode = xmlNode.xpath('./svg:ellipse', namespaces=ns)[0]
				elProps = { k: float(ellipseNode.attrib[k]) for k in ['cx', 'cy', 'rx', 'ry']}
				rect = QRectF( elProps['cx']-elProps['rx'], elProps['cy']-elProps['ry'], 2*elProps['rx'], 2*elProps['ry'])
				penColor = QString(ellipseNode.attrib['stroke'])
				ellipseItem = QGraphicsEllipseItem(rect, group)
				if QColor.isValidColor(penColor):
					ellipseItem.setPen( QColor(penColor) )

				# get the text info
				textNode = xmlNode.xpath('./svg:text', namespaces=ns)[0]
				text = textNode.text
				textItem = QGraphicsTextItem(text, group)
				penColor = textNode.attrib.get('fill', 'black')
				nodePoint = QPointF(float(textNode.attrib['x']), float(textNode.attrib['y']))
				textItem.setPos( nodePoint - textItem.boundingRect().center() + QPointF(0.0,-4.0))
				if QColor.isValidColor(penColor):
					textItem.setDefaultTextColor( QColor(penColor) )

				group.setRect( ellipseItem.boundingRect() )
				group.setFlags( QGraphicsRectItem.ItemIsSelectable )

			elif xmlNode.attrib['class'] == 'edge':

 				# parse the line portion of the arrow
 				line = xmlNode.xpath('./svg:path', namespaces=ns)[0]
				path = QPainterPath()

				# pull info from xml file
				linePath = line.attrib['d']
				lineColor = line.attrib['stroke']
					
				# parse path coords
				points = re.findall( '(-?\d+\.\d+),(-?\d+\.\d+)', linePath )
				if len(points) != 4:
					continue
				startPoint = QPointF( float(points[0][0]), float(points[0][1]) )
				path.moveTo(startPoint)
				curvePoints = []
				for pointCoord in points[1:]:
					curvePoints.append( QPointF(float(pointCoord[0]), float(pointCoord[1])) )
				path.cubicTo( curvePoints[0], curvePoints[1], curvePoints[2] )

				# construct path item
				pathItem = QGraphicsPathItem(path, group)
				if QColor.isValidColor(lineColor):
					pathItem.setPen( QColor(lineColor) )

				polyNode = xmlNode.xpath('./svg:polygon', namespaces=ns)[0]

				# pull info from xml file
				pointStr = polyNode.xpath('./@points', namespaces=ns)[0]
				penColor = QString(polyNode.xpath('./@stroke', namespaces=ns)[0])
				fillColor = QString(polyNode.xpath('./@fill', namespaces=ns)[0])

				# parse polygon path
				path = QPolygonF()
				for pair in pointStr.split(' '):
					dims = pair.split(',')
					point = QPointF( float(dims[0]), float(dims[1]) )
					path.append(point)

				# construct polygon item
				polygonItem = QGraphicsPolygonItem(path, group)
				if QColor.isValidColor(penColor):
					polygonItem.setPen( QColor(penColor) )
				if QColor.isValidColor(fillColor):
					polygonItem.setBrush( QColor(fillColor) )

				group.setRect( pathItem.boundingRect() and polygonItem.boundingRect() )
Beispiel #15
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 #16
0
class Pointer(QGraphicsLineItem):
    """ QGraphicsPolygonItem to model a Pointer as an Arrow from a Pointer-Variable to its Content. """
    fgcolor = QColor(0, 0, 0)
    bgcolor = QColor(0, 0, 0)

    def __init__(self, parent, fromView, toView, distributedObjects):
        """ Constructor
        @param parent                parent for the QGraphicsPolygonItem-Constructor
        @param fromView              datagraph.htmlvariableview.HtmlVariableView, starting point of the Pointer
        @param toView                datagraph.htmlvariableview.HtmlVariableView, end point of the Pointer
        @param distributedObjects    distributedobjects.DistributedObjects, the DistributedObjects-Instance
        fromView and toView are QGraphicsWebViews
        """
        QGraphicsLineItem.__init__(self, parent)
        self.fromView = fromView
        fromView.addOutgoingPointer(self)
        self.toView = toView
        toView.addIncomingPointer(self)
        self.setPen(QPen(self.fgcolor, 1))

        self.distributedObjects = distributedObjects

        self.fromView.geometryChanged.connect(self.updatePosition)
        self.toView.geometryChanged.connect(self.updatePosition)
        self.fromView.xChanged.connect(self.updatePosition)
        self.fromView.yChanged.connect(self.updatePosition)
        self.toView.xChanged.connect(self.updatePosition)
        self.toView.yChanged.connect(self.updatePosition)
        self.fromView.removing.connect(self.delete)
        self.toView.removing.connect(self.delete)

        self.arrowhead = QPolygonF()
        self.arrowSize = 20
        self.setZValue(
            -1)  # paint the arrows behind (lower z-value) everything else

    def boundingRect(self):
        extra = (self.pen().width() + 20) / 2
        return QRectF(
            self.line().p1(),
            QSizeF(self.line().p2().x() - self.line().p1().x(),
                   self.line().p2().y() -
                   self.line().p1().y())).normalized().adjusted(
                       -extra, -extra, extra, extra)

    def shape(self):
        path = QGraphicsLineItem.shape(self)
        path.addPolygon(self.arrowhead)
        return path

    def updatePosition(self):
        line = QLineF(self.mapFromItem(self.fromView, 0, 0),
                      self.mapFromItem(self.toView, 0, 0))
        self.setLine(line)

    def paint(self, painter, _1, _2):
        """ Main-Method of the Pointer-Class <br>
            calculates/renders/draws the Lines of the Arrow
        """
        if self.fromView.collidesWithItem(self.toView):
            return

        # antialiasing makes things look nicer :)
        painter.setRenderHint(QPainter.Antialiasing)

        self.toView.x()
        pM1 = QPointF(self.fromView.x() + self.fromView.size().width() / 2,
                      self.fromView.y() + self.fromView.size().height() / 2)
        pM2 = QPointF(self.toView.x() + self.toView.size().width() / 2,
                      self.toView.y() + self.toView.size().height() / 2)
        deltaX = pM2.x() - pM1.x()
        deltaY = pM2.y() - pM1.y()
        if deltaX == 0:
            deltaX = 0.01
        if deltaY == 0:
            deltaY = 0.01
        if deltaX >= 0:
            if deltaY >= 0:
                # rechts unten
                if deltaX / deltaY >= self.fromView.size().width(
                ) / self.fromView.size().height():
                    # Start von rechter Seite
                    pStart = QPointF(
                        pM1.x() + self.fromView.size().width() / 2,
                        pM1.y() + (self.fromView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Start von unterer Seite
                    pStart = QPointF(
                        pM1.x() + (self.fromView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM1.y() + self.fromView.size().height() / 2)

                if deltaX / deltaY >= self.toView.size().width(
                ) / self.toView.size().height():
                    # Ende bei linker Seite
                    pEnd = QPointF(
                        pM2.x() - self.toView.size().width() / 2,
                        pM2.y() - (self.toView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Ende bei oberer Seite
                    pEnd = QPointF(
                        pM2.x() - (self.toView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM2.y() - self.toView.size().height() / 2)
            else:
                # rechts oben
                if deltaX / deltaY * -1 >= self.fromView.size().width(
                ) / self.fromView.size().height():
                    # Start von rechter Seite
                    pStart = QPointF(
                        pM1.x() + self.fromView.size().width() / 2,
                        pM1.y() + (self.fromView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Start von oberer Seite
                    pStart = QPointF(
                        pM1.x() - (self.fromView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM1.y() - self.fromView.size().height() / 2)

                if deltaX / deltaY * -1 >= self.toView.size().width(
                ) / self.toView.size().height():
                    # Ende bei linker Seite
                    pEnd = QPointF(
                        pM2.x() - self.toView.size().width() / 2,
                        pM2.y() - (self.toView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Ende bei unterer Seite
                    pEnd = QPointF(
                        pM2.x() + (self.toView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM2.y() + self.toView.size().height() / 2)
        else:
            if deltaY >= 0:
                # links unten
                if deltaX / deltaY * -1 >= self.fromView.size().width(
                ) / self.fromView.size().height():
                    # Start von linker Seite
                    pStart = QPointF(
                        pM1.x() - self.fromView.size().width() / 2,
                        pM1.y() - (self.fromView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Start von unterer Seite
                    pStart = QPointF(
                        pM1.x() + (self.fromView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM1.y() + self.fromView.size().height() / 2)

                if deltaX / deltaY * -1 >= self.toView.size().width(
                ) / self.toView.size().height():
                    # Ende bei rechten Seite
                    pEnd = QPointF(
                        pM2.x() + self.toView.size().width() / 2,
                        pM2.y() + (self.toView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Ende bei oberer Seite
                    pEnd = QPointF(
                        pM2.x() - (self.toView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM2.y() - self.toView.size().height() / 2)
            else:
                # links oben
                if deltaX / deltaY >= self.fromView.size().width(
                ) / self.fromView.size().height():
                    # Start von linker Seite
                    pStart = QPointF(
                        pM1.x() - self.fromView.size().width() / 2,
                        pM1.y() - (self.fromView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Start von oberer Seite
                    pStart = QPointF(
                        pM1.x() - (self.fromView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM1.y() - self.fromView.size().height() / 2)

                if deltaX / deltaY >= self.toView.size().width(
                ) / self.toView.size().height():
                    # Ende bei rechter Seite
                    pEnd = QPointF(
                        pM2.x() + self.toView.size().width() / 2,
                        pM2.y() + (self.toView.size().width() / 2) *
                        (deltaY / deltaX))
                else:
                    # Ende bei unterer Seite
                    pEnd = QPointF(
                        pM2.x() + (self.toView.size().height() / 2) *
                        (deltaX / deltaY),
                        pM2.y() + self.toView.size().height() / 2)

        self.setLine(QLineF(pEnd, pStart))

        if self.line().length() != 0:
            angle = math.acos(self.line().dx() / self.line().length())
            if self.line().dy() >= 0:
                angle = math.pi * 2 - angle

            arrowP1 = self.line().p1() + QPointF(
                math.sin(angle + math.pi / 2.5) * self.arrowSize,
                math.cos(angle + math.pi / 2.5) * self.arrowSize)
            arrowP2 = self.line().p1() + QPointF(
                math.sin(angle + math.pi - math.pi / 2.5) * self.arrowSize,
                math.cos(angle + math.pi - math.pi / 2.5) * self.arrowSize)
            self.arrowhead.clear()
            self.arrowhead.append(self.line().p1())
            self.arrowhead.append(arrowP1)
            self.arrowhead.append(arrowP2)
            painter.setBrush(QBrush(self.bgcolor))
            painter.drawLine(self.line())
            painter.drawPolygon(self.arrowhead)

    def delete(self):
        """ removes the pointer from the DataGraph """
        self.toView.incomingPointers.remove(self)
        self.fromView.outgoingPointers.remove(self)
        self.distributedObjects.datagraphController.removePointer(self)

    def setX(self, _):
        logging.error("Ignoring setting our Pointer's x position")

    def setY(self, _):
        logging.error("Ignoring setting our Pointer's y position")
Beispiel #17
0
class Pointer(QGraphicsLineItem):
    """ QGraphicsPolygonItem to model a Pointer as an Arrow from a Pointer-Variable to its Content. """
    fgcolor = QColor(0, 0, 0)
    bgcolor = QColor(0, 0, 0)

    def __init__(self, parent, fromView, toView, distributedObjects):
        """ Constructor
        @param parent                parent for the QGraphicsPolygonItem-Constructor
        @param fromView              datagraph.htmlvariableview.HtmlVariableView, starting point of the Pointer
        @param toView                datagraph.htmlvariableview.HtmlVariableView, end point of the Pointer
        @param distributedObjects    distributedobjects.DistributedObjects, the DistributedObjects-Instance
        fromView and toView are QGraphicsWebViews
        """
        QGraphicsLineItem.__init__(self, parent)
        self.fromView = fromView
        fromView.addOutgoingPointer(self)
        self.toView = toView
        toView.addIncomingPointer(self)
        #self.setBrush( QBrush( self.bgcolor  ) )
        self.setPen(QPen(self.fgcolor, 1))

        self.distributedObjects = distributedObjects

        QObject.connect(self.fromView, SIGNAL('geometryChanged()'), self.updatePosition)
        QObject.connect(self.toView, SIGNAL('geometryChanged()'), self.updatePosition)
        QObject.connect(self.fromView, SIGNAL('xChanged()'), self.updatePosition)
        QObject.connect(self.fromView, SIGNAL('yChanged()'), self.updatePosition)
        QObject.connect(self.toView, SIGNAL('xChanged()'), self.updatePosition)
        QObject.connect(self.toView, SIGNAL('yChanged()'), self.updatePosition)
        QObject.connect(self.fromView, SIGNAL('removing()'), self.delete)
        QObject.connect(self.toView, SIGNAL('removing()'), self.delete)

        self.arrowhead = QPolygonF()
        self.arrowSize = 20
        self.setZValue(-1)  # paint the arrows behind (lower z-value) everything else

    def boundingRect(self):
        extra = (self.pen().width() + 20) / 2
        return QRectF(self.line().p1(), QSizeF(self.line().p2().x() - self.line().p1().x(),
                                               self.line().p2().y() - self.line().p1().y())).normalized().adjusted(-extra, -extra, extra, extra)

    def shape(self):
        path = QGraphicsLineItem.shape(self)
        path.addPolygon(self.arrowhead)
        return path

    def updatePosition(self):
        line = QLineF(self.mapFromItem(self.fromView, 0, 0), self.mapFromItem(self.toView, 0, 0))
        self.setLine(line)

    def paint(self, painter, _1, _2):
        """ Main-Method of the Pointer-Class <br>
            calculates/renders/draws the Lines of the Arrow
        """
        if self.fromView.collidesWithItem(self.toView):
            return

        # antialiasing makes things look nicer :)
        painter.setRenderHint(QPainter.Antialiasing)

        self.toView.x()
        pM1 = QPointF(self.fromView.x() + self.fromView.size().width() / 2,
                      self.fromView.y() + self.fromView.size().height() / 2)
        pM2 = QPointF(self.toView.x() + self.toView.size().width() / 2,
                      self.toView.y() + self.toView.size().height() / 2)
        deltaX = pM2.x() - pM1.x()
        deltaY = pM2.y() - pM1.y()
        if deltaX == 0:
            deltaX = 0.01
        if deltaY == 0:
            deltaY = 0.01
        if deltaX >= 0:
            if deltaY >= 0:
                # rechts unten
                if deltaX / deltaY >= self.fromView.size().width() / self.fromView.size().height():
                    # Start von rechter Seite
                    pStart = QPointF(pM1.x() + self.fromView.size().width() / 2,
                                     pM1.y() + (self.fromView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Start von unterer Seite
                    pStart = QPointF(pM1.x() + (self.fromView.size().height() / 2) * (deltaX / deltaY),
                                     pM1.y() + self.fromView.size().height() / 2)

                if deltaX / deltaY >= self.toView.size().width() / self.toView.size().height():
                    # Ende bei linker Seite
                    pEnd = QPointF(pM2.x() - self.toView.size().width() / 2,
                                   pM2.y() - (self.toView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Ende bei oberer Seite
                    pEnd = QPointF(pM2.x() - (self.toView.size().height() / 2) * (deltaX / deltaY),
                                   pM2.y() - self.toView.size().height() / 2)
            else:
                # rechts oben
                if deltaX / deltaY * -1 >= self.fromView.size().width() / self.fromView.size().height():
                    # Start von rechter Seite
                    pStart = QPointF(pM1.x() + self.fromView.size().width() / 2,
                                     pM1.y() + (self.fromView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Start von oberer Seite
                    pStart = QPointF(pM1.x() - (self.fromView.size().height() / 2) * (deltaX / deltaY),
                                     pM1.y() - self.fromView.size().height() / 2)

                if deltaX / deltaY * -1 >= self.toView.size().width() / self.toView.size().height():
                    # Ende bei linker Seite
                    pEnd = QPointF(pM2.x() - self.toView.size().width() / 2,
                                   pM2.y() - (self.toView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Ende bei unterer Seite
                    pEnd = QPointF(pM2.x() + (self.toView.size().height() / 2) * (deltaX / deltaY),
                                   pM2.y() + self.toView.size().height() / 2)
        else:
            if deltaY >= 0:
                # links unten
                if deltaX / deltaY * -1 >= self.fromView.size().width() / self.fromView.size().height():
                    # Start von linker Seite
                    pStart = QPointF(pM1.x() - self.fromView.size().width() / 2,
                                     pM1.y() - (self.fromView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Start von unterer Seite
                    pStart = QPointF(pM1.x() + (self.fromView.size().height() / 2) * (deltaX / deltaY),
                                     pM1.y() + self.fromView.size().height() / 2)

                if deltaX / deltaY * -1 >= self.toView.size().width() / self.toView.size().height():
                    # Ende bei rechten Seite
                    pEnd = QPointF(pM2.x() + self.toView.size().width() / 2,
                                   pM2.y() + (self.toView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Ende bei oberer Seite
                    pEnd = QPointF(pM2.x() - (self.toView.size().height() / 2) * (deltaX / deltaY),
                                   pM2.y() - self.toView.size().height() / 2)
            else:
                # links oben
                if deltaX / deltaY >= self.fromView.size().width() / self.fromView.size().height():
                    # Start von linker Seite
                    pStart = QPointF(pM1.x() - self.fromView.size().width() / 2,
                                     pM1.y() - (self.fromView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Start von oberer Seite
                    pStart = QPointF(pM1.x() - (self.fromView.size().height() / 2) * (deltaX / deltaY),
                                     pM1.y() - self.fromView.size().height() / 2)

                if deltaX / deltaY >= self.toView.size().width() / self.toView.size().height():
                    # Ende bei rechter Seite
                    pEnd = QPointF(pM2.x() + self.toView.size().width() / 2,
                                   pM2.y() + (self.toView.size().width() / 2) * (deltaY / deltaX))
                else:
                    # Ende bei unterer Seite
                    pEnd = QPointF(pM2.x() + (self.toView.size().height() / 2) * (deltaX / deltaY),
                                   pM2.y() + self.toView.size().height() / 2)

        self.setLine(QLineF(pEnd, pStart))

        if self.line().length() != 0:
            angle = math.acos(self.line().dx() / self.line().length())
            if self.line().dy() >= 0:
                angle = math.pi * 2 - angle

            arrowP1 = self.line().p1() + QPointF(math.sin(angle + math.pi / 2.5) * self.arrowSize, math.cos(angle + math.pi / 2.5) * self.arrowSize)
            arrowP2 = self.line().p1() + QPointF(math.sin(angle + math.pi - math.pi / 2.5) * self.arrowSize, math.cos(angle + math.pi - math.pi / 2.5) * self.arrowSize)
            self.arrowhead.clear()
            self.arrowhead.append(self.line().p1())
            self.arrowhead.append(arrowP1)
            self.arrowhead.append(arrowP2)
            painter.setBrush(QBrush(self.bgcolor))
            painter.drawLine(self.line())
            painter.drawPolygon(self.arrowhead)

    def delete(self):
        """ removes the pointer from the DataGraph """
        self.toView.incomingPointers.remove(self)
        self.fromView.outgoingPointers.remove(self)
        self.distributedObjects.datagraphController.removePointer(self)

    def setX(self, _):
        logging.error("Ignoring setting our Pointer's x position")

    def setY(self, _):
        logging.error("Ignoring setting our Pointer's y position")
Beispiel #18
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 #19
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)

        """
Beispiel #20
0
from itertools import product

baseWidth = styles.PATH_BASE_WIDTH
ppL5 = QPainterPath()  # Left 5' PainterPath
ppR5 = QPainterPath()  # Right 5' PainterPath
ppL3 = QPainterPath()  # Left 3' PainterPath
ppR3 = QPainterPath()  # Right 3' PainterPath
# set up ppL5 (left 5' blue square)
ppL5.addRect(0.25 * baseWidth, 0.125 * baseWidth,\
             0.75 * baseWidth, 0.75 * baseWidth)
# set up ppR5 (right 5' blue square)
ppR5.addRect(0, 0.125 * baseWidth,\
             0.75 * baseWidth, 0.75 * baseWidth)
# set up ppL3 (left 3' blue triangle)
l3poly = QPolygonF()
l3poly.append(QPointF(baseWidth, 0))
l3poly.append(QPointF(0.25 * baseWidth, 0.5 * baseWidth))
l3poly.append(QPointF(baseWidth, baseWidth))
ppL3.addPolygon(l3poly)
# set up ppR3 (right 3' blue triangle)
r3poly = QPolygonF()
r3poly.append(QPointF(0, 0))
r3poly.append(QPointF(0.75 * baseWidth, 0.5 * baseWidth))
r3poly.append(QPointF(0, baseWidth))
ppR3.addPolygon(r3poly)


class PathHelix(QGraphicsItem):
    """
    PathHelix is the primary "view" of the VirtualHelix data.
    It manages the ui interactions from the user, such as
Beispiel #21
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        width = self.width()
        height = self.height()

        if self.dynamic_resize:
            knob_radius = self.dynamic_knob_radius
        else:
            knob_radius = self.knob_radius

        # ensure that the center point is in the middle of a pixel to ensure
        # that exact vertial and horizantal ticks are drawn exactly 1px wide
        x = math.floor(width / 2.0) + 0.5
        y = math.floor(height / 2.0) + 0.5

        if DEBUG:
            painter.fillRect(0, 0, width, height, Qt.yellow)

        painter.translate(x, y)

        if self.knob_style == KnobWidget.STYLE_NEEDLE:
            r = min(x, y) - 1

            painter.setPen(Qt.white)
            painter.setBrush(Qt.white)
            painter.drawEllipse(QPoint(0, 0), r, r)

        angle = self.value_factor * self.total_angle - (self.total_angle / 2.0)

        # draw base knob or needle spike
        if self.knob_style == KnobWidget.STYLE_ROUND:
            painter.setPen(self.border_color)

            if self.pressed:
                gradient = QRadialGradient(0, 0, knob_radius)
                gradient.setColorAt(0, self.base_color_pressed)
                gradient.setColorAt(0.85, self.base_color)
                gradient.setColorAt(1, self.base_color)

                painter.setBrush(gradient)
            else:
                painter.setBrush(self.base_color)

            painter.drawEllipse(QPoint(0, 0), knob_radius, knob_radius)
        elif self.knob_style == KnobWidget.STYLE_NEEDLE:
            painter.save()
            painter.rotate(angle)
            painter.setPen(self.needle_color)
            painter.setBrush(self.needle_color)

            needle = QPolygonF()
            needle.append(QPointF(self.needle_base_radius * 0.6, 0))
            needle.append(QPointF(0, -knob_radius))
            needle.append(QPointF(-self.needle_base_radius * 0.6, 0))

            painter.drawPolygon(needle)
            painter.restore()

        # draw knob mark or needle base
        if self.knob_style == KnobWidget.STYLE_ROUND:
            painter.save()
            painter.rotate(angle)
            painter.setPen(QPen(self.mark_color, 2))
            painter.drawLine(0, -knob_radius * 0.4, 0, -knob_radius * 0.8)
            painter.restore()
        elif self.knob_style == KnobWidget.STYLE_NEEDLE:
            painter.setPen(self.border_color)
            painter.setBrush(self.base_color)
            painter.drawEllipse(QPoint(0, 0), self.needle_base_radius, self.needle_base_radius)

        if self.scale_visible:
            painter.setPen(Qt.black)

            # draw scale arc
            if self.scale_arc_visible:
                painter.drawArc(-knob_radius - self.knob_to_scale,
                                -knob_radius - self.knob_to_scale,
                                knob_radius * 2 + self.knob_to_scale * 2,
                                knob_radius * 2 + self.knob_to_scale * 2,
                                (90 + self.total_angle / 2) * 16, -self.total_angle * 16)

            # draw scale ticks
            def value_to_angle(value):
                return (float(value - self.minimum_value) / self.value_range) * self.total_angle - (self.total_angle / 2.0)

            value = self.minimum_value

            while value <= self.maximum_value:
                angle = value_to_angle(value)

                painter.save()
                painter.rotate(value_to_angle(value))
                painter.drawLine(0, -knob_radius - self.knob_to_scale,
                                 0, -knob_radius - self.knob_to_scale - self.tick_size_large)

                if self.scale_text_visible:
                    p = painter.worldTransform().map(QPoint(0, -knob_radius - \
                                                               self.knob_to_scale - \
                                                               self.tick_size_large - \
                                                               self.tick_to_text - \
                                                               self.text_radius))

                painter.restore()

                if self.scale_text_visible:
                    if DEBUG:
                        painter.save()
                        painter.setPen(QColor(255, 0, 0, 50))
                        painter.setBrush(QColor(255, 0, 0, 50))
                        painter.drawEllipse(QPoint(p.x() - x, p.y() - y),
                                            self.text_radius, self.text_radius)
                        painter.restore()

                    painter.drawText(p.x() - x - 30, p.y() - y - 30, 60, 60,
                                     Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter,
                                     str(value))

                for i in range(1, self.scale_step_divisions):
                    sub_value = value + (float(self.scale_step_size) * i) / self.scale_step_divisions

                    if sub_value > self.maximum_value:
                        break

                    painter.save()
                    painter.rotate(value_to_angle(sub_value))
                    painter.drawLine(0, -knob_radius - self.knob_to_scale,
                                     0, -knob_radius - self.knob_to_scale - self.tick_size_small)
                    painter.restore()

                value += self.scale_step_size

        if self.title_text != None:
            painter.drawText(-knob_radius, knob_radius - 30,
                             knob_radius * 2, 60,
                             Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter,
                             self.title_text)
Beispiel #22
0
def calcArrow(srcdes_list,itemignoreZooming,iconScale):
    ''' if PoolItem then boundingrect should be background rather than graphicsobject '''
    src = srcdes_list[0]
    des = srcdes_list[1]
    endtype = srcdes_list[2]
    order = srcdes_list[3]
    # print("Source => ", src)
    compartment = src.parentItem()
    srcobj = src.gobj
    desobj = des.gobj
    if isinstance(src,PoolItem):
        srcobj = src.bg
    if isinstance(des,PoolItem):
        desobj = des.bg
            
    # if itemignoreZooming:
    #     srcRect = self.recalcSceneBoundingRect(srcobj)
    #     desRect = self.recalcSceneBoundingRect(desobj)
    # else:
    srcRect = compartment.mapFromScene(srcobj.sceneBoundingRect()).boundingRect()
    desRect = compartment.mapFromScene(desobj.sceneBoundingRect()).boundingRect()
    arrow = QPolygonF()
    if srcRect.intersects(desRect):                
        ''' This is created for getting a emptyline reference \
            because 'lineCord' function keeps a reference between qgraphicsline and its src and des
        '''
        arrow.append(QPointF(0,0))
        arrow.append(QPointF(0,0))
        return arrow
    if (order == 0):
        tmpLine = QLineF(srcRect.center().x(),
                                srcRect.center().y(),
                                desRect.center().x(),
                                desRect.center().y())
    elif(order > 0):
        dx = desRect.center().x()- srcRect.center().x()
        dy = desRect.center().y()- srcRect.center().y()
        dx0 = dy
        dy0 = -dx
        tetha1 = (math.atan2(dy0,dx0))
        a0 = 4 *(math.cos(tetha1))
        b0 = 4 *(math.sin(tetha1))
        ''' Higher order ( > 4) connectivity will not be done'''
        if ((order == 3) or (order == 4)):
            a0 = a0*2
            b0 = b0*2
        if(order %2 == 0):
            srcCentera0 = srcRect.center().x()-a0
            srcCenterb0 = srcRect.center().y()-b0
            desCentera0 = desRect.center().x()-a0
            desCenterb0 = desRect.center().y()-b0
        else:
            srcCentera0 = srcRect.center().x()+a0
            srcCenterb0 = srcRect.center().y()+b0
            desCentera0 = desRect.center().x()+a0
            desCenterb0 = desRect.center().y()+b0
        pointa = QPointF(srcCentera0,srcCenterb0)
        pointb = QPointF(desCentera0,desCenterb0)
        tmpLine = QLineF(srcCentera0,srcCenterb0,desCentera0,desCenterb0)

    srcIntersects, lineSrcPoint = calcLineRectIntersection(srcRect, tmpLine)
    destIntersects, lineDestPoint = calcLineRectIntersection(desRect, tmpLine)

    if not srcIntersects:
        print 'Source does not intersect line. Arrow points:',lineSrcPoint,src.mobj.name, src.mobj.className
    if not destIntersects:
        print 'Dest does not intersect line. Arrow points:', lineDestPoint,  des.mobj.name, des.mobj.className

    '''src and des are connected with line co-ordinates
       Arrow head is drawned if the distance between src and des line is >8 just for clean appeareance
    '''
    if (abs(lineSrcPoint.x()-lineDestPoint.x()) > 8 or abs(lineSrcPoint.y()-lineDestPoint.y())>8):
        srcAngle = tmpLine.angle()
        if endtype == 'p' or endtype == 'stp':
            ''' Arrow head for Destination is calculated'''
            arrow.append(lineSrcPoint)
            arrow.append(lineDestPoint)
            degree = -60
            srcXArr1,srcYArr1= arrowHead(srcAngle,degree,lineDestPoint,iconScale)
            arrow.append(QPointF(srcXArr1,srcYArr1))
            arrow.append(QPointF(lineDestPoint.x(),lineDestPoint.y()))
                
            degree = -120
            srcXArr2,srcYArr2 = arrowHead(srcAngle,degree,lineDestPoint,iconScale)
            arrow.append(QPointF(srcXArr2,srcYArr2))                    
            arrow.append(QPointF(lineDestPoint.x(),lineDestPoint.y()))
 
        elif endtype == 'st':
            ''' Arrow head for Source is calculated'''
            arrow.append(lineDestPoint)
            arrow.append(lineSrcPoint)
            degree = 60
            srcXArr2,srcYArr2 = arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr2,srcYArr2))                    
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))

            degree = 120
            srcXArr1,srcYArr1= arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr1,srcYArr1))
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))

        elif endtype == 's' or endtype == 'sts':
            arrow.append(lineDestPoint)
            arrow.append(lineSrcPoint)
            
            degree = 60
            srcXArr2,srcYArr2 = arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr2,srcYArr2))                    
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))

            degree = 120
            srcXArr1,srcYArr1= arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr1,srcYArr1))
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))
        else:
            arrow.append(lineSrcPoint)
            arrow.append(lineDestPoint)
    return arrow
Beispiel #23
0
def calcArrow(srcdes_list,itemignoreZooming,iconScale):
    ''' if PoolItem then boundingrect should be background rather than graphicsobject '''
    src = srcdes_list[0]
    des = srcdes_list[1]
    endtype = srcdes_list[2]
    order = srcdes_list[3]
    # print("Source => ", src)
    compartment = src.parentItem()
    srcobj = src.gobj
    desobj = des.gobj
    if isinstance(src,PoolItem):
        srcobj = src.bg
    if isinstance(des,PoolItem):
        desobj = des.bg
            
    # if itemignoreZooming:
    #     srcRect = self.recalcSceneBoundingRect(srcobj)
    #     desRect = self.recalcSceneBoundingRect(desobj)
    # else:
    srcRect = compartment.mapFromScene(srcobj.sceneBoundingRect()).boundingRect()
    desRect = compartment.mapFromScene(desobj.sceneBoundingRect()).boundingRect()
    arrow = QPolygonF()
    if srcRect.intersects(desRect):                
        ''' This is created for getting a emptyline reference \
            because 'lineCord' function keeps a reference between qgraphicsline and its src and des
        '''
        arrow.append(QPointF(0,0))
        arrow.append(QPointF(0,0))
        return arrow
    if (order == 0):
        tmpLine = QLineF(srcRect.center().x(),
                                srcRect.center().y(),
                                desRect.center().x(),
                                desRect.center().y())
    elif(order > 0):
        dx = desRect.center().x()- srcRect.center().x()
        dy = desRect.center().y()- srcRect.center().y()
        dx0 = dy
        dy0 = -dx
        tetha1 = (atan2(dy0,dx0))
        a0 = 4 *(cos(tetha1))
        b0 = 4 *(sin(tetha1))
        ''' Higher order ( > 4) connectivity will not be done'''
        if ((order == 3) or (order == 4)):
            a0 = a0*2
            b0 = b0*2
        if(order %2 == 0):
            srcCentera0 = srcRect.center().x()-a0
            srcCenterb0 = srcRect.center().y()-b0
            desCentera0 = desRect.center().x()-a0
            desCenterb0 = desRect.center().y()-b0
        else:
            srcCentera0 = srcRect.center().x()+a0
            srcCenterb0 = srcRect.center().y()+b0
            desCentera0 = desRect.center().x()+a0
            desCenterb0 = desRect.center().y()+b0
        pointa = QPointF(srcCentera0,srcCenterb0)
        pointb = QPointF(desCentera0,desCenterb0)
        tmpLine = QLineF(srcCentera0,srcCenterb0,desCentera0,desCenterb0)

    srcIntersects, lineSrcPoint = calcLineRectIntersection(srcRect, tmpLine)
    destIntersects, lineDestPoint = calcLineRectIntersection(desRect, tmpLine)

    if not srcIntersects:
        print 'Source does not intersect line. Arrow points:',lineSrcPoint,src.mobj.name, src.mobj.className
    if not destIntersects:
        print 'Dest does not intersect line. Arrow points:', lineDestPoint,  des.mobj.name, des.mobj.className

    '''src and des are connected with line co-ordinates
       Arrow head is drawned if the distance between src and des line is >8 just for clean appeareance
    '''
    if (abs(lineSrcPoint.x()-lineDestPoint.x()) > 8 or abs(lineSrcPoint.y()-lineDestPoint.y())>8):
        srcAngle = tmpLine.angle()
        if endtype == 'p' or endtype == 'stp':
            ''' Arrow head for Destination is calculated'''
            arrow.append(lineSrcPoint)
            arrow.append(lineDestPoint)
            degree = -60
            srcXArr1,srcYArr1= arrowHead(srcAngle,degree,lineDestPoint,iconScale)
            arrow.append(QPointF(srcXArr1,srcYArr1))
            arrow.append(QPointF(lineDestPoint.x(),lineDestPoint.y()))
                
            degree = -120
            srcXArr2,srcYArr2 = arrowHead(srcAngle,degree,lineDestPoint,iconScale)
            arrow.append(QPointF(srcXArr2,srcYArr2))                    
            arrow.append(QPointF(lineDestPoint.x(),lineDestPoint.y()))
 
        elif endtype == 'st':
            ''' Arrow head for Source is calculated'''
            arrow.append(lineDestPoint)
            arrow.append(lineSrcPoint)
            degree = 60
            srcXArr2,srcYArr2 = arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr2,srcYArr2))                    
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))

            degree = 120
            srcXArr1,srcYArr1= arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr1,srcYArr1))
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))

        elif endtype == 's' or endtype == 'sts':
            arrow.append(lineDestPoint)
            arrow.append(lineSrcPoint)
            
            degree = 60
            srcXArr2,srcYArr2 = arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr2,srcYArr2))                    
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))

            degree = 120
            srcXArr1,srcYArr1= arrowHead(srcAngle,degree,lineSrcPoint,iconScale)
            arrow.append(QPointF(srcXArr1,srcYArr1))
            arrow.append(QPointF(lineSrcPoint.x(),lineSrcPoint.y()))
        else:
            arrow.append(lineSrcPoint)
            arrow.append(lineDestPoint)
    return arrow
 def drawPolygon(self, Polygon):
     """Draw a polygon on the canvas"""
     polygon = QPolygonF()
     for point in Polygon:
         polygon.append(QPointF(point[0], point[1]))
     self.canvasScene.addPolygon(polygon, self.pen)
Beispiel #25
0
 def _paintLine(self, painter, line):
     polyline = QPolygonF()
     for point in line:
         polyline.append(self.toCanvasCoordinates(point) - self.pos())
     painter.drawPolyline(polyline)
Beispiel #26
0
 def render(self):
     """ Main-Method of the Pointer-Class <br>
         calculates/renders/draws the Lines of the Arrow
     """
     points = QPolygonF()
     self.toView.x()
     pM1 = QPointF(self.fromView.x() + self.fromView.size().width()/2,
                   self.fromView.y() + self.fromView.size().height()/2)
     pM2 = QPointF(self.toView.x() + self.toView.size().width()/2,
                   self.toView.y() + self.toView.size().height()/2)
     deltaX = pM2.x()-pM1.x()
     deltaY = pM2.y()-pM1.y()
     if deltaX == 0:
         deltaX = 0.01 
     if deltaY == 0:
         deltaY = 0.01
     if deltaX >= 0:
         if deltaY >= 0:
             # rechts unten
             if deltaX/deltaY >= self.fromView.size().width()/self.fromView.size().height():
                 # Start von rechter Seite
                 pStart = QPointF(pM1.x() + self.fromView.size().width()/2,
                                  pM1.y() + (self.fromView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Start von unterer Seite
                 pStart = QPointF(pM1.x() + (self.fromView.size().height()/2)*(deltaX/deltaY),
                                  pM1.y() + self.fromView.size().height()/2)
             
             if deltaX/deltaY >= self.toView.size().width()/self.toView.size().height():
                 # Ende bei linker Seite
                 pEnd = QPointF(pM2.x() - self.toView.size().width()/2,
                                pM2.y() - (self.toView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Ende bei oberer Seite
                 pEnd = QPointF(pM2.x() - (self.toView.size().height()/2)*(deltaX/deltaY),
                                pM2.y() - self.toView.size().height()/2)
         else:
             # rechts oben
             if deltaX/deltaY*-1 >= self.fromView.size().width()/self.fromView.size().height():
                 # Start von rechter Seite
                 pStart = QPointF(pM1.x() + self.fromView.size().width()/2,
                                  pM1.y() + (self.fromView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Start von oberer Seite
                 pStart = QPointF(pM1.x() - (self.fromView.size().height()/2)*(deltaX/deltaY),
                                  pM1.y() - self.fromView.size().height()/2)
             
             if deltaX/deltaY*-1 >= self.toView.size().width()/self.toView.size().height():
                 # Ende bei linker Seite
                 pEnd = QPointF(pM2.x() - self.toView.size().width()/2,
                                pM2.y() - (self.toView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Ende bei unterer Seite
                 pEnd = QPointF(pM2.x() + (self.toView.size().height()/2)*(deltaX/deltaY),
                                pM2.y() + self.toView.size().height()/2)
     else:
         if deltaY >= 0:
             # links unten
             if deltaX/deltaY*-1 >= self.fromView.size().width()/self.fromView.size().height():
                 # Start von linker Seite
                 pStart = QPointF(pM1.x() - self.fromView.size().width()/2,
                                  pM1.y() - (self.fromView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Start von unterer Seite
                 pStart = QPointF(pM1.x() + (self.fromView.size().height()/2)*(deltaX/deltaY),
                                  pM1.y() + self.fromView.size().height()/2)
             
             if deltaX/deltaY*-1 >= self.toView.size().width()/self.toView.size().height():
                 # Ende bei rechten Seite
                 pEnd = QPointF(pM2.x() + self.toView.size().width()/2,
                                pM2.y() + (self.toView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Ende bei oberer Seite
                 pEnd = QPointF(pM2.x() - (self.toView.size().height()/2)*(deltaX/deltaY),
                                pM2.y() - self.toView.size().height()/2)
         else:
             # links oben
             if deltaX/deltaY >= self.fromView.size().width()/self.fromView.size().height():
                 # Start von linker Seite
                 pStart = QPointF(pM1.x() - self.fromView.size().width()/2,
                                  pM1.y() - (self.fromView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Start von oberer Seite
                 pStart = QPointF(pM1.x() - (self.fromView.size().height()/2)*(deltaX/deltaY),
                                  pM1.y() - self.fromView.size().height()/2)
             
             if deltaX/deltaY >= self.toView.size().width()/self.toView.size().height():
                 # Ende bei rechter Seite
                 pEnd = QPointF(pM2.x() + self.toView.size().width()/2,
                                pM2.y() + (self.toView.size().width()/2)*(deltaY/deltaX))
             else:
                 # Ende bei unterer Seite
                 pEnd = QPointF(pM2.x() + (self.toView.size().height()/2)*(deltaX/deltaY),
                                pM2.y() + self.toView.size().height()/2)
     
     #pStart = QPointF(self.fromView.x() + self.fromView.size().width(),
     #                 self.fromView.y() + self.fromView.size().height()/2)
     #pEnd = QPointF(self.toView.x(), self.toView.y() + self.toView.size().height()/2)
     p1 = pStart
     p2 = QPointF(pEnd.x()-(pEnd.x()-pStart.x())/7, pEnd.y()-(pEnd.y()-pStart.y())/7)
     p3 = QPointF(p2.x()-(p2.y()-p1.y())/20, p2.y()+(p2.x()-p1.x())/20)
     p4 = pEnd
     p5 = QPointF(p2.x()+(p2.y()-p1.y())/20, p2.y()-(p2.x()-p1.x())/20)
     p6 = p2
     points.append(p1)
     points.append(p2)
     points.append(p3)
     points.append(p4)
     points.append(p5)
     points.append(p6)
     self.setPolygon(points)
Beispiel #27
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)