Ejemplo n.º 1
0
    def _get_icon(self, node, obj, is_expanded=False):
        """Returns the index of the specified object icon."""
        if True:
            return QtGui.QIcon()

        icon_name = node.get_icon(obj, is_expanded)
        if isinstance(icon_name, str):
            icon = STD_ICON_MAP.get(icon_name)

            if icon is not None and self.proxy_is_active:
                return self.get_widget().style().standardIcon(icon)

            path = node.get_icon_path(obj)
            if isinstance(path, str):
                path = [path, node]
            else:
                path.append(node)
            # resource_manager.locate_image( icon_name, path )
            reference = None
            if reference is None:
                return QtGui.QIcon()
            file_name = reference.filename
        else:
            # Assume it is an ImageResource, and get its file name directly:
            file_name = icon_name.absolute_path

        return QtGui.QIcon(pixmap_cache(file_name))
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super(QtViewer3d, self).__init__(*args, **kwargs)
        self._lock_rotation = False
        self._lock_zoom = False
        self._drawbox = None
        self._zoom_area = False
        self._select_area = False
        self._inited = False
        self._leftisdown = False
        self._middleisdown = False
        self._rightisdown = False
        self._selection = None
        self._drawtext = True
        self._select_pen = QtGui.QPen(QtGui.QColor(0, 0, 0), 2)
        self._callbacks = {
            'key_pressed': [],
            'mouse_dragged': [],
            'mouse_scrolled': [],
            'mouse_moved': [],
            'mouse_pressed': [],
            'mouse_released': [],
        }
        self.proxy = None
        self._last_code = None

        # enable Mouse Tracking
        self.setMouseTracking(True)
        # Strong focus
        self.setFocusPolicy(Qt.WheelFocus)

        # required for overpainting the widget
        self.setAttribute(Qt.WA_PaintOnScreen)
        self.setAttribute(Qt.WA_NoSystemBackground)
        self.setAutoFillBackground(False)
Ejemplo n.º 3
0
 def _get_brush(self, color):
     """Get brush associated to a color."""
     if isinstance(color, list) or isinstance(color, tuple):
         q_color = QtGui.QColor(*color)
     else:
         q_color = QtGui.QColor(color)
     return QtGui.QBrush(q_color)
Ejemplo n.º 4
0
    def _create_item(self, nid, node, obj, index=None):
        """ Create  a new TreeWidgetItem as per word_wrap policy.

        Index is the index of the new node in the parent:
        None implies append the child to the end.
        """
        if index is None:
            cnid = QtGui.QTreeWidgetItem(nid)
        else:
            cnid = QtGui.QTreeWidgetItem()
            nid.insertChild(index, cnid)

        cnid.setText(0, node.get_label(obj))
        cnid.setIcon(0, self._get_icon(node, obj))
        cnid.setToolTip(0, node.get_tooltip(obj))
        self._set_column_labels(cnid, node.get_column_labels(obj))

        color = node.get_background(obj)
        if color:
            cnid.setBackground(0, self._get_brush(color))
        color = node.get_foreground(obj)
        if color:
            cnid.setForeground(0, self._get_brush(color))

        return cnid
Ejemplo n.º 5
0
    def set_color_default(self, color_default):
        self.color_default = get_cached_qcolor(color_default)

        self.pen_default = QtGui.QPen(self.color_default)
        self.pen_default.setWidthF(self.line_width)

        self.pen_dragging = QtGui.QPen(self.color_default)
        self.pen_dragging.setStyle(QtCore.Qt.DashLine)
        self.pen_dragging.setWidthF(self.line_width)
Ejemplo n.º 6
0
    def init(self, view_items):
        default_items = []
        self.paths = [QtGui.QPainterPath(), QtGui.QPainterPath()]

        default_items.append(
            PainterPathPlotItem(self.paths[0], pen=self.pen_down))
        default_items.append(
            PainterPathPlotItem(self.paths[1], pen=self.pen_up))
        self.plot = default_items + view_items
