Ejemplo n.º 1
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
Ejemplo n.º 2
0
    def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color):
        OWPlotItem.__init__(self)
        self.outer_box = QGraphicsPolygonItem(self)
        self.inner_box = QGraphicsPolygonItem(self)

        self.i = i
        self.mu1 = mu1
        self.mu2 = mu2
        self.sigma1 = sigma1
        self.sigma2 = sigma2
        self.phi = phi

        self.twosigmapolygon = QPolygonF([
            QPointF(i, mu1 - sigma1),
            QPointF(i, mu1 + sigma1),
            QPointF(i + 1, mu2 + sigma2),
            QPointF(i + 1, mu2 - sigma2),
            QPointF(i, mu1 - sigma1)
        ])

        self.sigmapolygon = QPolygonF([
            QPointF(i, mu1 - .5 * sigma1),
            QPointF(i, mu1 + .5 * sigma1),
            QPointF(i + 1, mu2 + .5 * sigma2),
            QPointF(i + 1, mu2 - .5 * sigma2),
            QPointF(i, mu1 - .5 * sigma1)
        ])

        if isinstance(color, tuple):
            color = QColor(*color)
        color.setAlphaF(.3)
        self.outer_box.setBrush(color)
        self.outer_box.setPen(QColor(0, 0, 0, 0))
        self.inner_box.setBrush(color)
        self.inner_box.setPen(color)
    def _add_selection(self, item):
        """Add selection rooted at item
        """
        outline = self._selection_poly(item)
        selection_item = QGraphicsPolygonItem(self)
#         selection_item = QGraphicsPathItem(self)
        selection_item.setPos(self.contentsRect().topLeft())
#         selection_item.setPen(QPen(Qt.NoPen))
        selection_item.setPen(make_pen(width=1, cosmetic=True))

        transform = self._itemgroup.transform()
        path = transform.map(outline)
        margin = 4
        if item.node.is_leaf:
            path = QPolygonF(path.boundingRect()
                             .adjusted(-margin, -margin, margin, margin))
        else:
            pass
#             ppath = QPainterPath()
#             ppath.addPolygon(path)
#             path = path_outline(ppath, width=margin).toFillPolygon()

        selection_item.setPolygon(path)
#         selection_item.setPath(path_outline(path, width=4))
        selection_item.unscaled_path = outline
        self._selection[item] = selection_item
        item.setSelected(True)
Ejemplo n.º 4
0
    def _add_selection(self, item):
        """Add selection rooted at item
        """
        outline = self._selection_poly(item)
        selection_item = QGraphicsPolygonItem(self)
        #         selection_item = QGraphicsPathItem(self)
        selection_item.setPos(self.contentsRect().topLeft())
        #         selection_item.setPen(QPen(Qt.NoPen))
        selection_item.setPen(make_pen(width=1, cosmetic=True))

        transform = self._itemgroup.transform()
        path = transform.map(outline)
        margin = 4
        if item.node.is_leaf:
            path = QPolygonF(path.boundingRect().adjusted(
                -margin, -margin, margin, margin))
        else:
            pass
#             ppath = QPainterPath()
#             ppath.addPolygon(path)
#             path = path_outline(ppath, width=margin).toFillPolygon()

        selection_item.setPolygon(path)
        #         selection_item.setPath(path_outline(path, width=4))
        selection_item.unscaled_path = outline
        self._selection[item] = selection_item
        item.setSelected(True)
Ejemplo n.º 5
0
 def set_poly_from_pos(self, positions, isactive=True, m=2, n=1):
     if isactive:
         # positions = ExternalDivision(positions).get_3rd_points_by(1).round().astype(int)
         positions = ExternalDivision(positions).get_3rd_points_by_ratio(
             m=m, n=n).round().astype(int)
         polygon = QPolygonF(map(QPointF, *positions.T))
     else:
         polygon = QPolygonF()
     self.setPolygon(polygon)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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
Ejemplo n.º 8
0
    def drawPatchQt(self, pos, turn, invert, patch_type, image, size,
                    foreColor, backColor, penwidth):  # pylint: disable=unused-argument
        """
        :param size: patch size
        """
        path = self.PATH_SET[patch_type]
        if not path:
            # blank patch
            invert = not invert
            path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)]

        polygon = QPolygonF([QPointF(x * size, y * size) for x, y in path])

        rot = turn % 4
        rect = [
            QPointF(0., 0.),
            QPointF(size, 0.),
            QPointF(size, size),
            QPointF(0., size)
        ]
        rotation = [0, 90, 180, 270]

        nopen = QtGui.QPen(foreColor, Qt.NoPen)
        foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern)
        if penwidth > 0:
            pen_color = QtGui.QColor(255, 255, 255)
            pen = QtGui.QPen(pen_color, Qt.SolidPattern)
            pen.setWidth(penwidth)

        painter = QPainter()
        painter.begin(image)
        painter.setPen(nopen)

        painter.translate(pos[0] * size + penwidth / 2,
                          pos[1] * size + penwidth / 2)
        painter.translate(rect[rot])
        painter.rotate(rotation[rot])

        if invert:
            # subtract the actual polygon from a rectangle to invert it
            poly_rect = QPolygonF(rect)
            polygon = poly_rect.subtracted(polygon)
        painter.setBrush(foreBrush)
        if penwidth > 0:
            # draw the borders
            painter.setPen(pen)
            painter.drawPolygon(polygon, Qt.WindingFill)
        # draw the fill
        painter.setPen(nopen)
        painter.drawPolygon(polygon, Qt.WindingFill)

        painter.end()

        return image
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 12
0
 def __init__(self, canvas, params={}):
     '''
     Constructor
     :param iface: An interface instance that will be passed to this class
         which provides the hook by which you can manipulate the QGIS
         application at run time.
     :type iface: QgsInterface
     :param params: A dictionary defining all the properties of the position marker
     :type params: dictionary
     '''
     self.canvas = canvas
     self.type = params.get('type', 'BOX').upper()
     self.size = int(params.get('size', 16))
     self.showLabel = bool(params.get('showLabel', True))
     s = (self.size - 1) / 2
     self.length = float(params.get('length', 98.0))
     self.width = float(params.get('width', 17.0))
     self.offsetX = float(params.get('offsetX', 0.0))
     self.offsetY = float(params.get('offsetY', 0.0))
     self.shape = params.get('shape', ((0.0, -0.5), (0.5, -0.3), (0.5, 0.5),
                                       (-0.5, 0.50), (-0.5, -0.3)))
     self.paintShape = QPolygonF(
         [QPointF(-s, -s),
          QPointF(s, -s),
          QPointF(s, s),
          QPointF(-s, s)])
     self.color = self.getColor(params.get('color', 'black'))
     self.fillColor = self.getColor(params.get('fillColor', 'lime'))
     self.penWidth = int(params.get('penWidth', 1))
     spw = s + self.penWidth + 1
     self.bounding = QRectF(-spw, -spw, spw * 2, spw * 2)
     if self.type in ('CROSS', 'X'):
         self.penWidth = 5
     self.trackLen = int(params.get('trackLength', 100))
     self.trackColor = self.getColor(
         params.get('trackColor', self.fillColor))
     self.track = deque()
     self.position = None
     self.heading = 0
     super(PositionMarker, self).__init__(canvas)
     self.setZValue(int(params.get('zValue', 100)))
     self.distArea = QgsDistanceArea()
     self.distArea.setEllipsoid(u'WGS84')
     self.distArea.setEllipsoidalMode(True)
     if self.showLabel:
         self.label = MarkerLabel(self.canvas, params)
         self.label.setZValue(self.zValue() + 0.1)
     self.updateSize()
