def paintEvent(self, event):
        """
        Paint the graph.

        :param event:
        :return:
        """

        painter = QPainter(self.viewport())

        # scrollbar values
        current_x = self.horizontalScrollBar().value()
        current_y = self.verticalScrollBar().value()
        # coord translation
        # (0, 0) -> middle of the page
        painter.translate(self.width() / 2 - current_x,
                          self.height() / 2 - current_y)

        painter.setFont(self.workspace.disasm_font)

        topleft_point = self._to_graph_pos(QPoint(0, 0))
        bottomright_point = self._to_graph_pos(
            QPoint(self.width(), self.height()))

        self._draw_edges(painter, topleft_point, bottomright_point)
        self._draw_nodes(painter, topleft_point, bottomright_point)
Beispiel #2
0
    def paint(self, painter, point):
        painter.save()

        size = QSize(self.width(), self.height())
        painter.setBrush(self.bg_color)
        painter.drawRoundedRect(QRect(point, size), BLOCK_RADIUS, BLOCK_RADIUS)

        # Рисуем столбцы
        p = QPoint(point) + QPoint(0, BLOCK_RADIUS)
        for c in self.columns:
            p += QPoint(BLOCK_RADIUS, 0)
            c.paint(painter, p)
            p += QPoint(c.width(), 0)

        # Рисуем левые порты
        if len(self.left_pins):
            p = QPoint(point)
            p += QPoint(0, size.height() / (len(self.left_pins) + 1))
            for lp in self.left_pins:
                lp.paint(painter, p)
                p += QPoint(0, size.height() / (len(self.left_pins) + 1))

        # Рисуем правые порты
        if len(self.right_pins):
            p = QPoint(point)
            p += QPoint(size.width(),
                        size.height() / (len(self.right_pins) + 1))
            for rp in self.right_pins:
                rp.paint(painter, p)
                p += QPoint(0, size.height() / (len(self.right_pins) + 1))

        painter.restore()
    def save_image_to(self, path):

        TOP_MARGIN = 50
        LEFT_MARGIN = 50

        # Determine the size of the entire graph
        graph_size = self._graph_size()

        image_size = QSize(graph_size.width() + LEFT_MARGIN * 2,
                           graph_size.height() + TOP_MARGIN * 2
                           )

        image = QImage(image_size, QImage.Format_ARGB32)
        image.fill(Qt.white)  # white background

        painter = QPainter(image)
        painter.translate(TOP_MARGIN, LEFT_MARGIN)
        painter.setRenderHint(QPainter.TextAntialiasing)
        self._paint(painter,
                    QPoint(-TOP_MARGIN, -LEFT_MARGIN),
                    QPoint(image_size.width(), image_size.height())
                    )
        painter.end()

        image.save(path)
Beispiel #4
0
    def __init__(self, directory, *args, **kwargs):
        self.directory = directory
        self.figures = []

        if 'json_dict' in kwargs:
            self.file_name = kwargs['json_dict']['file_name']

            if 'draw_scale' in kwargs['json_dict']:
                self.draw_scale = kwargs['json_dict']['draw_scale']
            else:
                self.draw_scale = 1.0

            if 'draw_offset' in kwargs['json_dict']:
                self.draw_offset = dict2qpoint(kwargs['json_dict']['draw_offset'])
            else:
                self.draw_offset = QPoint()

            self.figures = [Rectangle(figure=figure_dict['rect']) if figure_dict.keys()[0] == 'rect' else
                            Circle(figure=figure_dict['circle']) if figure_dict.keys()[0] == 'circle' else
                            Polygon(figure=figure_dict['polygon']) for figure_dict in kwargs['json_dict']['figures']]
        else:
            self.draw_scale = 1.0
            self.draw_offset = QPoint()
            self.file_name = kwargs['file_name']

        self.image = None
def QtRectToPoly(rect):
    x1, y1, x2, y2 = rect.getCoords()
    poly = QPolygon()
    poly.push_back(QPoint(x1, y1))
    poly.push_back(QPoint(x2, y1))
    poly.push_back(QPoint(x2, y2))
    poly.push_back(QPoint(x1, y2))
    return poly