Ejemplo n.º 7
0
    def parseTransform(self, e):
        """ Based on simpletrasnform.py by from 
        Jean-Francois Barraud, [email protected]

        """
        t = QtGui.QTransform()

        if isinstance(e, EtreeElement):
            trans = e.attrib.get('transform', '').strip()
        else:
            trans = e  # e is a string of the previous transform

        if not trans:
            return t

        m = re.match(
            "(translate|scale|rotate|skewX|skewY|matrix)\s*\(([^)]*)\)\s*,?",
            trans)
        if m is None:
            return t

        name, args = m.group(1), m.group(2).replace(',', ' ').split()

        if name == "translate":
            dx = float(args[0])
            dy = len(args) == 2 and float(args[1]) or dx
            t.translate(dx, dy)

        elif name == "scale":
            sx = float(args[0])
            sy = len(args) == 2 and float(args[1]) or sx
            t.scale(sx, sy)

        elif name == "rotate":
            if len(args) == 1:
                cx, cy = (0, 0)
            else:
                cx, cy = map(float, args[1:])

            t.translate(cx, cy)
            t.rotate(float(args[0]))
            t.translate(-cx, -cy)

        elif name == "skewX":
            t.shear(math.tan(float(args[0]) * math.pi / 180.0), 0)

        elif name == "skewY":
            t.shear(0, math.tan(float(args[0]) * math.pi / 180.0))

        elif name == "matrix":
            t = t * QtGui.QTransform(*map(float, args))

        if m.end() < len(trans):
            t = self.parseTransform(trans[m.end():]) * t

        return t
Ejemplo n.º 8
0
    def paintEvent(self, event):
        if self._inited:
            self._display.Context.UpdateCurrentViewer()
            # important to allow overpainting of the OCC OpenGL context in Qt
            self.swapBuffers()

        if self._drawbox:
            self.makeCurrent()
            painter = QtGui.QPainter(self)
            painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 0), 1))
            rect = QtCore.QRect(*self._drawbox)
            painter.drawRect(rect)
            painter.end()
            self.doneCurrent()
Ejemplo n.º 9
0
    def leftMouseButtonPress(self, event):
        # get item which we clicked on
        item = self.getItemAtClick(event)

        # we store the position of last LMB click
        point = self.mapToScene(event.pos())
        self.proxy.lastLmbClickScenePos = Point2D(x=point.x(), y=point.y())

        # logic
        if isinstance(item, QNodeItem) or isinstance(item, QEdgeItem) or item is None:
            if event.modifiers() & QtCore.Qt.ShiftModifier:
                event.ignore()
                fake_event = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress,
                                               event.localPos(),
                                               event.screenPos(),
                                               QtCore.Qt.LeftButton,
                                               event.buttons() | QtCore.Qt.LeftButton,
                                               event.modifiers() | QtCore.Qt.ControlModifier)
                super().mousePressEvent(fake_event)
                return

        if isinstance(item, QNodeSocket):
            if self.proxy.edgeEditMode == EdgeEditMode.MODE_NOOP:
                self.proxy.edgeEditMode = EdgeEditMode.MODE_EDGE_DRAG
                self.proxy.edgeDragStart(item.proxy if item is not None else None)
                return

        if self.proxy.edgeEditMode == EdgeEditMode.MODE_EDGE_DRAG:
            res = self.proxy.edgeDragEnd(item)
            self.proxy.edgeEditMode = EdgeEditMode.MODE_NOOP
            if res:
                return

        if item is None:
            if event.modifiers() & QtCore.Qt.ControlModifier:
                self.proxy.edgeEditMode = EdgeEditMode.MODE_EDGE_CUT
                fake_event = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease,
                                               event.localPos(),
                                               event.screenPos(),
                                               QtCore.Qt.LeftButton,
                                               QtCore.Qt.NoButton,
                                               event.modifiers())
                super().mouseReleaseEvent(fake_event)
                QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.CrossCursor)
                return
            else:
                self.proxy.rubberBandDraggingRectangle = True

        super().mousePressEvent(event)
    def init_widget(self):
        """ Initialize the underlying widget.
        """
        super(QtNodeGraphicsScene, self).init_widget()
        d = self.declaration
        self.pen_light = QtGui.QPen(QtGui.QColor.fromRgba(d.color_light.argb))
        self.pen_light.setWidth(1)
        self.pen_dark = QtGui.QPen(QtGui.QColor.fromRgba(d.color_dark.argb))
        self.pen_dark.setWidth(2)

        self.show_background = d.show_background
        self.background_grid_size = d.background_grid_size
        self.background_grid_squares = d.background_grid_squares
        self.color_light = d.color_light
        self.color_dark = d.color_dark