Ejemplo n.º 13
0
 def points( self, phase ):
     points = QPolygonF()
     numSamples = 9
     for i in range(numSamples):
         v = i * 2.0 * 3.14159 / ( numSamples - 1 )
         points += QPointF( math.sin( v - phase ), math.cos( 3.0 * ( v + phase ) ) )
     return points;
Ejemplo n.º 14
0
    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)))
Ejemplo n.º 15
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
Ejemplo n.º 16
0
    def polygon_from_data(xData, yData):
        """
            Creates a polygon from a list of x and y coordinates.

            :returns: A polygon with point corresponding to ``xData`` and ``yData``.
            :rtype: QPolygonF
        """
        if xData and yData:
            n = min(len(xData), len(yData))
            p = QPolygonF(n + 1)
            for i in range(n):
                p[i] = QPointF(xData[i], yData[i])
            p[n] = QPointF(xData[0], yData[0])
            return p
        else:
            return QPolygonF()
Ejemplo n.º 17
0
 def points(self, phase ):
     pnts = QPolygonF()
     numSamples = 15;
     for i in range(numSamples):
         v = 6.28 * i / ( numSamples - 1 )
         pnts += QPointF( math.sin( v - phase ), v )
     return pnts
Ejemplo n.º 18
0
 def points(self, phase ):
     points = QPolygonF()
     numSamples = 50
     for i in range(numSamples):
         v = 10.0 * i / ( numSamples - 1 )
         points += QPointF( v, math.cos( 3.0 * ( v + phase ) ) )
     return points
Ejemplo n.º 19
0
 def setSamples(self, numPoints):
     samples = QPolygonF()
     for i in range(numPoints):
         x = randomValue() * 24.0 + 1.0
         y = math.log(10.0 * (x - 1.0) + 1.0) * (randomValue() * 0.5 + 0.9)
         samples += QPointF(x, y)
     self.d_plot.setSamples(samples)
Ejemplo n.º 20
0
def read_patternRepeats_API_3(stream, numRepeats):
    """ Read all patternRepeats from our output stream """

    patternRepeats = []
    for count in range(numRepeats):

        polygon = QPolygonF()
        stream >> polygon

        position = QPointF()
        stream >> position

        legendID = stream.readUInt16()
        width = stream.readInt16()
        color = QColor()
        stream >> color

        newItem = {
            "polygon": polygon,
            "position": position,
            "width": width,
            "color": color,
            "legendID": legendID
        }

        patternRepeats.append(newItem)

    return patternRepeats
Ejemplo n.º 21
0
 def __init__(self, canvas, params={}):
     '''
     Constructor
     :param iface: An interface instance that will be passed to this class
         which provides the hook by which you can manipulate the QGIS
         application at run time.
     :type iface: QgsInterface
     :param params: A dictionary defining all the properties of the position marker
     :type params: dictionary
     '''
     self.canvas = canvas
     self.type = params.get('type', 'BOX').upper()
     self.size = int(params.get('size', 16))
     self.bounding = 1.414213562 * self.size
     self.length = float(params.get('length', 98.0))
     self.width = float(params.get('width', 17.0))
     self.shape = params.get('shape', ((0.0, -0.5), (0.5, -0.3), (0.5, 0.5), (-0.5, 0.50), (-0.5, -0.3)))
     s = (self.size - 1) / 2
     self.paintShape = QPolygonF([QPointF(-s, -s), QPointF(s, -s), QPointF(s, s), QPointF(-s, s)])
     self.color = self.getColor(params.get('color', 'black'))
     self.fillColor = self.getColor(params.get('fillColor', 'lime'))
     self.penWidth = int(params.get('penWidth', 1))
     if self.type in ('CROSS', 'X'):
         self.penWidth = 5
     self.trackLen = int(params.get('trackLength', 100))
     self.trackColor = self.getColor(params.get('trackColor', self.fillColor))
     self.track = deque()
     self.pos = None
     self.heading = 0
     super(PositionMarker, self).__init__(canvas)
     self.setZValue(int(params.get('zValue', 100)))
     self.distArea = QgsDistanceArea()
     self.distArea.setEllipsoid(u'WGS84')
     self.distArea.setEllipsoidalMode(True)
     self.updateSize()