Beispiel #6
0
    def testConstructorQPoint(self):
        topLeft = QPoint(3, 0)
        bottomRight = QPoint(0, 3)

        rect1 = QRect(topLeft, bottomRight)
        rect2 = QRect(topLeft, bottomRight)

        self.assertEqual(rect1, rect2)
Beispiel #7
0
    def testFunctionUnit(self):
        r = QRegion(0, 0, 10, 10)
        r2 = QRegion(5, 5, 10, 10)
 
        ru = r.united(r2)
        self.assert_(ru.contains(QPoint(0,0)))
        self.assert_(ru.contains(QPoint(5,5)))
        self.assert_(ru.contains(QPoint(10,10)))
        self.assert_(ru.contains(QPoint(14,14)))
Beispiel #8
0
 def test_getDict(self):
     r = Rectangle(QPoint(10, 20), QPoint(30, 40))
     self.assertEqual(r.getDict(),
                      {'rect': {
                          'x1': 10,
                          'y1': 20,
                          'x2': 30,
                          'y2': 40
                      }})
Beispiel #9
0
 def _calculateMeasures(self):
     self._hor_margin = 4
     self._ver_margin = (self.height() - self._drop_icon.height()) // 2
     self._drop_icon_pos = QPoint(
         self.width() - self._drop_icon.width() - self._hor_margin,
         self._ver_margin)
     self._grad_start = QPoint(self.width() // 2,
                               self.height())  # bottom-up gradient
     self._grad_end = QPoint(self.width() // 2, 0)
Beispiel #10
0
    def paint(self, painter, point):
        painter.save()

        p = QPoint(point)
        for b in self.blocks:
            b.paint(painter, p)
            p += QPoint(0, 5)
            p += QPoint(0, b.height())

        painter.restore()
Beispiel #11
0
def intersection(p1, p2, q1, q2):
    a1 = p2.y() - p1.y()
    b1 = p1.x() - p2.x()
    c1 = a1 * p1.x() + b1 * p1.y()
    a2 = q2.y() - q1.y()
    b2 = q1.x() - q2.x()
    c2 = a2 * q1.x() + b2 * q1.y()
    det = a1 * b2 - a2 * b1
    if not eq(det, 0):
        return QPoint((b2 * c1 - b1 * c2) / det, (a1 * c2 - a2 * c1) / det)
    else:
        return QPoint()
Beispiel #12
0
 def animateWidget(self, widget, distance, direction):
     widget_anim = QPropertyAnimation(widget, "geometry")
     cur_geom = widget.geometry()
     next_geom = QRect(cur_geom)
     if direction == self.LEFT:
         next_geom.moveTo(widget.pos() - QPoint(distance, 0))
     elif direction == self.RIGHT:
         next_geom.moveTo(widget.pos() + QPoint(distance, 0))
     widget_anim.setDuration(self.ANIM_DURATION)
     widget_anim.setEasingCurve(self.EASING)
     widget_anim.setStartValue(cur_geom)
     widget_anim.setEndValue(next_geom)
     self._anim_grp.addAnimation(widget_anim)
Beispiel #13
0
    def __init__(self, *args, **kwargs):

        self.first_point = FirstPoint()
        self.second_point = SecondPoint()
        self.control = Control()

        self.p1 = QPoint()
        self.p2 = QPoint()

        Figure.__init__(self, self.first_point)
        if 'x1' in kwargs and 'y1' in kwargs:
            self.p1 = QPoint(kwargs['x1'], kwargs['y1'])
        if 'x2' in kwargs and 'y2' in kwargs:
            self.p2 = QPoint(kwargs['x2'], kwargs['y2'])
        if 'p1' in kwargs:
            self.p1 = kwargs['p1']
        if 'p2' in kwargs:
            self.p2 = kwargs['p2']
        if len(args) == 2:
            self.p1 = args[0]
            self.p2 = args[1]
        if len(args) == 4:
            self.p1 = QPoint(args[0], args[1])
            self.p2 = QPoint(args[2], args[3])

        if 'figure' in kwargs:
            self.p1 = QPoint(kwargs['figure']['x1'], kwargs['figure']['y1'])
            self.p2 = QPoint(kwargs['figure']['x2'], kwargs['figure']['y2'])
            self.state = self.control
    def _draw_nodes(self, painter, topleft_point, bottomright_point):

        # draw nodes
        for block in self.blocks:
            # optimization: don't paint blocks that are outside of the current range
            block_topleft_point = QPoint(block.x, block.y)
            block_bottomright_point = QPoint(block.x + block.width,
                                             block.y + block.height)
            if block_topleft_point.x() > bottomright_point.x(
            ) or block_topleft_point.y() > bottomright_point.y():
                continue
            elif block_bottomright_point.x() < topleft_point.x(
            ) or block_bottomright_point.y() < topleft_point.y():
                continue
            block.paint(painter)
Beispiel #15
0
    def _handle_i_edited(self, line, base, fmt, minval, maxval, field):
        msg = None
        text = line.text().replace(' ', '')

        if self._last_val_cache[line] == text:
            return

        try:
            val = int(text, base)
            if val > maxval:
                msg = "Exceeded max value of " + format(maxval, fmt)
            elif val < minval:
                msg = "Under min value of " + format(minval, fmt)
        except ValueError:
            msg = "Invalid format."
        except Exception:
            msg = "Unknown error."

        if msg is None:
            union = ValUnion()
            setattr(union, field, val)
            self._set_new_val(union)
        else:
            line.setStyleSheet("border: 1px solid red")
            line.setToolTip(msg)
            QtGui.QToolTip.showText(line.mapToGlobal(QPoint(0, 0)), msg)
Beispiel #16
0
    def paintEvent(self, pe):

        if self._drop_zones_shown:
            painter = QPainter(self.viewport(
            ))  # See documentation to know why I draw on the viewport
            painter.setFont(self._titles_font)
            vr = self.rect()

            nb_drop_zones = len(self._drop_zones_titles)

            subr = QRect(vr)
            subr.setHeight(vr.height() / nb_drop_zones)

            for i in range(nb_drop_zones):
                c = self._drop_zones_colors[i]

                text_pen = QPen()
                text_pen.setColor(inverse_colors(c))
                painter.setPen(text_pen)

                if i == self._selected_drop_zone:
                    # mainlog.debug("selected drop zone is {}".format(i))
                    c = c.lighter(200)
                painter.setBrush(c)

                subr.moveTop(int(i * vr.height() / nb_drop_zones))
                painter.drawRect(subr)
                painter.drawText(
                    QPoint(10, int((i + 0.5) * vr.height() / nb_drop_zones)),
                    self._drop_zones_titles[i])
            return None
        else:
            return super(AnimatedTableView, self).paintEvent(pe)
Beispiel #17
0
    def parseMarkdown(self):
        """
        Parse the Markdown stuff.
        """
        self.updateStructure()
        if self.sync is False:
            return

        y = self.web.page().mainFrame().scrollPosition().y()
        txt = self.editor.toPlainText().encode('utf-8')

        if txt is '' or None:
            return

        p = Popen([self.parser],
                  stdout=PIPE,
                  stdin=PIPE,
                  stderr=STDOUT,
                  shell=False)
        grep_stdout = p.communicate(input=txt)[0].decode('utf-8')
        path = QUrl.fromUserInput(os.getcwd() + os.sep)
        grep_stdout = grep_stdout.replace('img src=\"',
                                          'img src=\"' + path.toString())
        # Can't use baseUrl=path because external img will not be loaded
        # than :-/
        self.web.setHtml(grep_stdout)
        self.web.settings().setUserStyleSheetUrl(
            QUrl.fromLocalFile(os.getcwd() + os.sep + "/style.css"))
        if y:
            self.web.scroll(0, y)
            self.web.page().mainFrame().scroll(0, y)
            self.web.page().mainFrame().setScrollPosition(QPoint(0, y))
Beispiel #18
0
    def showRepr(self):
        '''Present a string of the parameters used to reproduce the current state of the
        widget used in the show() command.
        
        :Return: str
        '''
        reprDict = {}
        reprDict['dockable'] = self.isDockable()
        reprDict['floating'] = self.isFloating()
        reprDict['area'] = self.dockArea()
        #reprDict['allowedArea'] = ??
        if reprDict['dockable'] == True:
            dockCtrl = self.parent()
            pos = dockCtrl.mapToGlobal(QPoint(0, 0))
        else:
            pos = self.pos()
        sz = self.geometry().size()
        reprDict['x'] = pos.x()
        reprDict['y'] = pos.y()
        reprDict['width'] = sz.width()
        reprDict['height'] = sz.height()

        # Construct the repr show() string
        reprShowList = [
            '%s=%r' % (k, v) for k, v in reprDict.items() if v != None
        ]
        reprShowStr = 'show(%s)' % (', '.join(reprShowList))
        return reprShowStr
Beispiel #19
0
    def _show_completion(self):
        replacement_area, suggestions, quote = find_suggestions(
            self.text(), self.cursorPosition())

        if suggestions:
            # mainlog.debug("Suggestions are ..." + str(suggestions))

            self.replacement_area = replacement_area
            self.quote = quote

            p = self.mapToGlobal(QPoint(self.cursorPos().x(), self.height()))
            self.completion.set_possible_completions(suggestions)
            self.completion.move(p)

            self.completion.activateWindow()  # So that show works
            self.completion.show()
            self.completion.raise_()

            self.completion.items_view.setFocus(Qt.OtherFocusReason)
            self.completion.items_view.setCurrentIndex(
                self.completion.model.index(0, 0))
        else:
            self.replacement_area = None
            self.quote = False
            self.completion.set_possible_completions(None)
            self.completion.hide()

        # self.activateWindow()
        self.setFocus(Qt.OtherFocusReason)

        return suggestions
    def test_get_dict(self):

        c = Circle(QPoint(10, 10), QPoint(20, 10))

        self.assertEqual(
            c.getDict(), {
                'circle': {
                    'center': {
                        'x': c.center.x(),
                        'y': c.center.y()
                    },
                    'ctrl': {
                        'x': c.ctrl.x(),
                        'y': c.ctrl.y()
                    }
                }
            })
Beispiel #21
0
 def getPosPopup(self):
     pos = self.pos()
     pos1 = self.mapToGlobal(pos)
     pos2 = QPoint()
     cRect = self.cursorRect()
     pos2.setX(cRect.x())
     pos2.setY(cRect.y())
     return pos1 + pos2
Beispiel #22
0
 def getText(self, position):
     """Returns text of a label on given position if such exists, otherwise returns empty string"""
     if helpers.isItemAtPoint(position, self.mainLayout):
         item = helpers.itemAtPoint(position, self.mainLayout)
         if item.widget() != 0:
             position -= QPoint(item.widget().x(), item.widget().y())
             return item.widget().getText(position)
     return ''
Beispiel #23
0
 def update_spiral(self):
     # create a polygon providing the corner points of the spiral
     polygon = QPolygon()
     for i in xrange(self.window().width()):
         x = int(math.cos(i * 0.16) * i)
         y = int(math.sin(i * 0.16) * i)
         polygon.append(QPoint(x, y))
     return polygon
Beispiel #24
0
 def boundingRect(self):
     if self.angle == 0:
         return QRectF(0, 0, self.w, self.h)
     else:
         sideLen = self.w + self.h
         rect = QRectF(0, 0, 2 * sideLen, 2 * sideLen)
         rect.moveTo(QPoint(-sideLen, -sideLen))
         return rect
 def checkBoxRect(self, opt, editor):
     cb_option = QStyleOptionButton()
     style = QApplication.style()
     cb_rect = style.subElementRect(QStyle.SE_CheckBoxIndicator, cb_option,
                                    editor)
     cb_point = QPoint(
         opt.rect.x() + (opt.rect.width() - cb_rect.width()) / 2,
         opt.rect.y() + (opt.rect.height() - cb_rect.height()) / 2)
     return QRect(cb_point, cb_rect.size())
Beispiel #26
0
    def __getStarPair__(self, points, idx):
        """

        :param points: int
        :param idx: int
        :return: QPointF, QPointF
        """
        inner_angle = float(idx) / points * 2 * math.pi
        outer_angle = float(idx) / points * 2 * math.pi + math.pi / points
        inner_x = self.inner_rad * math.cos(inner_angle) + self.center[0]
        inner_y = self.inner_rad * math.sin(inner_angle) + self.center[1]
        outer_x = self.outer_rad * math.cos(outer_angle) + self.center[0]
        outer_y = self.outer_rad * math.sin(outer_angle) + self.center[1]

        inner_point = QPoint(inner_x, inner_y)
        outer_point = QPoint(outer_x, outer_y)

        return inner_point, outer_point
    def _draw_nodes(self, painter, topleft_point, bottomright_point):

        # draw nodes
        for block in self.blocks:

            # safety check
            if block.x is None or block.y is None:
                l.warning("Failed to assign coordinates to block %s.", block)
                continue

            # optimization: don't paint blocks that are outside of the current range
            block_topleft_point = QPoint(block.x, block.y)
            block_bottomright_point = QPoint(block.x + block.width, block.y + block.height)
            if block_topleft_point.x() > bottomright_point.x() or block_topleft_point.y() > bottomright_point.y():
                continue
            elif block_bottomright_point.x() < topleft_point.x() or block_bottomright_point.y() < topleft_point.y():
                continue
            block.paint(painter)
 def _show_built_content(self, thing_to_show):
     if self._last_shown_content is not None:
         self._last_shown_content.hide()
     self._last_shown_content = thing_to_show
     # Always stick it top left to make it easier for the user to know
     # where to put this gui, such that they can see both this one and the
     # built one.
     thing_to_show.move(QPoint(0, 0))
     self._last_shown_content.show()
    def mousePressEvent(self, mouse_event):
        if mouse_event.button() == Qt.RightButton:
            if self._spec_index is None:
                print("spec_index is None")
                print(self)
                print(self._running_providers)
                return
            pos = mouse_event.pos()
            items = [
                item for item in self.items(pos)
                if isinstance(item, NodeItem) and item._label.text()
            ]
            if len(items) != 1:
                print("wrong number of things",
                      [x._label.text() for x in items])
                return

            name = items[0]._label.text().rstrip('(default)').strip()
            if name not in self._spec_index.provider_names:
                print(name, "Not in list of providers")
                return
            provider = self._spec_index.providers[name]

            def start_trigger():
                # TODO: replace 'capability_server' with user provided server name
                service_name = '/{0}/start_capability'.format(
                    'capability_server')
                rospy.wait_for_service(service_name)
                start_capability = rospy.ServiceProxy(service_name,
                                                      StartCapability)
                start_capability(provider.implements, name)

            def stop_trigger():
                # TODO: replace 'capability_server' with user provided server name
                service_name = '/{0}/stop_capability'.format(
                    'capability_server')
                rospy.wait_for_service(service_name)
                stop_capability = rospy.ServiceProxy(service_name,
                                                     StopCapability)
                stop_capability(provider.implements)

            if name not in self._running_providers:
                trigger = start_trigger
                msg = "start => "
            else:
                trigger = stop_trigger
                msg = "stop => "

            menu = QMenu()
            action = menu.addAction(msg + name)
            action.triggered.connect(trigger)
            pos = mouse_event.globalPos()
            pos = QPoint(pos.x(), pos.y())
            menu.exec_(pos)
        else:
            InteractiveGraphicsView.mousePressEvent(self, mouse_event)
Beispiel #30
0
 def getCheckBoxRect(self, option):
     check_box_style_option = QStyleOptionButton()
     check_box_rect = QApplication.style().subElementRect(
         QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
     check_box_point = QPoint(
         option.rect.x() + option.rect.width() / 2 -
         check_box_rect.width() / 2,
         option.rect.y() + option.rect.height() / 2 -
         check_box_rect.height() / 2)
     return QRect(check_box_point, check_box_rect.size())