Ejemplo n.º 11
0
    def transform(self, path):
        """ Apply the device output transform to the given path. This
        is used by other plugins that may need to display or work with
        tranformed output.

        Parameters
        ----------
            path: QPainterPath
                Path to transform

        Returns
        -------
            path: QPainterPath

        """
        config = self.config

        t = QtGui.QTransform()

        #: Order matters!
        if config.scale:
            #: Do final output scaling
            t.scale(*config.scale)

        if config.rotation:
            #: Do final output rotation
            t.rotate(config.rotation)

        #: TODO: Translate back to 0,0 so all coordinates are positive
        path = path * t

        return path
 def _get_color(self, color):
     """ Returns a QColor built from a Pygments color string.
     """
     qcolor = QtGui.QColor()
     qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16),
                   int(color[4:6], base=16))
     return qcolor
Ejemplo n.º 13
0
    def _create_copy(self):
        """ Creates a copy of the original graphic applying the given 
        transforms 
        
        """
        bbox = self.path.boundingRect()

        # Create the base copy
        t = QtGui.QTransform()

        t.scale(
            self.scale[0] * (self.mirror[0] and -1 or 1),
            self.scale[1] * (self.mirror[1] and -1 or 1),
        )

        # Rotate about center
        if self.rotation != 0:
            c = bbox.center()
            t.translate(-c.x(), -c.y())
            t.rotate(self.rotation)
            t.translate(c.x(), c.y())

        # Apply transform
        path = self.path * t

        # Add weedline to copy
        if self.copy_weedline:
            self._add_weedline(path, self.copy_weedline_padding)

        # Apply ordering to path
        # this delegates to objects in the ordering module
        # TODO: Should this be done via plugins?
        OrderingHandler = ordering.REGISTRY.get(self.order)
        if OrderingHandler:
            path = OrderingHandler().order(self, path)

        # If it's too big we have to scale it
        w, h = path.boundingRect().width(), path.boundingRect().height()
        available_area = self.material.available_area

        #: This screws stuff up!
        if w > available_area.width() or h > available_area.height():

            # If it's too big an auto scale is enabled, resize it to fit
            if not self.auto_scale:
                raise JobError("Image is too large to fit on the material")
            sx, sy = 1, 1
            if w > available_area.width():
                sx = available_area.width() / w
            if h > available_area.height():
                sy = available_area.height() / h
            s = min(sx, sy)  # Fit to the smaller of the two
            path = self.path * QtGui.QTransform.fromScale(s, s)

        # Move to bottom left
        p = path.boundingRect().bottomRight()

        path = path * QtGui.QTransform.fromTranslate(-p.x(), -p.y())

        return path
Ejemplo n.º 14
0
    def __init__(self, parent, delimiters, entries, entries_updater):

        super(QtGui.QCompleter, self).__init__(parent)

        self.delimiters = delimiters
        if isinstance(parent, QtGui.QLineEdit):
            self.text_getter = parent.text
            self.cursor_pos = parent.cursorPosition
            self.insert_text = parent.insert
            parent.textChanged[str].connect(self.text_changed)
            self.completionNeeded.connect(self.complete)
        elif isinstance(parent, QtGui.QTextEdit):
            parent.textChanged.connect(self.text_changed)
            self.cursor_pos = lambda: parent.textCursor().position()
            self.insert_text =\
                lambda text: parent.textCursor().insertText(text)
            self.text_getter = parent.toPlainText
            self.completionNeeded.connect(self._text_edit_complete)
        else:
            msg = 'Parent of QtCompleter must QLineEdit or QTextEdit, not {}'
            raise ValueError(msg.format(parent))

        self.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.setModel(QtGui.QStringListModel(entries, self))

        self.activated[str].connect(self.complete_text)
        self.setWidget(parent)

        self._upddate_entries = True
        self._popup_active = False
        self.entries_updater = entries_updater