Ejemplo n.º 22
0
 def on_actionGotoCell_triggered(self):
     cells = [str(cid) for cid in self._data.cells]
     selected, ok = QInputDialog.getItem(self, "Goto cell",
                                         "Select the cell to go to", cells,
                                         0)
     if ok:
         cid = int(selected)
         self.ui.actionAdd_cell.setChecked(True)
         data = self._data
         if cid not in data.cells:
             return
         ls = data.cells_lifespan[cid]
         prev_pos = self._previousScene.current_data._current_index
         cur_pos = self._currentScene.current_data._current_index
         full_poly = data.cells[cid]
         poly = [pid for pid in full_poly if pid in data[prev_pos]]
         #log_debug("Cell %d on time %d: %s" % (cid, prev_pos, poly))
         if prev_pos < ls.start or prev_pos >= ls.end or not poly:
             for i in range(*ls.slice().indices(len(data))):
                 poly = [pid for pid in full_poly if pid in data[i]]
                 if poly:
                     log_debug("Found cell %d on image %d with polygon %s" %
                               (cid, i, poly))
                     new_prev_pos = i
                     break
             else:
                 log_debug("Cell %d found nowhere in range %s!!!" %
                           (cid, ls.slice()))
         else:
             new_prev_pos = prev_pos
         new_cur_pos = min(max(cur_pos + new_prev_pos - prev_pos, 0),
                           len(data))
         self.ui.previousState.setCurrentIndex(new_prev_pos)
         self.ui.currentState.setCurrentIndex(new_cur_pos)
         self._previousScene.current_cell = cid
         self._currentScene.current_cell = cid
         prev_data = self._previousScene.current_data
         poly = data.cells[cid]
         prev_poly = QPolygonF(
             [prev_data[ptid] for ptid in poly if ptid in prev_data])
         prev_bbox = prev_poly.boundingRect()
         log_debug("Previous bounding box = %dx%d+%d+%d" %
                   (prev_bbox.width(), prev_bbox.height(), prev_bbox.left(),
                    prev_bbox.top()))
         self.ui.previousData.ensureVisible(prev_bbox)
Ejemplo n.º 23
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))
Ejemplo n.º 24
0
    def __updateShape(self):

        fBBox = QFontMetrics(self.Font).boundingRect(self.Name)

        if self.__polygon.boundingRect().width() < fBBox.width():
            self.__polygon = QPolygonF(QRectF(fBBox).normalized().adjusted(-fBBox.width() / 4,
                                                                           -fBBox.height() / 4,
                                                                           fBBox.height(),
                                                                           fBBox.height() / 2))
Ejemplo n.º 25
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
Ejemplo n.º 26
0
 def paintEvent(self, event=None):
     font = QFont(self.font())
     font.setPointSize(font.pointSize() - 1)
     fm = QFontMetricsF(font)
     fracWidth = fm.width(FractionSlider.WSTRING)
     indent = fm.boundingRect("9").width() / 2.0
     if not X11:
         fracWidth *= 1.5
     span = self.width() - (FractionSlider.XMARGIN * 2)
     value = self.__numerator / float(self.__denominator)
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.TextAntialiasing)
     painter.setPen(self.palette().color(QPalette.Mid))
     painter.setBrush(self.palette().brush(
             QPalette.AlternateBase))
     painter.drawRect(self.rect())
     segColor = QColor(Qt.green).dark(120)
     segLineColor = segColor.dark()
     painter.setPen(segLineColor)
     painter.setBrush(segColor)
     painter.drawRect(FractionSlider.XMARGIN,
                      FractionSlider.YMARGIN, span, fm.height())
     textColor = self.palette().color(QPalette.Text)
     segWidth = span / self.__denominator
     segHeight = fm.height() * 2
     nRect = fm.boundingRect(FractionSlider.WSTRING)
     x = FractionSlider.XMARGIN
     yOffset = segHeight + fm.height()
     for i in range(self.__denominator + 1):
         painter.setPen(segLineColor)
         painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight)
         painter.setPen(textColor)
         y = segHeight
         rect = QRectF(nRect)
         rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
         painter.drawText(rect, Qt.AlignCenter,
                          QString.number(i))
         y = yOffset
         rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
         painter.drawText(rect, Qt.AlignCenter,
                          QString.number(self.__denominator))
         painter.drawLine(QPointF(rect.left() + indent, y),
                          QPointF(rect.right() - indent, y))
         x += segWidth
     span = int(span)
     y = FractionSlider.YMARGIN - 0.5
     triangle = [QPointF(value * span, y),
                 QPointF((value * span) +
                         (2 * FractionSlider.XMARGIN), y),
                 QPointF((value * span) +
                         FractionSlider.XMARGIN, fm.height())]
     painter.setPen(Qt.yellow)
     painter.setBrush(Qt.darkYellow)
     painter.drawPolygon(QPolygonF(triangle))
Ejemplo n.º 27
0
    def drawSkel(self, worm_img, worm_qimg, row_data, roi_corner=(0, 0)):
        if not self.skel_file or not isinstance(self.trajectories_data,
                                                pd.DataFrame):
            return

        c_ratio_y = worm_qimg.width() / worm_img.shape[1]
        c_ratio_x = worm_qimg.height() / worm_img.shape[0]

        skel_id = int(row_data['skeleton_id'])

        qPlg = {}

        with tables.File(self.skel_file, 'r') as ske_file_id:
            for tt in ['skeleton', 'contour_side1', 'contour_side2']:
                dat = ske_file_id.get_node('/' + tt)[skel_id]
                dat[:, 0] = (dat[:, 0] - roi_corner[0]) * c_ratio_x
                dat[:, 1] = (dat[:, 1] - roi_corner[1]) * c_ratio_y

                qPlg[tt] = QPolygonF()
                for p in dat:
                    qPlg[tt].append(QPointF(*p))

        if 'is_good_skel' in row_data and row_data['is_good_skel'] == 0:
            self.skel_colors = {
                'skeleton': (102, 0, 0),
                'contour_side1': (102, 0, 0),
                'contour_side2': (102, 0, 0)
            }
        else:
            self.skel_colors = {
                'skeleton': (27, 158, 119),
                'contour_side1': (217, 95, 2),
                'contour_side2': (231, 41, 138)
            }

        pen = QPen()
        pen.setWidth(2)

        painter = QPainter()
        painter.begin(worm_qimg)

        for tt, color in self.skel_colors.items():
            pen.setColor(QColor(*color))
            painter.setPen(pen)
            painter.drawPolyline(qPlg[tt])

        pen.setColor(Qt.black)
        painter.setBrush(Qt.white)
        painter.setPen(pen)

        radius = 3
        painter.drawEllipse(qPlg['skeleton'][0], radius, radius)

        painter.end()