Ejemplo n.º 15
0
    def parseTransform(self, e):
        t = QtGui.QTransform()
        # transforms don't apply to the root svg element, but we do need to
        # take into account the viewBox there
        if self.isParentSvg:
            viewBox = e.attrib.get('viewBox', None)
            if viewBox is not None:
                (x, y, innerWidth,
                 innerHeight) = map(self.parseUnit, re.split("[ ,]+", viewBox))

                if x != 0 or y != 0:
                    raise ValueError(
                        "viewBox '%s' needs to be translated "
                        "because is not at the origin. "
                        "See https://github.com/codelv/inkcut/issues/69" %
                        viewBox)

                outerWidth, outerHeight = map(self.parseUnit, (e.attrib.get(
                    'width', None), e.attrib.get('height', None)))
                if outerWidth is not None and outerHeight is not None:
                    t.scale(outerWidth / innerWidth, outerHeight / innerHeight)
        else:
            x, y = map(self.parseUnit,
                       (e.attrib.get('x', 0), e.attrib.get('y', 0)))
            t.translate(x, y)

        return t
Ejemplo n.º 16
0
 def middleMouseButtonPress(self, event):
     release_event = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease,
                                       event.localPos(),
                                       event.screenPos(),
                                       QtCore.Qt.LeftButton,
                                       QtCore.Qt.NoButton,
                                       event.modifiers())
     super().mouseReleaseEvent(release_event)
     self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
     fake_event = QtGui.QMouseEvent(event.type(),
                                    event.localPos(),
                                    event.screenPos(),
                                    QtCore.Qt.LeftButton,
                                    event.buttons() | QtCore.Qt.LeftButton,
                                    event.modifiers())
     super().mousePressEvent(fake_event)
Ejemplo n.º 17
0
    def _insert_node(self, nid, index, node, obj):
        """ Inserts a new node before a specified index into the children of
        the specified node.
        """

        cnid = self._create_item(nid, node, obj, index)

        has_children = self._has_children(node, obj)
        self._set_node_data(cnid, (False, node, obj))
        self._map.setdefault(id(obj), []).append(
            (node.get_children_id(obj), cnid))
        self._add_listeners(node, obj)

        # Automatically expand the new node (if requested):
        if has_children:
            if node.can_auto_open(obj):
                cnid.setExpanded(True)
            else:
                # Qt only draws the control that expands the tree if there is a
                # child.  As the tree is being populated lazily we create a
                # dummy that will be removed when the node is expanded for the
                # first time.
                cnid._dummy = QtGui.QTreeWidgetItem(cnid)

        # Return the newly created node:
        return cnid
 def _get_format_from_style(self, token, style):
     """ Returns a QTextCharFormat for token by reading a Pygments style.
     """
     result = QtGui.QTextCharFormat()
     try:
         token_style = style.style_for_token(token)
     except KeyError:
         return result
     for key, value in token_style.items():
         if value:
             if key == 'color':
                 result.setForeground(self._get_brush(value))
             elif key == 'bgcolor':
                 result.setBackground(self._get_brush(value))
             elif key == 'bold':
                 result.setFontWeight(QtGui.QFont.Bold)
             elif key == 'italic':
                 result.setFontItalic(True)
             elif key == 'underline':
                 result.setUnderlineStyle(
                     QtGui.QTextCharFormat.SingleUnderline)
             elif key == 'sans':
                 result.setFontStyleHint(QtGui.QFont.SansSerif)
             elif key == 'roman':
                 result.setFontStyleHint(QtGui.QFont.Times)
             elif key == 'mono':
                 result.setFontStyleHint(QtGui.QFont.TypeWriter)
     return result