Ejemplo n.º 28
0
 def __init__(self):
     Curve.__init__(self)
     self.d_points = QPolygonF()
     self.setStyle( Qwt.QwtPlotCurve.Lines )
     self.setPen( Qt.red, 2 )
     self.initSamples()
     # somewhere in the center
     transform = QTransform()
     transform.translate( 7.0, 3.0 )
     transform.scale( 1.5, 1.5 )
     self.setTransformation( transform )
Ejemplo n.º 29
0
    def _selection_poly(self, item):
        """Return an selection item covering the selection rooted at item.
        """
        def branches(item):
            return [self._items[ch] for ch in item.node.branches]

        def left(item):
            return [self._items[ch] for ch in item.node.branches[:1]]

        def right(item):
            return [self._items[ch] for ch in item.node.branches[-1:]]

        allitems = list(preorder(item, left)) + list(preorder(item, right))[1:]

        if len(allitems) == 1:
            assert (allitems[0].node.is_leaf)
        else:
            allitems = [item for item in allitems if not item.node.is_leaf]

        brects = [QPolygonF(item.boundingRect()) for item in allitems]
        return reduce(QPolygonF.united, brects, QPolygonF())
    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
Ejemplo n.º 31
0
 def on_actionGotoCell_triggered(self):
     cells = [str(cid) for cid in self._data.cells]
     selected, ok = QInputDialog.getItem(self, "Goto cell", "Select the cell to go to", cells, 0)
     if ok:
         cid = int(selected)
         self.ui.actionAdd_cell.setChecked(True)
         data = self._data
         if cid not in data.cells:
             return
         ls = data.cells_lifespan[cid]
         prev_pos = self._previousScene.current_data._current_index
         cur_pos = self._currentScene.current_data._current_index
         full_poly = data.cells[cid]
         poly = [pid for pid in full_poly if pid in data[prev_pos]]
         #log_debug("Cell %d on time %d: %s" % (cid, prev_pos, poly))
         if prev_pos < ls.start or prev_pos >= ls.end or not poly:
             for i in range(*ls.slice().indices(len(data))):
                 poly = [pid for pid in full_poly if pid in data[i]]
                 if poly:
                     log_debug("Found cell %d on image %d with polygon %s" % (cid, i, poly))
                     new_prev_pos = i
                     break
             else:
                 log_debug("Cell %d found nowhere in range %s!!!" % (cid, ls.slice()))
         else:
             new_prev_pos = prev_pos
         new_cur_pos = min(max(cur_pos + new_prev_pos - prev_pos, 0), len(data))
         self.ui.previousState.setCurrentIndex(new_prev_pos)
         self.ui.currentState.setCurrentIndex(new_cur_pos)
         self._previousScene.current_cell = cid
         self._currentScene.current_cell = cid
         prev_data = self._previousScene.current_data
         poly = data.cells[cid]
         prev_poly = QPolygonF([prev_data[ptid] for ptid in poly if ptid in prev_data])
         prev_bbox = prev_poly.boundingRect()
         log_debug("Previous bounding box = %dx%d+%d+%d" % (prev_bbox.width(), prev_bbox.height(),
                                                            prev_bbox.left(), prev_bbox.top()))
         self.ui.previousData.ensureVisible(prev_bbox)
Ejemplo n.º 32
0
    def paint(self, painter, option, widget=None):

        painter.setPen(self.pen())
        painter.setBrush(
            EDraw.EColor.LinearGradient(self.boundingRect(), Qt.darkGray))
        painter.drawPolygon(QPolygonF(self.boundingRect()))

        painter.setPen(Qt.lightGray)

        r = QRectF(0.0, -(self.__sExtra / 2),
                   self.__name.boundingRect().width(),
                   self.boundingRect().height())
        painter.drawText(r, Qt.AlignRight | Qt.AlignCenter,
                         "%s: " % self.__name.toPlainText())
Ejemplo n.º 33
0
 def __init__(self, startItem, startIndex, endItem, endIndex,
              parent=None, scene=None):
     super(ModelerArrowItem, self).__init__(parent, scene)
     self.arrowHead = QPolygonF()
     self.endIndex = endIndex
     self.startIndex = startIndex
     self.startItem = startItem
     self.endItem = endItem
     self.endPoints = []
     self.setFlag(QGraphicsItem.ItemIsSelectable, False)
     self.myColor = Qt.gray
     self.setPen(QPen(self.myColor, 1, Qt.SolidLine,
                 Qt.RoundCap, Qt.RoundJoin))
     self.setZValue(0)
Ejemplo n.º 34
0
	def __init__(self, poly = None, dim = None):
		if not poly:
			if not dim:
				raise ValueError("need to set bounding rect!")
			else:
				poly = []
				for i in range(10):
					poly.append(planar.Point(
						random.randint(dim.left(),dim.right()),
						random.randint(dim.top(),dim.bottom())))
				poly = planar.Polygon.convex_hull(poly)
				poly = QPolygonF([QPointF(p.x,p.y) for p in poly])
			
		QGraphicsPolygonItem.__init__(self, poly)
		self.setConnectors([(0,random.random()),(len(poly)//2,random.random())])
Ejemplo n.º 35
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_
Ejemplo n.º 36
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)
Ejemplo n.º 37
0
    def drawArrow(self, painter, p, v, head_size):
        base = p - v
        tip = p + v
        painter.drawLine(base, tip)

        vl = length(v)
        nv = v / vl
        head_size = head_size * vl

        orth = QPointF(nv.y(), -nv.x()) * head_size
        base_center = tip - nv * head_size * 2.0
        base1 = base_center + orth
        base2 = base_center - orth
        base_center = tip - nv * head_size * 1.0

        painter.drawPolygon(QPolygonF([base_center, base1, tip, base2]))
Ejemplo n.º 38
0
    def updateShape(self, point=None, pos=None):
        # Main arrow direction
        params = parameters.instance
        scale = self.scale
        ms = min(scale)
        head_size = params.arrow_head_size * ms
        width = params.arrow_line_size * ms
        self.prepareGeometryChange()
        if point == self.source:
            p1 = pos
        else:
            p1 = self.source.pos()
        self.setPos(p1)
        if point == self.target:
            p2 = pos
        else:
            p2 = self.target.pos()
        tip = p2 - p1
        if abs(tip.x()) > 0.001 or abs(tip.y()) > 0.001:
            # Normalised
            #ntip = tip/stip
            ntip = tip
            # Arrow head base
            orth = QPointF(ntip.y(), -ntip.x()) * (head_size * 0.5)
            base_center = tip * (1 - 2 * head_size)
            base1 = base_center + orth
            base2 = base_center - orth
            base_center = tip * (1 - head_size * 1.50)
        else:
            ntip = tip
            base_center = tip
            base1 = tip
            base2 = tip

        self.tip = tip
        self.base_center = base_center
        self.base1 = base1
        self.base2 = base2

        path = QPainterPath()
        path.lineTo(base_center)
        path.addPolygon(QPolygonF([base_center, base1, tip, base2]))
        path.closeSubpath()
        self.rect = path.controlPointRect().adjusted(-width, -width, 2 * width,
                                                     2 * width)
        self.path = path
        self.update()
Ejemplo n.º 39
0
    def __init__(self, ENodeHandle):
        ENode.__init__(self, ENodeHandle)

        self.__polygon = QPolygonF(QRectF(-50, -15, 100, 30))

        self.__updateShape()

        self.__attributes = {}
        self.__hiddenAttributes = {}

        self.__group = QGraphicsItemGroup()
        self.__group.addToGroup(QGraphicsPolygonItem(self.__polygon))

        self.__buildAttributes(self.Handle.lsInputAttributes())
        self.__buildAttributes(self.Handle.lsOutputAttributes(), True)

        self.__muted = None
Ejemplo n.º 40
0
 def polygon(self):
     font = QFont('Verdana', 8)
     fm = QFontMetricsF(font)
     hUp = fm.height() * 1.2 * (len(self.element.parameters) + 2)
     hDown = fm.height() * 1.2 * (len(self.element.outputs) + 2)
     pol = QPolygonF([
         QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2,
                 -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp),
         QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2,
                 (ModelerGraphicItem.BOX_HEIGHT + 2) / 2 + hDown),
         QPointF((ModelerGraphicItem.BOX_WIDTH + 2) / 2,
                 (ModelerGraphicItem.BOX_HEIGHT + 2) / 2 + hDown),
         QPointF((ModelerGraphicItem.BOX_WIDTH + 2) / 2,
                 -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp),
         QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2,
                 -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp)
     ])
     return pol
Ejemplo n.º 41
0
def arrow_path_concave(line, width):
    """
    Return a :class:`QPainterPath` of a pretty looking arrow.
    """
    path = QPainterPath()
    p1, p2 = line.p1(), line.p2()

    if p1 == p2:
        return path

    baseline = QLineF(line)
    # Require some minimum length.
    baseline.setLength(max(line.length() - width * 3, width * 3))

    start, end = baseline.p1(), baseline.p2()
    mid = (start + end) / 2.0
    normal = QLineF.fromPolar(1.0, baseline.angle() + 90).p2()

    path.moveTo(start)
    path.lineTo(start + (normal * width / 4.0))

    path.quadTo(mid + (normal * width / 4.0), end + (normal * width / 1.5))

    path.lineTo(end - (normal * width / 1.5))
    path.quadTo(mid - (normal * width / 4.0), start - (normal * width / 4.0))
    path.closeSubpath()

    arrow_head_len = width * 4
    arrow_head_angle = 50
    line_angle = line.angle() - 180

    angle_1 = line_angle - arrow_head_angle / 2.0
    angle_2 = line_angle + arrow_head_angle / 2.0

    points = [
        p2, p2 + QLineF.fromPolar(arrow_head_len, angle_1).p2(),
        baseline.p2(), p2 + QLineF.fromPolar(arrow_head_len, angle_2).p2(), p2
    ]

    poly = QPolygonF(points)
    path_head = QPainterPath()
    path_head.addPolygon(poly)
    path = path.united(path_head)
    return path
Ejemplo n.º 42
0
 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)
Ejemplo n.º 43
0
 def test_QPolygon_intersection(self):
   tri1 = QVectorF([(0,0),(0,1),(1,0)])
   tri2 = QVectorF([(1,0),(0,0),(1,1)])
   tri3 = QVectorF([(.5,.5),(1,0),(0,0),(.5,.5)])
   tri3i = QVector([(1,1),(1,0),(0,0),(1,1)])
   sq1 = QVectorF([(0,0),(0,1),(1,1),(1,0)])
   # Intersect two triangles
   p1 = QPolygonF(tri1)
   p2 = QPolygonF(tri2)
   p3 = p1.intersected(p2)
   self.assertTrue( p1 == p1 )
   self.assertTrue( p1 == QPolygonF(tri1) )
   self.assertTrue( p3 == QPolygonF(tri3) )
   # Intersect two integer triangles
   p1 = QtGui.QPolygon(map(lambda (x,y): QtCore.QPoint(x,y), [(0,0),(0,1),(1,0)]))
   p2 = QtGui.QPolygon(map(lambda (x,y): QtCore.QPoint(x,y), [(1,0),(0,0),(1,1)]))
   p3 = p1.intersected(p2)
   self.assertTrue( p3 == QtGui.QPolygon(tri3i) )
   # Test containment/overlapping
   p1 = QtGui.QPolygonF(sq1)
   for v1 in sq1: self.assertTrue( p1.contains(v1) )        # vertices are contained
   self.assertTrue( p1.translated(2,0).intersected(p1).isEmpty() )
   self.assertTrue( p1.translated(1,0).intersected(p1).isEmpty() ) # common edges do not overlap
   self.assertFalse( p1.translated(.5,0).intersected(p1).isEmpty() )