Ejemplo n.º 19
0
    def create_widget(self, parent):
        """ Create the QListView widget.

        """
        # Create the list model and accompanying controls:
        widget = QtGui.QListWidget(parent)
        self._set_items(self.items, widget)
        if self.multiselect:
            mode = QtGui.QAbstractItemView.ExtendedSelection
        else:
            mode = QtGui.QAbstractItemView.SingleSelection
        widget.setSelectionMode(mode)
        # This is necessary to ensure that the first selection is correctly
        # dispatched.
        if self.items:
            self._guard ^= INDEX_GUARD
            self.selected_index = 0
            self.selected_indexes = [0]
            self.selected_item = self.items[0]
            self.selected_items = [self.items[0]]
            widget.setCurrentItem(widget.item(0),
                                  QtGui.QItemSelectionModel.ClearAndSelect)
            self._guard ^= INDEX_GUARD
        widget.itemSelectionChanged.connect(self.on_selection)
        return widget
Ejemplo n.º 20
0
 def create_widget(self, parent):
     """ Finishes initializing the editor by creating the underlying toolkit
         widget.
     """
     widget = QtGui.QTextEdit(parent)
     widget.setReadOnly(True)
     widget.setHtml(self.text)
     return widget
Ejemplo n.º 21
0
    def __init__(self, parent, delimiters, entries, entries_updater):

        self.delimiters = delimiters

        super(CompleterLineEdit, self).__init__(parent)
        self.textChanged[str].connect(self.text_changed)
        self.completer = QtGui.QCompleter(self)
        self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.completer.setModel(QtGui.QStringListModel(entries,self.completer))
        
        self.completionNeeded.connect(self.completer.complete)
        self.completer.activated[str].connect(self.complete_text)
        self.completer.setWidget(self)

        self._upddate_entries = True
        self.editingFinished.connect(self.on_editing_finished)
        self.entries_updater = entries_updater
 def _get_brush(self, color):
     """ Returns a brush for the color.
     """
     result = self._brushes.get(color)
     if result is None:
         qcolor = self._get_color(color)
         result = QtGui.QBrush(qcolor)
         self._brushes[color] = result
     return result
Ejemplo n.º 23
0
    def initUI(self):
        grid = QtGui.QGridLayout()

        self.start_button = QtGui.QPushButton("Start")
        grid.addWidget(self.start_button, 0, 0)
        self.start_button.clicked.connect(self.handle_start_dataflow)

        self.stop_button = QtGui.QPushButton("Stop")
        grid.addWidget(self.stop_button, 0, 1)
        self.stop_button.clicked.connect(self.handle_stop_dataflow)
        self.stop_button.setEnabled(False)

        self.close_button = QtGui.QPushButton("Close")
        grid.addWidget(self.close_button, 0, 3)
        self.close_button.clicked.connect(self.handle_unload_dataflow)

        self.setLayout(grid)
        self.setWindowTitle('Dataflow')
Ejemplo n.º 24
0
 def middleMouseButtonRelease(self, event):
     fake_event = QtGui.QMouseEvent(event.type(),
                                    event.localPos(),
                                    event.screenPos(),
                                    QtCore.Qt.LeftButton,
                                    event.buttons() & ~QtCore.Qt.LeftButton,
                                    event.modifiers())
     super().mouseReleaseEvent(fake_event)
     self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
Ejemplo n.º 25
0
    def calcPath(self):
        edge_type = self.proxy.edge_type
        if edge_type == EdgeType.EDGE_TYPE_DIRECT:
            path = QtGui.QPainterPath(
                QtCore.QPointF(self.proxy.pos_source.x,
                               self.proxy.pos_source.y))
            path.lineTo(self.proxy.pos_destination.x,
                        self.proxy.pos_destination.y)
            return path

        elif edge_type == EdgeType.EDGE_TYPE_BEZIER:
            s = self.proxy.pos_source
            d = self.proxy.pos_destination
            dist = (d.x - s.x) * 0.5

            cpx_s = +dist
            cpx_d = -dist
            cpy_s = 0
            cpy_d = 0

            if self.proxy.start_socket is not None:
                sspos = self.proxy.start_socket.socket_position

                if (s.x > d.x and sspos in (SocketPosition.RIGHT_TOP, SocketPosition.RIGHT_BOTTOM)) \
                        or (s.x < d.x and sspos in (SocketPosition.LEFT_BOTTOM, SocketPosition.LEFT_TOP)):
                    cpx_d *= -1
                    cpx_s *= -1

                    cpy_d = ((s.y - d.y) / math.fabs(
                        (s.y - d.y) if (s.y - d.y) != 0 else 0.00001)
                             ) * self.proxy.edge_roundness
                    cpy_s = ((d.y - s.y) / math.fabs(
                        (d.y - s.y) if (d.y - s.y) != 0 else 0.00001)
                             ) * self.proxy.edge_roundness

            path = QtGui.QPainterPath(
                QtCore.QPointF(self.proxy.pos_source.x,
                               self.proxy.pos_source.y))
            path.cubicTo(s.x + cpx_s, s.y + cpy_s, d.x + cpx_d, d.y + cpy_d,
                         self.proxy.pos_destination.x,
                         self.proxy.pos_destination.y)

            return path