Ejemplo n.º 44
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)
Ejemplo n.º 45
0
 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)
Ejemplo n.º 46
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
Ejemplo n.º 47
0
class PositionMarker(QgsMapCanvasItem):
    '''
    classdocs
    '''

    def __init__(self, canvas, params={}):
        '''
        Constructor
        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        :param params: A dictionary defining all the properties of the position marker
        :type params: dictionary
        '''
        self.canvas = canvas
        self.type = params.get('type', 'BOX').upper()
        self.size = int(params.get('size', 16))
        self.bounding = 1.414213562 * self.size
        self.length = float(params.get('length', 98.0))
        self.width = float(params.get('width', 17.0))
        self.shape = params.get('shape', ((0.0, -0.5), (0.5, -0.3), (0.5, 0.5), (-0.5, 0.50), (-0.5, -0.3)))
        s = (self.size - 1) / 2
        self.paintShape = QPolygonF([QPointF(-s, -s), QPointF(s, -s), QPointF(s, s), QPointF(-s, s)])
        self.color = self.getColor(params.get('color', 'black'))
        self.fillColor = self.getColor(params.get('fillColor', 'lime'))
        self.penWidth = int(params.get('penWidth', 1))
        if self.type in ('CROSS', 'X'):
            self.penWidth = 5
        self.trackLen = int(params.get('trackLength', 100))
        self.trackColor = self.getColor(params.get('trackColor', self.fillColor))
        self.track = deque()
        self.pos = None
        self.heading = 0
        super(PositionMarker, self).__init__(canvas)
        self.setZValue(int(params.get('zValue', 100)))
        self.distArea = QgsDistanceArea()
        self.distArea.setEllipsoid(u'WGS84')
        self.distArea.setEllipsoidalMode(True)
        self.updateSize()

    def properties(self):
        return {'type': self.type,
                'size': self.size,
                'length': self.length,
                'width': self.width,
                'shape': self.shape,
                'color': self.color.rgba(),
                'fillColor': self.fillColor.rgba(),
                'penWidth': self.penWidth,
                'trackLength': self.trackLen,
                'trackColor' : self.trackColor.rgba(),
                'zValue': self.zValue()}

    def setMapPosition(self, pos):
        if self.pos != pos:
            self.updateTrack()
            self.pos = pos
            self.setPos(self.toCanvasCoordinates(self.pos))
            self.update()

    def newHeading(self, heading):
        if self.heading != heading:
            self.heading = heading
            self.setRotation(self.canvas.rotation() + self.heading)
            self.update()

    def resetPosition(self):
        self.pos = None

    def updatePosition(self):
        if self.pos:
            self.prepareGeometryChange()
            self.updateSize()
            self.setPos(self.toCanvasCoordinates(self.pos))
            self.setRotation(self.canvas.rotation() + self.heading)
            self.update()

    def updateSize(self):
        if self.type != 'SHAPE':
            return
        s = self.canvas.mapSettings()
        self.distArea.setSourceCrs(s.destinationCrs())
        try:
            p1 = self.toMapCoordinates(QPoint(0, 0))
            p2 = self.toMapCoordinates(QPoint(0, 100))
            l = self.distArea.measureLine(p1, p2)
            f = 100 / l
        except:
            f = s.outputDpi() / 0.0254 / s.scale()
        paintLength = max(self.length * f, 50)
        paintWidth = paintLength * self.width / self.length
        self.paintShape.clear()
        for v in self.shape:
            self.paintShape << QPointF(v[0] * paintWidth, v[1] * paintLength)
        self.size = max(paintLength, paintWidth)
        self.bounding = sqrt(pow(paintLength, 2) + pow(paintLength, 2))

    def updateTrack(self):
        if self.pos and self.trackLen:
            if len(self.track) >= self.trackLen:
                tpr = self.track.popleft()
                self.canvas.scene().removeItem(tpr)
                del(tpr)
            tp = QgsVertexMarker(self.canvas)
            tp.setCenter(self.pos)
            tp.setIconType(QgsVertexMarker.ICON_CROSS)
            tp.setColor(self.trackColor)
            tp.setZValue(self.zValue() - 0.1)
            tp.setIconSize(3)
            tp.setPenWidth(3)
            self.track.append(tp)

    def setVisible(self, visible):
        for tp in self.track:
            tp.setVisible(visible)
        QgsMapCanvasItem.setVisible(self, visible)

    def deleteTrack(self):
        for tp in self.track:
            self.canvas.scene().removeItem(tp)
        self.track.clear()

    def paint(self, painter, xxx, xxx2):
        if not self.pos:
            return

        s = (self.size - 1) / 2
        pen = QPen(self.color)
        pen.setWidth(self.penWidth)
        painter.setPen(pen)
        if self.type == 'CROSS':
            painter.drawLine(QLineF(-s, 0, s, 0))
            painter.drawLine(QLineF(0, -s, 0, s))
        elif self.type == 'X':
            painter.drawLine(QLineF(-s, -s, s, s))
            painter.drawLine(QLineF(-s, s, s, -s))
        elif self.type == 'BOX':
            brush = QBrush(self.fillColor)
            painter.setBrush(brush)
            painter.drawConvexPolygon(self.paintShape)
        elif self.type == 'SHAPE':
            painter.setRenderHint(QPainter.Antialiasing, True)
            brush = QBrush(self.fillColor)
            painter.setBrush(brush)
            painter.drawConvexPolygon(self.paintShape)

    def boundingRect(self):
        s = self.bounding / 2
        return QRectF(QPointF(-s, -s), QPointF(s, s))

    def getColor(self, value):
        try:
            return QColor.fromRgba(int(value))
        except ValueError:
            return QColor(value)

    def removeFromCanvas(self):
        self.deleteTrack()
        self.canvas.scene().removeItem(self)
Ejemplo n.º 48
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)
Ejemplo n.º 49
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")
Ejemplo n.º 50
0
    def setGeometry(self):
        """
        Read the parameters that define the geometry of the point
        """
        params = parameters.instance
        self.setEditable(params.is_cell_editable)
        points = self.points
        polygon_id = self.polygon_id
        polygon = [points[pt].pos() if pt in points else None for pt in polygon_id]
        non_none_cnt = len([p for p in polygon if p is not None])
        if non_none_cnt == 0:
            self.rect = QRectF()
            self.bounding_rect = QRectF()
            self.setVisible(False)
            return
        self.setVisible(True)
# First, check if this is a "simple" cell
        walls = self.walls
        real_polygon = [pid for pid in polygon_id if pid in points]
        #sides = [ walls[real_polygon[i], real_polygon[(i+1)%len(real_polygon)]] for i in range(len(real_polygon)) ]
        sides = [None] * len(polygon)
        self.sides = sides
        real_scale_x = self.scale[0]/self.glob_scale
        real_scale_y = self.scale[1]/self.glob_scale
        for i in range(len(polygon)):
            if polygon[i] is not None:  # Find the next
                j = (i+1) % len(polygon)
                while polygon[j] is None:
                    j = (j+1) % len(polygon)
                w = [QPointF(p.x()*real_scale_x, p.y()*real_scale_y) for p in walls[polygon_id[i], polygon_id[j]]]
                sides[i] = [polygon[i]] + w + [polygon[j]]
        prev = real_polygon[-1]
        polygon_shape = []
        for i in range(len(polygon)):
            if polygon[i]:
                polygon_shape.append(polygon[i])
                polygon_shape.extend(sides[i])
# Now add the dummy points .. starts at the first non-None point
        if non_none_cnt > 2:
            start = None
            for i in range(len(polygon)):
                if polygon[i] is not None:
                    start = i
                    break
            prev = start
            cur = start+1 if start+1 < len(polygon) else 0
            log_debug("Polygon before: [%s]" % ",".join("(%f,%f)" % (p.x(), p.y()) if p is not None else "None"
                                                        for p in polygon))
            while cur != start:
                if polygon[cur] is None:
                    cnt = 1
                    next = cur+1 if cur+1 < len(polygon) else 0
                    while True:
                        if polygon[next] is None:
                            cnt += 1
                        else:
                            break
                        next += 1
                        if next == len(polygon):
                            next = 0
                    #print "%d points missing" % cnt
                    # First, find total length of wall
                    length = 0.0
                    side = sides[prev]
                    for i in range(len(side)-1):
                        length += dist(side[i], side[i+1])
                    diff = length/(cnt+1)  # Distance between two points
                    i = cur
                    p = side[0]
                    for j in range(cnt):
                        l = 0.0
                        found = False
                        for k in range(len(side)-1):
                            dl = dist(side[k], side[k+1])
                            l += dl
                            if l > diff*(1+1e-5):  # Account for accumulation of small errors
                                c = (i + j) % len(polygon)
                                delta = diff-l+dl
                                p = side[k] + (side[k+1]-side[k])*delta/dl
                                s1 = side[:k+1] + [p]
                                s2 = [p] + side[k+1:]
                                sides[c-1] = s1
                                sides[c] = s2
                                side = s2
                                polygon[c] = p
                                found = True
                                break
                        assert found, "Could not find point in polygon for position %d" % (j+i,)
                        #p = p + diff
                        #c = (i+j)%len(polygon)
                        #polygon[c] = QPointF(p)
                    cur = next
                else:
                    prev = cur
                    cur += 1
                if cur >= len(polygon):
                    cur = 0
            assert None not in polygon, "Error, some dummy points were not added"
        else:
            polygon = [p for p in polygon if p is not None]
        center = sum(polygon, QPointF(0, 0)) / float(len(polygon))
        self.center = center
        if len(polygon) > 2:
            polygon = QPolygonF(polygon+[polygon[0]])
            polygon.translate(-center)
            polygon_shape = QPolygonF(polygon_shape + [polygon_shape[0]])
            self.polygon_shape = polygon_shape
            polygon_shape.translate(-center)
            # Translate the sides too
            sides = [[p-center for p in s] for s in sides]
            self.sides = sides
            assert len(sides) == len(polygon)-1
        elif len(polygon) == 2:
            polygon = QLineF(polygon[0], polygon[1])
            polygon.translate(-center)
        else:
            polygon = None
        self.polygon = polygon
        self.setPos(center)
        params = parameters.instance
        self.prepareGeometryChange()
        size = params.cell_size
        scale = self.scale
        height = size*cos(pi/6)*scale[1]
        width = size*scale[0]
        pos_x = size*cos(pi/3)*scale[0]
        self.sel_rect = QRectF(-width, -height, 2*width, 2*height)
        if isinstance(polygon, QPolygonF):
            self.rect = self.polygon_shape.boundingRect() | self.sel_rect
        elif isinstance(polygon, QLineF):
            self.rect = QRectF(polygon.p1(), polygon.p2()).normalized() | self.sel_rect
        else:
            self.rect = self.sel_rect
        self.bounding_rect = QRectF(self.rect)
        if self.p1 in points and self.p2 in points:
            self.division_line = QLineF(points[self.p1].pos()-center, points[self.p2].pos()-center)
        else:
            self.division_line = None
        self.hexagon = QPolygonF([QPointF(-width, 0), QPointF(-pos_x, height), QPointF(pos_x, height),
                                  QPointF(width, 0), QPointF(pos_x, -height), QPointF(-pos_x, -height)])
        self.hexagon_path = QPainterPath()
        self.hexagon_path.addPolygon(self.hexagon)
        s1 = QPainterPath()
        if isinstance(self.polygon, QPolygonF):
            s1.addPolygon(polygon_shape)
        elif isinstance(self.polygon, QLineF):
            s1.moveTo(self.polygon.p1())
            s1.lineTo(self.polygon.p2())
        stroke = QPainterPathStroker()
        sel_thick = 3*params.cell_thickness
        if sel_thick == 0:
            sel_thick = 3
        stroke.setWidth(sel_thick)
        self.stroke = stroke.createStroke(s1)