Ejemplo n.º 26
0
 def window(self):
     """ Return the main UI window or a dialog if it wasn't made yet 
     (during loading) 
     
     """
     try:
         ui = self.get_plugin('enaml.workbench.ui')
         return ui.window.proxy.widget
     except:
         return QtGui.QDialog()
Ejemplo n.º 27
0
    def startDrag(self, actions):
        """ Reimplemented to start the drag of a tree widget item.

        """
        nid = self.currentItem()
        if nid is None:
            return

        self._dragging = nid

        _, node, obj = self._controller._get_node_data(nid)

        # Convert the item being dragged to MIME data.
        drag_object = node.get_drag_object(obj)
        md = PyMimeData.coerce(drag_object)

        # Render the item being dragged as a pixmap.
        nid_rect = self.visualItemRect(nid)
        rect = nid_rect.intersected(self.viewport().rect())
        pm = QtGui.QPixmap(rect.size())
        pm.fill(self.palette().base().color())
        painter = QtGui.QPainter(pm)

        option = self.viewOptions()
        option.state |= QtWidgets.QStyle.State_Selected
        option.rect = QtCore.QRect(nid_rect.topLeft() -
                                   rect.topLeft(), nid_rect.size())
        self.itemDelegate().paint(painter, option, self.indexFromItem(nid))

        painter.end()

        # Calculate the hotspot so that the pixmap appears on top of the
        # original item.
        hspos = self.viewport().mapFromGlobal(QtGui.QCursor.pos()) - \
            nid_rect.topLeft()

        # Start the drag.
        drag = QtGui.QDrag(self)
        drag.setMimeData(md)
        drag.setPixmap(pm)
        drag.setHotSpot(hspos)
        drag.exec_(actions)
Ejemplo n.º 28
0
    def create_widget(self, parent):
        """Finishes initializing by creating the underlying toolkit widget.

        """
        widget = QtGui.QLineEdit(parent)
        self._completer = QDelimitedCompleter(widget, self.delimiters,
                                              self.entries,
                                              self.entries_updater)
        widget.setText(self.text)
        widget.textEdited.connect(self.update_object)
        return widget
Ejemplo n.º 29
0
 def move_path(self):
     """ Returns the path the head moves when not cutting 
     
     """
     # Compute the negative
     path = QtGui.QPainterPath()
     for i in range(self.model.elementCount()):
         e = self.model.elementAt(i)
         if e.isMoveTo():
             path.lineTo(e.x, e.y)
         else:
             path.moveTo(e.x, e.y)
     return path
Ejemplo n.º 30
0
    def _observe_selection(self, change):
        """ Handles the **selection** event.
        """
        selection = change['value']
        node_control = self._node_control
        try:
            tree = self.get_widget()
            if (not isinstance(selection, basestring)
                    and isinstance(selection, collections.Iterable)):

                item_selection = QtGui.QItemSelection()
                for sel in selection:
                    item = node_control._object_info(sel)[2]
                    idx = tree.indexFromItem(item)
                    item_selection.append(QtGui.QItemSelectionRange(idx))

                tree.selectionModel().select(
                    item_selection, QtGui.QItemSelectionModel.ClearAndSelect)
            else:
                tree.setCurrentItem(node_control._object_info(selection)[2])
        except Exception:
            raise