Ejemplo n.º 51
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)
Ejemplo n.º 52
0
class EPoint(ENode):

    def __init__(self, ENodeHandle):
        ENode.__init__(self, ENodeHandle)

        self.__polygon = QPolygonF(QRectF(-50, -15, 100, 30))

        self.__updateShape()

        self.__attributes = {}
        self.__hiddenAttributes = {}

        self.__group = QGraphicsItemGroup()
        self.__group.addToGroup(QGraphicsPolygonItem(self.__polygon))

        self.__buildAttributes(self.Handle.lsInputAttributes())
        self.__buildAttributes(self.Handle.lsOutputAttributes(), True)

        self.__muted = None

    def __updateShape(self):

        fBBox = QFontMetrics(self.Font).boundingRect(self.Name)

        if self.__polygon.boundingRect().width() < fBBox.width():
            self.__polygon = QPolygonF(QRectF(fBBox).normalized().adjusted(-fBBox.width() / 4,
                                                                           -fBBox.height() / 4,
                                                                           fBBox.height(),
                                                                           fBBox.height() / 2))

    def __buildAttributes(self, attributes, opposite=False):

        rotation = 90

        for index, point in enumerate(self.getPoints(len(attributes), opposite)):

            switch = {0: point.y() - (8 + self.pen().width()), 1: point.y() + (5 + self.pen().width())}

            connSlot = EDraw.Circle(8, 3, rotation).translated(QPointF(point.x(), switch[opposite]))

            self.__group.addToGroup(QGraphicsPolygonItem(connSlot))

            self.__attributes[connSlot] = dict({self.kGuiAttributeId: attributes[index].Id,
                                               self.kGuiAttributeType: attributes[index].Type,
                                               self.kGuiAttributeParent: self,
                                               self.kGuiAttributePlug: self.Polygon.boundingRect().center(),
                                               self.kGuiAttributeLongName: attributes[index].Name})

        return

    @property
    def Polygon(self):
        return self.__polygon

    @property
    def BoundPolygon(self):
        return self.__polygon.boundingRect()

    def mute(self, uuid):
        self.__muted = uuid

    def togglePlug(self, plugId):

        hiddenId = self.mapFromId(plugId)[ENode.kGuiAttributeId]

        if self.__hiddenAttributes.has_key(hiddenId):
            self.__hiddenAttributes.pop(hiddenId, None)
            return

        self.__hiddenAttributes[self.mapFromId(plugId)[ENode.kGuiAttributeId]] = []

    def mapFromPoint(self, QPoint):

        for attrRect, attrValues in self.__attributes.iteritems():
            if attrRect.boundingRect().contains(self.mapFromScene(QPoint)):
                return attrValues[self.kGuiAttributeId], self.scenePos()

        return self.Handle.Id, None

    def mapFromId(self, attrId):

        for attrValue in self.__attributes.itervalues():
            if attrValue[self.kGuiAttributeId] == attrId:
                return attrValue

        return None

    def boundingRect(self):
        extra = self.pen().width()

        return self.__group.boundingRect().normalized().adjusted(-extra, -extra, extra, extra)

    def shape(self):
        return QGraphicsItem.shape(self)

    def getLines(self, count, opposite=False):

        angleOffset = 25

        inputLines = []

        startAngle = QLineF(QPointF(0.0, 0.0), self.boundingRect().topRight()).angle() + angleOffset
        endAngle = QLineF(QPointF(0.0, 0.0), self.boundingRect().topLeft()).angle() - angleOffset

        if opposite:
            startAngle = QLineF(QPointF(0.0, 0.0), self.boundingRect().bottomLeft()).angle() + angleOffset
            endAngle = QLineF(QPointF(0.0, 0.0), self.boundingRect().bottomRight()).angle() - angleOffset

        step = (endAngle - startAngle) / (count - 1)

        for x in range(0, count):
            tLine = QLineF(QPointF(0.0, 0.0), QPointF(0, 100))
            tLine.setAngle(startAngle)
            inputLines.append(tLine)

            startAngle += step

        return inputLines

    def getPoints(self, count, opposite=False):
        result = []

        line = QLineF(self.__polygon.boundingRect().topLeft(), self.__polygon.boundingRect().topRight())

        if opposite:
            line = QLineF(self.__polygon.boundingRect().bottomLeft(), self.__polygon.boundingRect().bottomRight())

        step = 1.0 / (count + 1)
        currentStep = step

        for x in range(0, count):
            result.append(line.pointAt(currentStep))
            currentStep += step

        return result

    def paint(self, painter, option, widget=None):

        painter.setPen(self.pen())
        painter.setBrush(EDraw.EColor.DefaultTitleColor)

        painter.drawRoundedRect(self.__polygon.boundingRect(), 3, 3)

        painter.setPen(EDraw.EColor.DefaultTitleTextColor)
        painter.drawText(self.__polygon.boundingRect(), Qt.AlignCenter, self.Name)

        for connSlot, connData in self.__attributes.iteritems():
            if connData[self.kGuiAttributeId] != self.__muted and connData[self.kGuiAttributeId] not in self.__hiddenAttributes.keys():
                painter.drawPolygon(connSlot)

        painter.setBrush(Qt.NoBrush)
Ejemplo n.º 53
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)

        """
Ejemplo n.º 54
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)
Ejemplo n.º 55
0
 def _paintLine(self, painter, line):
     polyline = QPolygonF()
     for point in line:
         polyline.append(self.toCanvasCoordinates(point) - self.pos())
     painter.drawPolyline(polyline)
Ejemplo n.º 56
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() )
Ejemplo n.º 57
0
from util import *
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.