Пример #1
0
 def enableHoverEffect(self):
     e = QGraphicsDropShadowEffect()
     e.setEnabled(False)
     e.setBlurRadius(2 * _trackWidth)
     e.setColor(_hoverColor)
     e.setOffset(0, 0)
     self.setGraphicsEffect(e)
     self.setAcceptHoverEvents(True)
Пример #2
0
 def must_glow(widget_list):
     ' apply an glow effect to the widget '
     for glow, each_widget in enumerate(widget_list):
         try:
             if each_widget.graphicsEffect() is None:
                 glow = QGraphicsDropShadowEffect(self)
                 glow.setOffset(0)
                 glow.setBlurRadius(99)
                 glow.setColor(QColor(99, 255, 255))
                 each_widget.setGraphicsEffect(glow)
                 glow.setEnabled(True)
         except:
             pass
Пример #3
0
class HighlightEdit(QLineEdit):
    clicked = pyqtSignal(name="clicked")

    def __init__(self, parent):
        QLineEdit.__init__(self, parent)
        self._highlight_effect = QGraphicsDropShadowEffect(self)
        self._highlight_effect.setOffset(0.0)
        self._highlight_effect.setBlurRadius(5.0)
        self._highlight_effect.setColor(QColor(50, 50, 200))
        self.setGraphicsEffect(self._highlight_effect)
        self._highlight_effect.setEnabled(False)

        self.clear_button = QToolButton(self)
        self.clear_button.setIcon(QIcon.fromTheme("edit-clear", QIcon("icons/delete_icon.png")))
        self.clear_button.setCursor(Qt.ArrowCursor)
        self.clear_button.setStyleSheet("QToolButton { border: none; padding: 1.5px; }")
        icon_size = int(self.sizeHint().height() * 0.65)
        self.clear_button.setIconSize(QSize(icon_size, icon_size))
        self.clear_button.clicked.connect(self.clear)
        # self.clear_button.hide()

        # some padding stuff
        frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
        self.setStyleSheet(
            "QLineEdit {{ padding-right: {}px; }} ".format(self.clear_button.sizeHint().width() + frameWidth)
        )

    # create a signal on doubleclick events
    def mouseDoubleClickEvent(self, ev):
        ev.accept()
        self.clicked.emit()

    # fix up the clear button positioning
    def resizeEvent(self, ev):
        sz = self.clear_button.sizeHint()

        frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
        self.clear_button.move(
            self.rect().right() - frameWidth - sz.width(), (self.rect().bottom() + 1 - sz.height()) / 2
        )

    # a slot for turning the graphics effect on and off
    @pyqtSlot(bool)
    def highlight(self, val):
        self._highlight_effect.setEnabled(val)
Пример #4
0
class ChannelAnchor(QGraphicsRectItem):
    """
    A rectangular Channel Anchor indicator.
    """
    def __init__(self, parent=None, channel=None, rect=None, **kwargs):
        QGraphicsRectItem.__init__(self, **kwargs)
        self.setAcceptHoverEvents(True)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__channel = None

        if rect is None:
            rect = QRectF(0, 0, 20, 20)

        self.setRect(rect)

        if channel:
            self.setChannel(channel)

        self.__shadow = QGraphicsDropShadowEffect(blurRadius=5,
                                                  offset=QPointF(0, 0))
        self.setGraphicsEffect(self.__shadow)
        self.__shadow.setEnabled(False)

    def setChannel(self, channel):
        """
        Set the channel description.
        """
        if channel != self.__channel:
            self.__channel = channel

            if hasattr(channel, "description"):
                self.setToolTip(channel.description)
            # TODO: Should also include name, type, flags, dynamic in the
            #       tool tip as well as add visual clues to the anchor

    def channel(self):
        """
        Return the channel description.
        """
        return self.__channel

    def hoverEnterEvent(self, event):
        self.__shadow.setEnabled(True)
        QGraphicsRectItem.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        self.__shadow.setEnabled(False)
        QGraphicsRectItem.hoverLeaveEvent(self, event)
Пример #5
0
class ChannelAnchor(QGraphicsRectItem):
    """
    A rectangular Channel Anchor indicator.
    """
    def __init__(self, parent=None, channel=None, rect=None, **kwargs):
        QGraphicsRectItem.__init__(self, **kwargs)
        self.setAcceptHoverEvents(True)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__channel = None

        if rect is None:
            rect = QRectF(0, 0, 20, 20)

        self.setRect(rect)

        if channel:
            self.setChannel(channel)

        self.__shadow = QGraphicsDropShadowEffect(blurRadius=5,
                                                  offset=QPointF(0, 0))
        self.setGraphicsEffect(self.__shadow)
        self.__shadow.setEnabled(False)

    def setChannel(self, channel):
        """
        Set the channel description.
        """
        if channel != self.__channel:
            self.__channel = channel

            if hasattr(channel, "description"):
                self.setToolTip(channel.description)
            # TODO: Should also include name, type, flags, dynamic in the
            #       tool tip as well as add visual clues to the anchor

    def channel(self):
        """
        Return the channel description.
        """
        return self.__channel

    def hoverEnterEvent(self, event):
        self.__shadow.setEnabled(True)
        QGraphicsRectItem.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        self.__shadow.setEnabled(False)
        QGraphicsRectItem.hoverLeaveEvent(self, event)
Пример #6
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.group0 = QGroupBox()
        self.group0.setTitle(' Source ')
        self.source, self.infile = QComboBox(), QLineEdit(path.expanduser("~"))
        self.source.addItems(['Local File', 'Remote URL'])
        self.source.currentIndexChanged.connect(self.on_source_changed)
        self.infile.setPlaceholderText(' /full/path/to/file.html ')
        self.infile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(
            str(
                QFileDialog.getOpenFileName(
                    self.dock, "Open a File to read from", path.expanduser(
                        "~"), ';;'.join([
                            '{}(*.{})'.format(e.upper(), e) for e in
                            ['html', 'webp', 'webm', 'svg', 'css', 'js', '*']
                        ])))))
        self.inurl, self.output = QLineEdit('http://www.'), QTextEdit()
        self.inurl.setPlaceholderText(
            'http://www.full/url/to/remote/file.html')
        self.inurl.hide()
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (self.source, self.infile, self.open, self.inurl):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Mobile ')
        self.ckcss1 = QCheckBox('Run in full screen using current resolution')
        self.ckcss2 = QCheckBox('Disable touch mode and use keypad mode')
        self.ckcss3 = QCheckBox(
            'Disable touch mode but allow to use the mouse')
        self.ckcss4 = QCheckBox(
            'Enable mouse,disable pointer & zoom emulation')
        self.ckcss5 = QCheckBox('Start the Mobile version of the browser')
        self.ckcss6 = QCheckBox('Start the Tablet version of the browser')
        self.ckcss7 = QCheckBox('Emulate hardware with Menu and Back keys')
        self.ckcss8 = QCheckBox('Start the browser in Kiosk mode')
        self.width, self.height = QSpinBox(), QSpinBox()
        self.zoom, self.ram, self.dpi = QSpinBox(), QSpinBox(), QSpinBox()
        self.cpulag, self.gpulag = QSpinBox(), QSpinBox()
        self.lang, self.agent = QComboBox(), QComboBox()
        self.lang.addItems(['EN', 'ES', 'PT', 'JA', 'ZH', 'DE', 'RU', 'FR'])
        self.agent.addItems(['Default', 'Android', 'MeeGo', 'Desktop'])
        self.fonts = QLineEdit()
        self.width.setMaximum(9999)
        self.width.setMinimum(100)
        self.width.setValue(480)
        self.height.setMaximum(9999)
        self.height.setMinimum(100)
        self.height.setValue(800)
        self.zoom.setMaximum(999)
        self.zoom.setMinimum(1)
        self.zoom.setValue(100)
        self.ram.setMaximum(999)
        self.ram.setMinimum(1)
        self.ram.setValue(100)
        self.dpi.setMaximum(200)
        self.dpi.setMinimum(50)
        self.dpi.setValue(96)
        self.cpulag.setMaximum(9999)
        self.cpulag.setMinimum(0)
        self.cpulag.setValue(1)
        self.gpulag.setMaximum(9999)
        self.gpulag.setMinimum(0)
        self.gpulag.setValue(1)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
                self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                QLabel('Width Pixels of the emulated device screen'),
                self.width,
                QLabel('Height Pixels of the emulated device screen'),
                self.height,
                QLabel('Zoom Percentage of emulated screen'), self.zoom,
                QLabel('RAM MegaBytes of the emulated device'), self.ram,
                QLabel('Language of the emulated device'), self.lang,
                QLabel('D.P.I. of the emulated device'), self.dpi,
                QLabel('User-Agent of the emulated device'), self.agent,
                QLabel('CPU Core Lag Miliseconds of emulated device'),
                self.cpulag,
                QLabel('GPU Video Lag Miliseconds of emulated device'),
                self.gpulag, QLabel('Extra Fonts Directory Full Path'),
                self.fonts):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(' General ')
        self.nice, self.opera = QSpinBox(), QLineEdit(path.expanduser("~"))
        self.nice.setValue(20)
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.opera.setCompleter(self.completer)
        if path.exists(CONFIG_FILE):
            with codecs.open(CONFIG_FILE, encoding='utf-8') as fp:
                self.opera.setText(fp.read())
        self.open2 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open2.setCursor(QCursor(Qt.PointingHandCursor))
        self.open2.clicked.connect(lambda: self.opera.setText(
            str(
                QFileDialog.getOpenFileName(
                    self.dock, "Open Opera Mobile Emulator",
                    path.expanduser("~"),
                    'Opera Mobile Emulator Executable(opera-mobile-emulator)'))
        ))
        self.help1 = QLabel('''<a href=
            "http://www.opera.com/developer/mobile-emulator">
            <small><center>Download Opera Mobile Emulator !</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group2)
        for each_widget in (QLabel(' Backend CPU priority: '), self.nice,
                            QLabel(' Opera Mobile Emulator Full Path: '),
                            self.opera, self.open2, self.help1):
            vboxg4.addWidget(each_widget)

        self.button = QPushButton('Preview on Mobile')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '

            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((
            QLabel('<b>Mobile Browser Emulator'),
            self.group0,
            self.group1,
            self.group2,
            self.output,
            self.button,
        ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Mobile")
        QPushButton(
            QIcon.fromTheme("help-about"), 'About', self.dock).clicked.connect(
                lambda: QMessageBox.information(self.dock, __doc__, HELPMSG))
Пример #7
0
class ArrowAnnotation(Annotation):
    def __init__(self, parent=None, line=None, **kwargs):
        Annotation.__init__(self, parent, **kwargs)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemIsSelectable)

        self.setFocusPolicy(Qt.ClickFocus)

        if line is None:
            line = QLineF(0, 0, 20, 0)

        self.__line = line
        self.__color = QColor(Qt.red)
        self.__arrowItem = ArrowItem(self)
        self.__arrowItem.setLine(line)
        self.__arrowItem.setBrush(self.__color)
        self.__arrowItem.setPen(QPen(Qt.NoPen))
        self.__arrowItem.setArrowStyle(ArrowItem.Concave)
        self.__arrowItem.setLineWidth(5)

        self.__shadow = QGraphicsDropShadowEffect(
            blurRadius=5,
            offset=QPointF(1.0, 2.0),
        )

        self.__arrowItem.setGraphicsEffect(self.__shadow)
        self.__shadow.setEnabled(True)

        self.__autoAdjustGeometry = True

    def setAutoAdjustGeometry(self, autoAdjust):
        """
        If set to `True` then the geometry will be adjusted whenever
        the arrow is changed with `setLine`. Otherwise the geometry
        of the item is only updated so the `line` lies within the
        `geometry()` rect (i.e. it only grows). True by default

        """
        self.__autoAdjustGeometry = autoAdjust
        if autoAdjust:
            self.adjustGeometry()

    def autoAdjustGeometry(self):
        """
        Should the geometry of the item be adjusted automatically when
        `setLine` is called.

        """
        return self.__autoAdjustGeometry

    def setLine(self, line):
        """
        Set the arrow base line (a `QLineF` in object coordinates).
        """
        if self.__line != line:
            self.__line = line

            # local item coordinate system
            geom = self.geometry().translated(-self.pos())

            if geom.isNull() and not line.isNull():
                geom = QRectF(0, 0, 1, 1)

            arrow_shape = arrow_path_concave(line, self.lineWidth())
            arrow_rect = arrow_shape.boundingRect()

            if not (geom.contains(arrow_rect)):
                geom = geom.united(arrow_rect)

            if self.__autoAdjustGeometry:
                # Shrink the geometry if required.
                geom = geom.intersected(arrow_rect)

            # topLeft can move changing the local coordinates.
            diff = geom.topLeft()
            line = QLineF(line.p1() - diff, line.p2() - diff)
            self.__arrowItem.setLine(line)
            self.__line = line

            # parent item coordinate system
            geom.translate(self.pos())
            self.setGeometry(geom)

    def line(self):
        """
        Return the arrow base line (`QLineF` in object coordinates).
        """
        return QLineF(self.__line)

    def setColor(self, color):
        """
        Set arrow brush color.
        """
        if self.__color != color:
            self.__color = QColor(color)
            self.__updateStyleState()

    def color(self):
        """
        Return the arrow brush color.
        """
        return QColor(self.__color)

    def setLineWidth(self, lineWidth):
        """
        Set the arrow line width.
        """
        self.__arrowItem.setLineWidth(lineWidth)

    def lineWidth(self):
        """
        Return the arrow line width.
        """
        return self.__arrowItem.lineWidth()

    def adjustGeometry(self):
        """
        Adjust the widget geometry to exactly fit the arrow inside
        while preserving the arrow path scene geometry.

        """
        # local system coordinate
        geom = self.geometry().translated(-self.pos())
        line = self.__line

        arrow_rect = self.__arrowItem.shape().boundingRect()

        if geom.isNull() and not line.isNull():
            geom = QRectF(0, 0, 1, 1)

        if not (geom.contains(arrow_rect)):
            geom = geom.united(arrow_rect)

        geom = geom.intersected(arrow_rect)
        diff = geom.topLeft()
        line = QLineF(line.p1() - diff, line.p2() - diff)
        geom.translate(self.pos())
        self.setGeometry(geom)
        self.setLine(line)

    def shape(self):
        arrow_shape = self.__arrowItem.shape()
        return self.mapFromItem(self.__arrowItem, arrow_shape)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemSelectedHasChanged:
            self.__updateStyleState()

        return Annotation.itemChange(self, change, value)

    def __updateStyleState(self):
        """
        Update the arrows' brush, pen, ... based on it's state
        """
        if self.isSelected():
            color = self.__color.darker(150)
            pen = QPen(QColor(96, 158, 215), Qt.DashDotLine)
            pen.setWidthF(1.25)
            pen.setCosmetic(True)
            self.__shadow.setColor(pen.color().darker(150))
        else:
            color = self.__color
            pen = QPen(Qt.NoPen)
            self.__shadow.setColor(QColor(63, 63, 63, 180))

        self.__arrowItem.setBrush(color)
        self.__arrowItem.setPen(pen)
Пример #8
0
class ArrowAnnotation(Annotation):
    def __init__(self, parent=None, line=None, **kwargs):
        Annotation.__init__(self, parent, **kwargs)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemIsSelectable)

        self.setFocusPolicy(Qt.ClickFocus)

        if line is None:
            line = QLineF(0, 0, 20, 0)

        self.__line = line
        self.__color = QColor(Qt.red)
        self.__arrowItem = ArrowItem(self)
        self.__arrowItem.setLine(line)
        self.__arrowItem.setBrush(self.__color)
        self.__arrowItem.setPen(QPen(Qt.NoPen))
        self.__arrowItem.setArrowStyle(ArrowItem.Concave)
        self.__arrowItem.setLineWidth(5)

        self.__shadow = QGraphicsDropShadowEffect(
            blurRadius=5, offset=QPointF(1.0, 2.0),
        )

        self.__arrowItem.setGraphicsEffect(self.__shadow)
        self.__shadow.setEnabled(True)

        self.__autoAdjustGeometry = True

    def setAutoAdjustGeometry(self, autoAdjust):
        """
        If set to `True` then the geometry will be adjusted whenever
        the arrow is changed with `setLine`. Otherwise the geometry
        of the item is only updated so the `line` lies within the
        `geometry()` rect (i.e. it only grows). True by default

        """
        self.__autoAdjustGeometry = autoAdjust
        if autoAdjust:
            self.adjustGeometry()

    def autoAdjustGeometry(self):
        """
        Should the geometry of the item be adjusted automatically when
        `setLine` is called.

        """
        return self.__autoAdjustGeometry

    def setLine(self, line):
        """
        Set the arrow base line (a `QLineF` in object coordinates).
        """
        if self.__line != line:
            self.__line = line

            # local item coordinate system
            geom = self.geometry().translated(-self.pos())

            if geom.isNull() and not line.isNull():
                geom = QRectF(0, 0, 1, 1)

            arrow_shape = arrow_path_concave(line, self.lineWidth())
            arrow_rect = arrow_shape.boundingRect()

            if not (geom.contains(arrow_rect)):
                geom = geom.united(arrow_rect)

            if self.__autoAdjustGeometry:
                # Shrink the geometry if required.
                geom = geom.intersected(arrow_rect)

            # topLeft can move changing the local coordinates.
            diff = geom.topLeft()
            line = QLineF(line.p1() - diff, line.p2() - diff)
            self.__arrowItem.setLine(line)
            self.__line = line

            # parent item coordinate system
            geom.translate(self.pos())
            self.setGeometry(geom)

    def line(self):
        """
        Return the arrow base line (`QLineF` in object coordinates).
        """
        return QLineF(self.__line)

    def setColor(self, color):
        """
        Set arrow brush color.
        """
        if self.__color != color:
            self.__color = QColor(color)
            self.__updateBrush()

    def color(self):
        """
        Return the arrow brush color.
        """
        return QColor(self.__color)

    def setLineWidth(self, lineWidth):
        """
        Set the arrow line width.
        """
        self.__arrowItem.setLineWidth(lineWidth)

    def lineWidth(self):
        """
        Return the arrow line width.
        """
        return self.__arrowItem.lineWidth()

    def adjustGeometry(self):
        """
        Adjust the widget geometry to exactly fit the arrow inside
        while preserving the arrow path scene geometry.

        """
        # local system coordinate
        geom = self.geometry().translated(-self.pos())
        line = self.__line

        arrow_rect = self.__arrowItem.shape().boundingRect()

        if geom.isNull() and not line.isNull():
            geom = QRectF(0, 0, 1, 1)

        if not (geom.contains(arrow_rect)):
            geom = geom.united(arrow_rect)

        geom = geom.intersected(arrow_rect)
        diff = geom.topLeft()
        line = QLineF(line.p1() - diff, line.p2() - diff)
        geom.translate(self.pos())
        self.setGeometry(geom)
        self.setLine(line)

    def shape(self):
        arrow_shape = self.__arrowItem.shape()
        return self.mapFromItem(self.__arrowItem, arrow_shape)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemSelectedHasChanged:
            self.__updateBrush()

        return Annotation.itemChange(self, change, value)

    def __updateBrush(self):
        """
        Update the arrow brush.
        """
        if self.isSelected():
            color = self.__color.darker(150)
        else:
            color = self.__color

        self.__arrowItem.setBrush(color)
Пример #9
0
class LinkCurveItem(QGraphicsPathItem):
    """
    Link curve item. The main component of a :class:`LinkItem`.
    """
    def __init__(self, parent):
        QGraphicsPathItem.__init__(self, parent)
        if not isinstance(parent, LinkItem):
            raise TypeError("'LinkItem' expected")

        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__canvasLink = parent
        self.setAcceptHoverEvents(True)

        self.shadow = QGraphicsDropShadowEffect(
            blurRadius=5, color=QColor(SHADOW_COLOR),
            offset=QPointF(0, 0)
        )

        self.normalPen = QPen(QBrush(QColor("#9CACB4")), 2.0)
        self.hoverPen = QPen(QBrush(QColor("#7D7D7D")), 2.1)
        self.setPen(self.normalPen)
        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        self.__hover = False
        self.__enabled = True
        self.__shape = None

    def linkItem(self):
        """
        Return the :class:`LinkItem` instance this curve belongs to.
        """
        return self.__canvasLink

    def setHoverState(self, state):
        self.prepareGeometryChange()
        self.__shape = None
        self.__hover = state
        self.__update()

    def setLinkEnabled(self, state):
        self.prepareGeometryChange()
        self.__shape = None
        self.__enabled = state
        self.__update()

    def isLinkEnabled(self):
        return self.__enabled

    def setCurvePenSet(self, pen, hoverPen):
        self.prepareGeometryChange()
        if pen is not None:
            self.normalPen = pen
        if hoverPen is not None:
            self.hoverPen = hoverPen
        self.__shape = None
        self.__update()

    def shape(self):
        if self.__shape is None:
            path = self.path()
            pen = QPen(self.pen())
            pen.setWidthF(max(pen.widthF(), 7.0))
            pen.setStyle(Qt.SolidLine)
            self.__shape = stroke_path(path, pen)
        return self.__shape

    def setPath(self, path):
        self.__shape = None
        QGraphicsPathItem.setPath(self, path)

    def __update(self):
        shadow_enabled = self.__hover
        if self.shadow.isEnabled() != shadow_enabled:
            self.shadow.setEnabled(shadow_enabled)

        link_enabled = self.__enabled
        if link_enabled:
            pen_style = Qt.SolidLine
        else:
            pen_style = Qt.DashLine

        if self.__hover:
            pen = self.hoverPen
        else:
            pen = self.normalPen

        pen.setStyle(pen_style)
        self.setPen(pen)
Пример #10
0
class LinkCurveItem(QGraphicsPathItem):
    """
    Link curve item. The main component of a :class:`LinkItem`.
    """
    def __init__(self, parent):
        QGraphicsPathItem.__init__(self, parent)
        if not isinstance(parent, LinkItem):
            raise TypeError("'LinkItem' expected")

        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__canvasLink = parent
        self.setAcceptHoverEvents(True)

        self.shadow = QGraphicsDropShadowEffect(blurRadius=5,
                                                color=QColor(SHADOW_COLOR),
                                                offset=QPointF(0, 0))

        self.normalPen = QPen(QBrush(QColor("#9CACB4")), 2.0)
        self.hoverPen = QPen(QBrush(QColor("#7D7D7D")), 2.1)
        self.setPen(self.normalPen)
        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        self.__hover = False
        self.__enabled = True
        self.__shape = None

    def linkItem(self):
        """
        Return the :class:`LinkItem` instance this curve belongs to.
        """
        return self.__canvasLink

    def setHoverState(self, state):
        self.prepareGeometryChange()
        self.__shape = None
        self.__hover = state
        self.__update()

    def setLinkEnabled(self, state):
        self.prepareGeometryChange()
        self.__shape = None
        self.__enabled = state
        self.__update()

    def isLinkEnabled(self):
        return self.__enabled

    def setCurvePenSet(self, pen, hoverPen):
        self.prepareGeometryChange()
        if pen is not None:
            self.normalPen = pen
        if hoverPen is not None:
            self.hoverPen = hoverPen
        self.__shape = None
        self.__update()

    def shape(self):
        if self.__shape is None:
            path = self.path()
            pen = QPen(self.pen())
            pen.setWidthF(max(pen.widthF(), 7.0))
            pen.setStyle(Qt.SolidLine)
            self.__shape = stroke_path(path, pen)
        return self.__shape

    def setPath(self, path):
        self.__shape = None
        QGraphicsPathItem.setPath(self, path)

    def __update(self):
        shadow_enabled = self.__hover
        if self.shadow.isEnabled() != shadow_enabled:
            self.shadow.setEnabled(shadow_enabled)

        link_enabled = self.__enabled
        if link_enabled:
            pen_style = Qt.SolidLine
        else:
            pen_style = Qt.DashLine

        if self.__hover:
            pen = self.hoverPen
        else:
            pen = self.normalPen

        pen.setStyle(pen_style)
        self.setPen(pen)
Пример #11
0
class QSwitch(QSlider):
    """ Custom Switch Widget, inspired from some QML desktop components """
    style_knob, style_off, style_on = qss_knob, qss_off, qss_on
    clicked, animationOk = pyqtSignal(), pyqtSignal()

    def __init__(self, parent=None):
        """ Init Custom Switch Widget, set Animation and Glow effects """
        QSlider.__init__(self, parent)
        self.setOrientation(Qt.Horizontal)
        self.animationType = QEasingCurve.OutExpo
        self.animation = QPropertyAnimation(self, "value")
        self.animation.setDuration(1000)
        self.animation.finished.connect(self.animationDone)
        self.clicked.connect(self.changeValue)
        self.setStyleSheet(self.style_knob + self.style_off)
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)

    def changeValue(self):
        """ method to change the actual state ON <--> OFF """
        self.animation.setEasingCurve(self.animationType)
        if self.value() == self.maximum():
            self.animation.setStartValue(self.maximum())
            self.animation.setEndValue(self.minimum())
            self.animation.start()
            self.setStyleSheet(self.style_knob + self.style_off)
            self.glow.setEnabled(False)
            return
        else:
            self.animation.setStartValue(self.minimum())
            self.animation.setEndValue(self.maximum())
            self.setStyleSheet(self.style_knob + self.style_on)
            self.glow.setEnabled(True)
        self.animation.start()

    @pyqtSignature("setAtMax()")
    def setAtMax(self):
        """ method to set at Maximum, aka ON """
        if self.value() == self.minimum():
            self.animation.setEasingCurve(self.animationType)
            self.animation.setStartValue(self.minimum())
            self.animation.setEndValue(self.maximum())
            self.animation.start()
            self.setStyleSheet(self.style_knob + self.style_on)

    @pyqtSignature("setAtMin()")
    def setAtMin(self):
        """ method to set at Minimum, aka OFF """
        if self.value() == self.maximum():
            self.animation.setEasingCurve(self.animationType)
            self.animation.setStartValue(self.maximum())
            self.animation.setEndValue(self.minimum())
            self.animation.start()
            self.setStyleSheet(self.style_knob + self.style_off)

    def mousePressEvent(self, event):
        """ method to respond a signal to mouse pointer clicks """
        self.clicked.emit()

    def isChecked(self):
        """ method to return a bool based on actual state """
        return self.value() == self.maximum()

    def wheelEvent(self, event):
        """ dumb method, its not a bug leave it alone """
        return

    def animationDone(self):
        """ method to respond a signal to animation effects """
        self.animationOk.emit()
Пример #12
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.chooser, self.process = QComboBox(), QProcess()
        self.chooser.addItems([' Ubuntu Unity QuickList .desktop ',
                               ' KDE Plasma MetaData .desktop ',
                               ' FreeDesktop Standard .desktop '])
        self.chooser.currentIndexChanged.connect(self.on_index_changed)
        self.chooser.setToolTip('Select a target .desktop file format')

        # Standard FreeDesktop
        self.group1 = QGroupBox()
        self.group1.setTitle(' Standard ')
        self.ledVersion, self.ledCategories = QDoubleSpinBox(), QComboBox()
        self.ledVersion.setMinimum(0.1)
        self.ledVersion.setMaximum(999.9)
        self.ledVersion.setValue(1.0)
        self.ledVersion.setDecimals(1)
        self.ledType, self.ledName = QLineEdit('Application'), QLineEdit('App')
        self.ledGenericName = QLineEdit('Generic App')
        self.ledComment, self.ledIcon = QLineEdit('App'), QLineEdit('icon.svg')
        self.ledCategories.addItems(['Python Programming Language',
            'Development', 'Ruby', 'C++', 'Amateur Radio', 'Communication',
            'Cross Platform', 'Databases', 'Debug', 'Documentation', 'Editors',
            'Education', 'Electronics', 'Email', 'Embebed Devices', 'Fonts',
            'GNOME Desktop Environment', 'GNU R Statistical System',
            'GObject Introspection Data', 'Games and Amusement',
            'Gnustep Desktop Environtment', 'Graphics',
            'Haskell Programming Language',
            'Internationalization and Localization', 'Internet',
            'Interpreted Computer Languages', 'KDE Software Compilation',
            'Kernel and Modules', 'Libraries', 'Libraries - Development',
            'Libraries - Old', 'Lisp Programming Language', 'Localization',
            'Mathematics', 'Meta Packages', 'Miscelaneous - Graphical',
            'Miscelaneous - Text Based', 'Mono/CLI Infraestructure',
            'Multimedia', 'Networking', 'Newsgroups',
            'OCaml Programming Language', 'PHP Programming Language',
            'Perl Programming Language', 'Ruby Programming Language',
            'Science', 'Shells', 'System Administration', 'TeX Authoring',
            'Utilities', 'Version Control Systems', 'Video Software',
            'Web Servers', 'Word Processing', 'Xfce Desktop Environment',
            'Zope/Plone Environment'])

        self.ledExec, self.ledTryExec = QLineEdit('myapp'), QLineEdit('myapp')
        self.ledMymeType = QLineEdit('application/x-desktop')
        self.ledTerminal = QComboBox()
        self.ledTerminal.addItems(['False', 'True'])
        self.ledActions = QLineEdit('Next;Previous')
        self.ledOnlyShowIn = QLineEdit('Unity;KDE')
        self.ledNotShowIn = QLineEdit('Gnome2')
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (QLabel('Version'), self.ledVersion, QLabel('Type'),
            self.ledType, QLabel('Name'), self.ledName, QLabel('GenericName'),
            self.ledGenericName, QLabel('Comment'), self.ledComment,
            QLabel('Icon'), self.ledIcon, QLabel('Categories'),
            self.ledCategories, QLabel('Exec'), self.ledExec, QLabel('TryExec'),
            self.ledTryExec, QLabel('MymeType'), self.ledMymeType,
            QLabel('Terminal'), self.ledTerminal, QLabel('Actions'),
            self.ledActions, QLabel('OnlyShowIn'), self.ledOnlyShowIn,
            QLabel('NotShowIn'), self.ledNotShowIn):
            vboxg1.addWidget(each_widget)

        # KDE Plasma
        self.group2 = QGroupBox()
        self.group2.setTitle(' KDE Plasma ')
        self.group2.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.ledEncoding, self.ledXPlasmaAPI = QComboBox(), QComboBox()
        self.ledEncoding.addItems(['UTF-8', 'ISO-8859-1'])
        self.ledServiceType = QLineEdit('Plasma/Applet')
        self.ledXPlasmaAPI.addItems([
                        'Python', 'Javascript', 'Ruby', 'C++', 'HTML5', 'QML'])
        self.ledXPlasmaMainScript = QLineEdit('path/to/your/code.py')
        self.ledXKDEPluginInfoAuthor = QLineEdit(getuser())
        self.ledXKDEPluginInfoEmail = QLineEdit(getuser() + '@gmail.com')
        self.ledXKDEPluginInfoName = QLineEdit('Hello-World')
        self.ledXKDEPluginInfoVersion = QLineEdit('1.0')
        self.ledXKDEPluginInfoWebsite = QLineEdit('http:plasma.kde.org')
        self.ledXKDEPluginInfoCategory = QComboBox()
        self.ledXKDEPluginInfoCategory.addItems(['Application Launchers',
            'Accessibility', 'Astronomy', 'Date and Time',
            'Development Tools', 'Education', 'Environment', 'Examples',
            'File System', 'Fun and Games', 'Graphics', 'Language', 'Mapping',
            'Multimedia', 'Online Services', 'System Information', 'Utilities',
            'Windows and Tasks', 'Miscelaneous'])
        self.ledXKDEPluginInfoDepends = QLineEdit()
        self.ledXKDEPluginInfoLicense = QLineEdit('GPL')
        self.ledXKDEPluginInfoEnabledByDefault = QComboBox()
        self.ledXKDEPluginInfoEnabledByDefault.addItems(['True', 'False'])
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('Encoding'), self.ledEncoding,
            QLabel('ServiceType'), self.ledServiceType,
            QLabel('X-Plasma-API'), self.ledXPlasmaAPI,
            QLabel('X-Plasma-MainScript'), self.ledXPlasmaMainScript,
            QLabel('X-KDE-PluginInfo-Author'), self.ledXKDEPluginInfoAuthor,
            QLabel('X-KDE-PluginInfo-Email'), self.ledXKDEPluginInfoEmail,
            QLabel('X-KDE-PluginInfo-Name'), self.ledXKDEPluginInfoName,
            QLabel('X-KDE-PluginInfo-Version'), self.ledXKDEPluginInfoVersion,
            QLabel('X-KDE-PluginInfo-Website'), self.ledXKDEPluginInfoWebsite,
            QLabel('X-KDE-PluginInfo-Category'), self.ledXKDEPluginInfoCategory,
            QLabel('X-KDE-PluginInfo-Depends'), self.ledXKDEPluginInfoDepends,
            QLabel('X-KDE-PluginInfo-License'), self.ledXKDEPluginInfoLicense,
            QLabel('X-KDE-PluginInfo-EnabledByDefault'),
            self.ledXKDEPluginInfoEnabledByDefault):
            vboxg2.addWidget(each_widget)

        # Ubuntu Unity
        self.ledXAyatanaDesktopShortcuts = QLineEdit('Next;Previous')

        self.checkbox1 = QCheckBox('Open .desktop file when done')
        self.checkbox2 = QCheckBox('Make .desktop file Executable')
        [a.setChecked(True) for a in (self.checkbox1, self.checkbox2)]

        self.button = QPushButton(' Make .Desktop File ! ')
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.writeFile)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((self.chooser, self.group1, self.group2,
            QLabel('X-Ayatana-Desktop-Shortcuts'),
            self.ledXAyatanaDesktopShortcuts, QLabel(''),
            self.checkbox1, self.checkbox2, self.button))
        self.dock, self.scrollable = QDockWidget(), QScrollArea()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "DotDesktop")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
          ''.join((__doc__, __version__, __license__, 'by', __author__))))
class NodeAnchorItem(GraphicsPathObject):
    """
    The left/right widget input/output anchors.
    """

    def __init__(self, parent, *args):
        GraphicsPathObject.__init__(self, parent, *args)
        self.setAcceptHoverEvents(True)
        self.setPen(QPen(Qt.NoPen))
        self.normalBrush = QBrush(QColor("#CDD5D9"))
        self.connectedBrush = QBrush(QColor("#9CACB4"))
        self.setBrush(self.normalBrush)

        self.shadow = QGraphicsDropShadowEffect(
            blurRadius=10,
            color=QColor(SHADOW_COLOR),
            offset=QPointF(0, 0)
        )

        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        # Does this item have any anchored links.
        self.anchored = False

        if isinstance(parent, NodeItem):
            self.__parentNodeItem = parent
        else:
            self.__parentNodeItem = None

        self.__anchorPath = QPainterPath()
        self.__points = []
        self.__pointPositions = []

        self.__fullStroke = None
        self.__dottedStroke = None
        self.__shape = None

    def parentNodeItem(self):
        """
        Return a parent :class:`NodeItem` or ``None`` if this anchor's
        parent is not a :class:`NodeItem` instance.

        """
        return self.__parentNodeItem

    def setAnchorPath(self, path):
        """
        Set the anchor's curve path as a :class:`QPainterPath`.
        """
        self.__anchorPath = path
        # Create a stroke of the path.
        stroke_path = QPainterPathStroker()
        stroke_path.setCapStyle(Qt.RoundCap)

        # Shape is wider (bigger mouse hit area - should be settable)
        stroke_path.setWidth(9)
        self.__shape = stroke_path.createStroke(path)

        # The full stroke
        stroke_path.setWidth(3)
        self.__fullStroke = stroke_path.createStroke(path)

        # The dotted stroke (when not connected to anything)
        stroke_path.setDashPattern(Qt.DotLine)
        self.__dottedStroke = stroke_path.createStroke(path)

        if self.anchored:
            self.setPath(self.__fullStroke)
            self.setBrush(self.connectedBrush)
        else:
            self.setPath(self.__dottedStroke)
            self.setBrush(self.normalBrush)

    def anchorPath(self):
        """
        Return the anchor path (:class:`QPainterPath`). This is a curve on
        which the anchor points lie.

        """
        return self.__anchorPath

    def setAnchored(self, anchored):
        """
        Set the items anchored state. When ``False`` the item draws it self
        with a dotted stroke.

        """
        self.anchored = anchored
        if anchored:
            self.setPath(self.__fullStroke)
            self.setBrush(self.connectedBrush)
        else:
            self.setPath(self.__dottedStroke)
            self.setBrush(self.normalBrush)

    def setConnectionHint(self, hint=None):
        """
        Set the connection hint. This can be used to indicate if
        a connection can be made or not.

        """
        raise NotImplementedError

    def count(self):
        """
        Return the number of anchor points.
        """
        return len(self.__points)

    def addAnchor(self, anchor, position=0.5):
        """
        Add a new :class:`AnchorPoint` to this item and return it's index.

        The `position` specifies where along the `anchorPath` is the new
        point inserted.

        """
        return self.insertAnchor(self.count(), anchor, position)

    def insertAnchor(self, index, anchor, position=0.5):
        """
        Insert a new :class:`AnchorPoint` at `index`.

        See also
        --------
        NodeAnchorItem.addAnchor

        """
        if anchor in self.__points:
            raise ValueError("%s already added." % anchor)

        self.__points.insert(index, anchor)
        self.__pointPositions.insert(index, position)

        anchor.setParentItem(self)
        anchor.setPos(self.__anchorPath.pointAtPercent(position))
        anchor.destroyed.connect(self.__onAnchorDestroyed)

        self.__updatePositions()

        self.setAnchored(bool(self.__points))

        return index

    def removeAnchor(self, anchor):
        """
        Remove and delete the anchor point.
        """
        anchor = self.takeAnchor(anchor)

        anchor.hide()
        anchor.setParentItem(None)
        anchor.deleteLater()

    def takeAnchor(self, anchor):
        """
        Remove the anchor but don't delete it.
        """
        index = self.__points.index(anchor)

        del self.__points[index]
        del self.__pointPositions[index]

        anchor.destroyed.disconnect(self.__onAnchorDestroyed)

        self.__updatePositions()

        self.setAnchored(bool(self.__points))

        return anchor

    def __onAnchorDestroyed(self, anchor):
        try:
            index = self.__points.index(anchor)
        except ValueError:
            return

        del self.__points[index]
        del self.__pointPositions[index]

    def anchorPoints(self):
        """
        Return a list of anchor points.
        """
        return list(self.__points)

    def anchorPoint(self, index):
        """
        Return the anchor point at `index`.
        """
        return self.__points[index]

    def setAnchorPositions(self, positions):
        """
        Set the anchor positions in percentages (0..1) along the path curve.
        """
        if self.__pointPositions != positions:
            self.__pointPositions = list(positions)

            self.__updatePositions()

    def anchorPositions(self):
        """
        Return the positions of anchor points as a list of floats where
        each float is between 0 and 1 and specifies where along the anchor
        path does the point lie (0 is at start 1 is at the end).

        """
        return list(self.__pointPositions)

    def shape(self):
        if self.__shape is not None:
            return self.__shape
        else:
            return GraphicsPathObject.shape(self)

    def boundingRect(self):
        if self.__shape is not None:
            return self.__shape.controlPointRect()
        else:
            return GraphicsPathObject.boundingRect(self)

    def hoverEnterEvent(self, event):
        self.shadow.setEnabled(True)
        return GraphicsPathObject.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        self.shadow.setEnabled(False)
        return GraphicsPathObject.hoverLeaveEvent(self, event)

    def __updatePositions(self):
        """Update anchor points positions.
        """
        for point, t in zip(self.__points, self.__pointPositions):
            pos = self.__anchorPath.pointAtPercent(t)
            point.setPos(pos)
Пример #14
0
class NodeAnchorItem(GraphicsPathObject):
    """
    The left/right widget input/output anchors.
    """
    def __init__(self, parent, *args):
        GraphicsPathObject.__init__(self, parent, *args)
        self.setAcceptHoverEvents(True)
        self.setPen(QPen(Qt.NoPen))
        self.normalBrush = QBrush(QColor("#CDD5D9"))
        self.connectedBrush = QBrush(QColor("#9CACB4"))
        self.setBrush(self.normalBrush)

        self.shadow = QGraphicsDropShadowEffect(blurRadius=10,
                                                color=QColor(SHADOW_COLOR),
                                                offset=QPointF(0, 0))

        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        # Does this item have any anchored links.
        self.anchored = False

        if isinstance(parent, NodeItem):
            self.__parentNodeItem = parent
        else:
            self.__parentNodeItem = None

        self.__anchorPath = QPainterPath()
        self.__points = []
        self.__pointPositions = []

        self.__fullStroke = None
        self.__dottedStroke = None
        self.__shape = None

    def parentNodeItem(self):
        """
        Return a parent :class:`NodeItem` or ``None`` if this anchor's
        parent is not a :class:`NodeItem` instance.

        """
        return self.__parentNodeItem

    def setAnchorPath(self, path):
        """
        Set the anchor's curve path as a :class:`QPainterPath`.
        """
        self.__anchorPath = path
        # Create a stroke of the path.
        stroke_path = QPainterPathStroker()
        stroke_path.setCapStyle(Qt.RoundCap)

        # Shape is wider (bigger mouse hit area - should be settable)
        stroke_path.setWidth(12)
        self.__shape = stroke_path.createStroke(path)

        # The full stroke
        stroke_path.setWidth(3)
        self.__fullStroke = stroke_path.createStroke(path)

        # The dotted stroke (when not connected to anything)
        stroke_path.setDashPattern(Qt.DotLine)
        self.__dottedStroke = stroke_path.createStroke(path)

        if self.anchored:
            self.setPath(self.__fullStroke)
            self.setBrush(self.connectedBrush)
        else:
            self.setPath(self.__dottedStroke)
            self.setBrush(self.normalBrush)

    def anchorPath(self):
        """
        Return the anchor path (:class:`QPainterPath`). This is a curve on
        which the anchor points lie.

        """
        return self.__anchorPath

    def setAnchored(self, anchored):
        """
        Set the items anchored state. When ``False`` the item draws it self
        with a dotted stroke.

        """
        self.anchored = anchored
        if anchored:
            self.setPath(self.__fullStroke)
            self.setBrush(self.connectedBrush)
        else:
            self.setPath(self.__dottedStroke)
            self.setBrush(self.normalBrush)

    def setConnectionHint(self, hint=None):
        """
        Set the connection hint. This can be used to indicate if
        a connection can be made or not.

        """
        raise NotImplementedError

    def count(self):
        """
        Return the number of anchor points.
        """
        return len(self.__points)

    def addAnchor(self, anchor, position=0.5):
        """
        Add a new :class:`AnchorPoint` to this item and return it's index.

        The `position` specifies where along the `anchorPath` is the new
        point inserted.

        """
        return self.insertAnchor(self.count(), anchor, position)

    def insertAnchor(self, index, anchor, position=0.5):
        """
        Insert a new :class:`AnchorPoint` at `index`.

        See also
        --------
        NodeAnchorItem.addAnchor

        """
        if anchor in self.__points:
            raise ValueError("%s already added." % anchor)

        self.__points.insert(index, anchor)
        self.__pointPositions.insert(index, position)

        anchor.setParentItem(self)
        anchor.setPos(self.__anchorPath.pointAtPercent(position))
        anchor.destroyed.connect(self.__onAnchorDestroyed)

        self.__updatePositions()

        self.setAnchored(bool(self.__points))

        return index

    def removeAnchor(self, anchor):
        """
        Remove and delete the anchor point.
        """
        anchor = self.takeAnchor(anchor)

        anchor.hide()
        anchor.setParentItem(None)
        anchor.deleteLater()

    def takeAnchor(self, anchor):
        """
        Remove the anchor but don't delete it.
        """
        index = self.__points.index(anchor)

        del self.__points[index]
        del self.__pointPositions[index]

        anchor.destroyed.disconnect(self.__onAnchorDestroyed)

        self.__updatePositions()

        self.setAnchored(bool(self.__points))

        return anchor

    def __onAnchorDestroyed(self, anchor):
        try:
            index = self.__points.index(anchor)
        except ValueError:
            return

        del self.__points[index]
        del self.__pointPositions[index]

    def anchorPoints(self):
        """
        Return a list of anchor points.
        """
        return list(self.__points)

    def anchorPoint(self, index):
        """
        Return the anchor point at `index`.
        """
        return self.__points[index]

    def setAnchorPositions(self, positions):
        """
        Set the anchor positions in percentages (0..1) along the path curve.
        """
        if self.__pointPositions != positions:
            self.__pointPositions = list(positions)

            self.__updatePositions()

    def anchorPositions(self):
        """
        Return the positions of anchor points as a list of floats where
        each float is between 0 and 1 and specifies where along the anchor
        path does the point lie (0 is at start 1 is at the end).

        """
        return list(self.__pointPositions)

    def shape(self):
        if self.__shape is not None:
            return self.__shape
        else:
            return GraphicsPathObject.shape(self)

    def boundingRect(self):
        if self.__shape is not None:
            return self.__shape.controlPointRect()
        else:
            return GraphicsPathObject.boundingRect(self)

    def hoverEnterEvent(self, event):
        self.shadow.setEnabled(True)
        return GraphicsPathObject.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        self.shadow.setEnabled(False)
        return GraphicsPathObject.hoverLeaveEvent(self, event)

    def __updatePositions(self):
        """Update anchor points positions.
        """
        for point, t in zip(self.__points, self.__pointPositions):
            pos = self.__anchorPath.pointAtPercent(t)
            point.setPos(pos)
Пример #15
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        ec = ExplorerContainer()
        super(Main, self).initialize(*args, **kwargs)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.RUNS, self.FAILS = 0, 0
        self.group0 = QGroupBox()
        self.group0.setTitle(' Source and Target ')
        self.baseurl = QLineEdit('http://google.com')
        self.outfile = QLineEdit(path.join(path.expanduser("~"), 'test.py'))
        self.outfile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.clicked.connect(lambda: self.outfile.setText(
            QFileDialog.getSaveFileName(self.dock, "Save", path.expanduser("~"),
            'PYTHON(*.py)')))
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (QLabel('<b>Base URL'), self.baseurl,
            QLabel('<b>Local File Target'), self.outfile, self.open):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Selenium ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_group)
        self.ckcss1 = QCheckBox('Test for correct Page Loading behaviour')
        self.ckcss2 = QCheckBox('Test for Sucessfull Status Code return')
        self.ckcss3 = QCheckBox('Test for valid Title of the web page')
        self.ckcss4 = QCheckBox('Test for Cookies Basic functionality')
        self.ckcss5 = QCheckBox('Test for Back, Forward, Reload behaviour')
        self.ckcss6 = QCheckBox('Take a Screenshot of page (CSS Debug)')
        self.ckcss7 = QCheckBox('Test for Search Form Field of the page')
        self.ckcss8 = QCheckBox('Test for Arbitrary Javascript (User provided)')
        self.ckcss9 = QCheckBox('Test for iFrame of the web page')
        self.ckcss10 = QCheckBox('Test for HTML5 Canvas element on the page')
        self.ckcss11 = QCheckBox('Test for HTML5 SVG element on the page')
        self.ckcss12 = QCheckBox('Test for HTML5 Audio element on the page')
        self.ckcss13 = QCheckBox('Test for HTML5 Video element on the page')
        self.ckcss14 = QCheckBox('Test for File Upload form on the page')
        self.ckcss15 = QCheckBox('Add ChromeDriver path to sys.path')
        self.webdriver = QComboBox()
        self.webdriver.addItems(['firefox', 'chrome',
                                 'zope.testbrowser', 'phantomjs'])
        self.titletxt = QLineEdit('Google')
        self.javascript = QLineEdit('console.log("test")')
        self.authdata, self.formdata = QLineEdit(), QLineEdit()
        self.authdata.setPlaceholderText("{'username':'******','password':'******'}")
        self.formdata.setPlaceholderText("{'name': 'Joe', 'age': '25'}")
        self.iframurl = QLineEdit()
        self.chrmedrv = QLineEdit('/usr/bin/chromedriver')
        self.timeout = QSpinBox()
        self.timeout.setMaximum(99)
        self.timeout.setMinimum(0)
        self.timeout.setValue(9)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
            self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8, self.ckcss9,
            self.ckcss10, self.ckcss11, self.ckcss12, self.ckcss13,
            self.ckcss14, self.ckcss15, QLabel('<b>WebDriver'), self.webdriver,
            QLabel('''<center><small><i>Firefox is only Driver that dont
                   require additional configuration'''),
            QLabel('<b>Title Content must contain'), self.titletxt,
            QLabel('<b>Minified Javascript for Test'), self.javascript,
            QLabel('<b>Arbitrary Authentication Data for Test'), self.authdata,
            QLabel('<b>Arbitrary Form Data for Test'), self.formdata,
            QLabel('<b>iFrame URL for Test'), self.iframurl,
            QLabel('<b>Chrome Driver'), self.chrmedrv,
            QLabel('<b>Timeout Timer Limit'), self.timeout):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())

        self.group4 = QGroupBox()
        self.group4.setTitle(' General ')
        self.chckbx1 = QCheckBox('Run the Tests after Writing')
        self.chckbx2 = QCheckBox('Open the Tests with Ninja after Writing')
        self.chckbx3 = QCheckBox('Add SheBang, Encoding and Metadata to Tests')
        self.nice = QSpinBox()
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.nice.setValue(20)
        self.help1 = QLabel('''<a href="http://splinter.cobrateam.info/docs/api"
            ><center><b>API Reference</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (self.chckbx1, self.chckbx2, self.chckbx3,
            QLabel('Backend CPU priority:'), self.nice, self.help1):
            vboxg4.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        [a.setChecked(True) for a in (self.ckcss1, self.ckcss2, self.ckcss3,
            self.ckcss4, self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
            self.ckcss15, self.chckbx1, self.chckbx2, self.chckbx3)]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Write and Run Test')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)
        self.output = QPlainTextEdit()
        self.runs = QLabel('<font color="green"><b>Runs: 0')
        self.failures = QLabel('<font color="red"><b>Failures: 0')

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<b>Selenium Tests'), self.group0,
            self.group1, self.group4, QLabel('<b>Log'), self.output, self.runs,
            self.failures, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ec.addTab(self.dock, "Selenium")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
            HELPMSG))
        QPushButton(QIcon.fromTheme("media-record"), 'Record', self.group1,
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
        'Not working. If you know how to make it Record, send me Pull Request'))
Пример #16
0
class LinkCurveItem(QGraphicsPathItem):
    """
    Link curve item. The main component of a :class:`LinkItem`.
    """
    def __init__(self, parent):
        QGraphicsPathItem.__init__(self, parent)
        if not isinstance(parent, LinkItem):
            raise TypeError("'LinkItem' expected")

        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__canvasLink = parent
        self.setAcceptHoverEvents(True)

        self.shadow = QGraphicsDropShadowEffect(
            blurRadius=5, color=QColor(SHADOW_COLOR),
            offset=QPointF(0, 0)
        )

        self.normalPen = QPen(QBrush(QColor("#9CACB4")), 2.0)
        self.hoverPen = QPen(QBrush(QColor("#7D7D7D")), 2.1)
        self.setPen(self.normalPen)
        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        self.__hover = False

    def linkItem(self):
        """
        Return the :class:`LinkItem` instance this curve belongs to.
        """
        return self.__canvasLink

    def setHoverState(self, state):
        self.__hover = state
        self.__update()

    def setCurvePenSet(self, pen, hoverPen):
        if pen is not None:
            self.normalPen = pen
        if hoverPen is not None:
            self.hoverPen = hoverPen
        self.__update()

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemEnabledHasChanged:
            # Update the pen style
            self.__update()

        return QGraphicsPathItem.itemChange(self, change, value)

    def __update(self):
        shadow_enabled = self.__hover
        if self.shadow.isEnabled() != shadow_enabled:
            self.shadow.setEnabled(shadow_enabled)

        link_enabled = self.isEnabled()
        if link_enabled:
            pen_style = Qt.SolidLine
        else:
            pen_style = Qt.DashLine

        if self.__hover:
            pen = self.hoverPen
        else:
            pen = self.normalPen

        pen.setStyle(pen_style)
        self.setPen(pen)
Пример #17
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.group0 = QGroupBox()
        self.group0.setTitle(' Source ')
        self.source, self.infile = QComboBox(), QLineEdit(path.expanduser("~"))
        self.source.addItems(['Local File', 'Remote URL'])
        self.source.currentIndexChanged.connect(self.on_source_changed)
        self.infile.setPlaceholderText(' /full/path/to/file.html ')
        self.infile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to read from",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['html', 'webp', 'webm', 'svg', 'css', 'js', '*']])))))
        self.inurl, self.output = QLineEdit('http://www.'), QTextEdit()
        self.inurl.setPlaceholderText('http://www.full/url/to/remote/file.html')
        self.inurl.hide()
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (self.source, self.infile, self.open, self.inurl):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Mobile ')
        self.ckcss1 = QCheckBox('Run in full screen using current resolution')
        self.ckcss2 = QCheckBox('Disable touch mode and use keypad mode')
        self.ckcss3 = QCheckBox('Disable touch mode but allow to use the mouse')
        self.ckcss4 = QCheckBox('Enable mouse,disable pointer & zoom emulation')
        self.ckcss5 = QCheckBox('Start the Mobile version of the browser')
        self.ckcss6 = QCheckBox('Start the Tablet version of the browser')
        self.ckcss7 = QCheckBox('Emulate hardware with Menu and Back keys')
        self.ckcss8 = QCheckBox('Start the browser in Kiosk mode')
        self.width, self.height = QSpinBox(), QSpinBox()
        self.zoom, self.ram, self.dpi = QSpinBox(), QSpinBox(), QSpinBox()
        self.cpulag, self.gpulag = QSpinBox(), QSpinBox()
        self.lang, self.agent = QComboBox(), QComboBox()
        self.lang.addItems(['EN', 'ES', 'PT', 'JA', 'ZH', 'DE', 'RU', 'FR'])
        self.agent.addItems(['Default', 'Android', 'MeeGo', 'Desktop'])
        self.fonts = QLineEdit()
        self.width.setMaximum(9999)
        self.width.setMinimum(100)
        self.width.setValue(480)
        self.height.setMaximum(9999)
        self.height.setMinimum(100)
        self.height.setValue(800)
        self.zoom.setMaximum(999)
        self.zoom.setMinimum(1)
        self.zoom.setValue(100)
        self.ram.setMaximum(999)
        self.ram.setMinimum(1)
        self.ram.setValue(100)
        self.dpi.setMaximum(200)
        self.dpi.setMinimum(50)
        self.dpi.setValue(96)
        self.cpulag.setMaximum(9999)
        self.cpulag.setMinimum(0)
        self.cpulag.setValue(1)
        self.gpulag.setMaximum(9999)
        self.gpulag.setMinimum(0)
        self.gpulag.setValue(1)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
            self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
            QLabel('Width Pixels of the emulated device screen'), self.width,
            QLabel('Height Pixels of the emulated device screen'), self.height,
            QLabel('Zoom Percentage of emulated screen'), self.zoom,
            QLabel('RAM MegaBytes of the emulated device'), self.ram,
            QLabel('Language of the emulated device'), self.lang,
            QLabel('D.P.I. of the emulated device'), self.dpi,
            QLabel('User-Agent of the emulated device'), self.agent,
            QLabel('CPU Core Lag Miliseconds of emulated device'), self.cpulag,
            QLabel('GPU Video Lag Miliseconds of emulated device'), self.gpulag,
            QLabel('Extra Fonts Directory Full Path'), self.fonts):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(' General ')
        self.nice, self.opera = QSpinBox(), QLineEdit(path.expanduser("~"))
        self.nice.setValue(20)
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.opera.setCompleter(self.completer)
        if path.exists(CONFIG_FILE):
            with codecs.open(CONFIG_FILE, encoding='utf-8') as fp:
                self.opera.setText(fp.read())
        self.open2 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open2.setCursor(QCursor(Qt.PointingHandCursor))
        self.open2.clicked.connect(lambda: self.opera.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open Opera Mobile Emulator",
            path.expanduser("~"),
            'Opera Mobile Emulator Executable(opera-mobile-emulator)'))))
        self.help1 = QLabel('''<a href=
            "http://www.opera.com/developer/mobile-emulator">
            <small><center>Download Opera Mobile Emulator !</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group2)
        for each_widget in (QLabel(' Backend CPU priority: '), self.nice,
            QLabel(' Opera Mobile Emulator Full Path: '), self.opera,
            self.open2, self.help1):
            vboxg4.addWidget(each_widget)

        self.button = QPushButton('Preview on Mobile')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<b>Mobile Browser Emulator'),
            self.group0, self.group1, self.group2, self.output, self.button, ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Mobile")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
            HELPMSG))
Пример #18
0
class LinkCurveItem(QGraphicsPathItem):
    """
    Link curve item. The main component of a :class:`LinkItem`.
    """
    def __init__(self, parent):
        super().__init__(parent)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.setAcceptHoverEvents(True)

        self.shadow = QGraphicsDropShadowEffect(
            blurRadius=10, color=QColor(SHADOW_COLOR),
            offset=QPointF(0, 0)
        )

        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        self.__hover = False
        self.__enabled = True
        self.__shape = None
        self.__curvepath = QPainterPath()
        self.__curvepath_disabled = None
        self.__pen = self.pen()
        self.setPen(QPen(QBrush(QColor("#9CACB4")), 2.0))

    def setCurvePath(self, path):
        if path != self.__curvepath:
            self.prepareGeometryChange()
            self.__curvepath = QPainterPath(path)
            self.__curvepath_disabled = None
            self.__shape = None
            self.__update()

    def curvePath(self):
        return QPainterPath(self.__curvepath)

    def setHoverState(self, state):
        self.prepareGeometryChange()
        self.__hover = state
        self.__update()

    def setLinkEnabled(self, state):
        self.prepareGeometryChange()
        self.__enabled = state
        self.__update()

    def isLinkEnabled(self):
        return self.__enabled

    def setPen(self, pen):
        if self.__pen != pen:
            self.prepareGeometryChange()
            self.__pen = QPen(pen)
            self.__shape = None
            super().setPen(self.__pen)

    def shape(self):
        if self.__shape is None:
            path = self.curvePath()
            pen = QPen(QBrush(Qt.black),
                       max(self.pen().widthF(), 20),
                       Qt.SolidLine)
            self.__shape = stroke_path(path, pen)
        return self.__shape

    def setPath(self, path):
        self.__shape = None
        super().setPath(path)

    def __update(self):
        shadow_enabled = self.__hover
        if self.shadow.isEnabled() != shadow_enabled:
            self.shadow.setEnabled(shadow_enabled)
        basecurve = self.__curvepath
        link_enabled = self.__enabled
        if link_enabled:
            path = basecurve
        else:
            if self.__curvepath_disabled is None:
                self.__curvepath_disabled = path_link_disabled(basecurve)
            path = self.__curvepath_disabled

        self.setPath(path)
Пример #19
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file ')
        self.infile.returnPressed.connect(self.run)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.infile.setCompleter(self.completer)

        self.menu = QMenu('Base64')
        self.menu.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu, lang='all')

        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to Encode...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['*', 'jpg', 'png', 'webp', 'svg', 'gif', 'webm']])))))
        self.chckbx1 = QCheckBox('Use basic Caesar Cipher (ROT13)')
        self.chckbx1.setToolTip('Use "string".decode("rot13") to Decipher ! ')
        self.chckbx2 = QCheckBox('Use "data:type/subtype;base64,..."')
        self.chckbx2.setChecked(True)
        self.chckbx3 = QCheckBox('Copy encoded output to Clipboard')
        self.chckbx4 = QCheckBox('Use URL-Safe Base64 Encoder')
        self.combo1 = QComboBox()
        self.combo1.addItems(['Do Not Generate Code', 'Generate CSS embed Code',
            'Generate Python Embed Code', 'Generate HTML embed Code',
            'Generate JS embed Code', 'Generate QML embed Code'])
        self.combo1.currentIndexChanged.connect(self.combo_changed)

        self.output = QTextEdit('''
        We can only see a short distance ahead,
        but we can see plenty there that needs to be done.
        - Alan Turing ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton(QIcon.fromTheme("face-cool"), 'Encode BASE64')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>Encode file as plain text string</i>'),
            QLabel('<b>File to Encode:'), self.infile, self.open, self.chckbx2,
            self.chckbx3, self.chckbx1, self.chckbx4,
            QLabel('<b>Embedding Template Code:'), self.combo1,
            QLabel(' <b>Base64 String Output: '), self.output,
            QLabel('<center><small><i>' + ''.join((__doc__, __version__,
                   __license__, 'by', __author__))), self.button
        ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Base64")
        self.guimode = QComboBox(self.dock)
        self.guimode.addItems(['Full Mode', 'Simple Mode'])
        self.guimode.currentIndexChanged.connect(self.guimode_change)
Пример #20
0
class NodeBodyItem(GraphicsPathObject):
    """
    The central part (body) of the `NodeItem`.
    """
    def __init__(self, parent=None):
        GraphicsPathObject.__init__(self, parent)
        assert (isinstance(parent, NodeItem))

        self.__processingState = 0
        self.__progress = -1
        self.__animationEnabled = False
        self.__isSelected = False
        self.__hasFocus = False
        self.__hover = False
        self.__shapeRect = QRectF(-10, -10, 20, 20)

        self.setAcceptHoverEvents(True)

        self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)

        self.setPen(QPen(Qt.NoPen))

        self.setPalette(default_palette())

        self.shadow = QGraphicsDropShadowEffect(
            blurRadius=3,
            color=QColor(SHADOW_COLOR),
            offset=QPointF(0, 0),
        )

        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(True)

        self.__blurAnimation = QPropertyAnimation(self.shadow, "blurRadius",
                                                  self)
        self.__blurAnimation.setDuration(100)
        self.__blurAnimation.finished.connect(self.__on_finished)

        self.__pingAnimation = QPropertyAnimation(self, "scale", self)
        self.__pingAnimation.setDuration(250)
        self.__pingAnimation.setKeyValues([(0.0, 1.0), (0.5, 1.1), (1.0, 1.0)])

    # TODO: The body item should allow the setting of arbitrary painter
    # paths (for instance rounded rect, ...)
    def setShapeRect(self, rect):
        """
        Set the item's shape `rect`. The item should be confined within
        this rect.

        """
        path = QPainterPath()
        path.addEllipse(rect)
        self.setPath(path)
        self.__shapeRect = rect

    def setPalette(self, palette):
        """
        Set the body color palette (:class:`QPalette`).
        """
        self.palette = palette
        self.__updateBrush()

    def setAnimationEnabled(self, enabled):
        """
        Set the node animation enabled.
        """
        if self.__animationEnabled != enabled:
            self.__animationEnabled = enabled

    def setProcessingState(self, state):
        """
        Set the processing state of the node.
        """
        if self.__processingState != state:
            self.__processingState = state
            if not state and self.__animationEnabled:
                self.ping()

    def setProgress(self, progress):
        """
        Set the progress indicator state of the node. `progress` should
        be a number between 0 and 100.

        """
        self.__progress = progress
        self.update()

    def ping(self):
        """
        Trigger a 'ping' animation.
        """
        animation_restart(self.__pingAnimation)

    def hoverEnterEvent(self, event):
        self.__hover = True
        self.__updateShadowState()
        return GraphicsPathObject.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        self.__hover = False
        self.__updateShadowState()
        return GraphicsPathObject.hoverLeaveEvent(self, event)

    def paint(self, painter, option, widget):
        """
        Paint the shape and a progress meter.
        """
        # Let the default implementation draw the shape
        if option.state & QStyle.State_Selected:
            # Prevent the default bounding rect selection indicator.
            option.state = option.state ^ QStyle.State_Selected
        GraphicsPathObject.paint(self, painter, option, widget)
        if self.__progress >= 0:
            # Draw the progress meter over the shape.
            # Set the clip to shape so the meter does not overflow the shape.
            painter.setClipPath(self.shape(), Qt.ReplaceClip)
            color = self.palette.color(QPalette.ButtonText)
            pen = QPen(color, 5)
            painter.save()
            painter.setPen(pen)
            painter.setRenderHints(QPainter.Antialiasing)
            span = max(1, int(self.__progress * 57.60))
            painter.drawArc(self.__shapeRect, 90 * 16, -span)
            painter.restore()

    def __updateShadowState(self):
        if self.__hasFocus:
            color = QColor(FOCUS_OUTLINE_COLOR)
            self.setPen(QPen(color, 1.5))
        else:
            self.setPen(QPen(Qt.NoPen))

        radius = 3
        enabled = False

        if self.__isSelected:
            enabled = True
            radius = 7

        if self.__hover:
            radius = 17
            enabled = True

        if enabled and not self.shadow.isEnabled():
            self.shadow.setEnabled(enabled)

        if self.__animationEnabled:
            if self.__blurAnimation.state() == QPropertyAnimation.Running:
                self.__blurAnimation.pause()

            self.__blurAnimation.setStartValue(self.shadow.blurRadius())
            self.__blurAnimation.setEndValue(radius)
            self.__blurAnimation.start()
        else:
            self.shadow.setBlurRadius(radius)

    def __updateBrush(self):
        palette = self.palette
        if self.__isSelected:
            cg = QPalette.Active
        else:
            cg = QPalette.Inactive

        palette.setCurrentColorGroup(cg)
        c1 = palette.color(QPalette.Light)
        c2 = palette.color(QPalette.Button)
        grad = radial_gradient(c2, c1)
        self.setBrush(QBrush(grad))

    # TODO: The selected and focus states should be set using the
    # QStyle flags (State_Selected. State_HasFocus)

    def setSelected(self, selected):
        """
        Set the `selected` state.

        .. note:: The item does not have `QGraphicsItem.ItemIsSelectable` flag.
                  This property is instead controlled by the parent NodeItem.

        """
        self.__isSelected = selected
        self.__updateBrush()

    def setHasFocus(self, focus):
        """
        Set the `has focus` state.

        .. note:: The item does not have `QGraphicsItem.ItemIsFocusable` flag.
                  This property is instead controlled by the parent NodeItem.

        """
        self.__hasFocus = focus
        self.__updateShadowState()

    def __on_finished(self):
        if self.shadow.blurRadius() == 0:
            self.shadow.setEnabled(False)
Пример #21
0
class LinkCurveItem(QGraphicsPathItem):
    """
    Link curve item. The main component of a :class:`LinkItem`.
    """
    def __init__(self, parent):
        super().__init__(parent)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.setAcceptHoverEvents(True)

        self.shadow = QGraphicsDropShadowEffect(blurRadius=10,
                                                color=QColor(SHADOW_COLOR),
                                                offset=QPointF(0, 0))

        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(False)

        self.__hover = False
        self.__enabled = True
        self.__shape = None
        self.__curvepath = QPainterPath()
        self.__curvepath_disabled = None
        self.__pen = self.pen()
        self.setPen(QPen(QBrush(QColor("#9CACB4")), 2.0))

    def setCurvePath(self, path):
        if path != self.__curvepath:
            self.prepareGeometryChange()
            self.__curvepath = QPainterPath(path)
            self.__curvepath_disabled = None
            self.__shape = None
            self.__update()

    def curvePath(self):
        return QPainterPath(self.__curvepath)

    def setHoverState(self, state):
        self.prepareGeometryChange()
        self.__hover = state
        self.__update()

    def setLinkEnabled(self, state):
        self.prepareGeometryChange()
        self.__enabled = state
        self.__update()

    def isLinkEnabled(self):
        return self.__enabled

    def setPen(self, pen):
        if self.__pen != pen:
            self.prepareGeometryChange()
            self.__pen = QPen(pen)
            self.__shape = None
            super().setPen(self.__pen)

    def shape(self):
        if self.__shape is None:
            path = self.curvePath()
            pen = QPen(QBrush(Qt.black), max(self.pen().widthF(), 20),
                       Qt.SolidLine)
            self.__shape = stroke_path(path, pen)
        return self.__shape

    def setPath(self, path):
        self.__shape = None
        super().setPath(path)

    def __update(self):
        shadow_enabled = self.__hover
        if self.shadow.isEnabled() != shadow_enabled:
            self.shadow.setEnabled(shadow_enabled)
        basecurve = self.__curvepath
        link_enabled = self.__enabled
        if link_enabled:
            path = basecurve
        else:
            if self.__curvepath_disabled is None:
                self.__curvepath_disabled = path_link_disabled(basecurve)
            path = self.__curvepath_disabled

        self.setPath(path)
class NodeBodyItem(GraphicsPathObject):
    """
    The central part (body) of the `NodeItem`.
    """
    def __init__(self, parent=None):
        GraphicsPathObject.__init__(self, parent)
        assert(isinstance(parent, NodeItem))

        self.__processingState = 0
        self.__progress = -1
        self.__animationEnabled = False
        self.__isSelected = False
        self.__hasFocus = False
        self.__hover = False
        self.__shapeRect = QRectF(-10, -10, 20, 20)

        self.setAcceptHoverEvents(True)

        self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)

        self.setPen(QPen(Qt.NoPen))

        self.setPalette(default_palette())

        self.shadow = QGraphicsDropShadowEffect(
            blurRadius=3,
            color=QColor(SHADOW_COLOR),
            offset=QPointF(0, 0),
            )

        self.setGraphicsEffect(self.shadow)
        self.shadow.setEnabled(True)

        self.__blurAnimation = QPropertyAnimation(self.shadow, "blurRadius",
                                                  self)
        self.__blurAnimation.setDuration(100)
        self.__blurAnimation.finished.connect(self.__on_finished)

        self.__pingAnimation = QPropertyAnimation(self, "scale", self)
        self.__pingAnimation.setDuration(250)
        self.__pingAnimation.setKeyValues([(0.0, 1.0), (0.5, 1.1), (1.0, 1.0)])

    # TODO: The body item should allow the setting of arbitrary painter
    # paths (for instance rounded rect, ...)
    def setShapeRect(self, rect):
        """
        Set the item's shape `rect`. The item should be confined within
        this rect.

        """
        path = QPainterPath()
        path.addEllipse(rect)
        self.setPath(path)
        self.__shapeRect = rect

    def setPalette(self, palette):
        """
        Set the body color palette (:class:`QPalette`).
        """
        self.palette = palette
        self.__updateBrush()

    def setAnimationEnabled(self, enabled):
        """
        Set the node animation enabled.
        """
        if self.__animationEnabled != enabled:
            self.__animationEnabled = enabled

    def setProcessingState(self, state):
        """
        Set the processing state of the node.
        """
        if self.__processingState != state:
            self.__processingState = state
            if not state and self.__animationEnabled:
                self.ping()

    def setProgress(self, progress):
        """
        Set the progress indicator state of the node. `progress` should
        be a number between 0 and 100.

        """
        self.__progress = progress
        self.update()

    def ping(self):
        """
        Trigger a 'ping' animation.
        """
        animation_restart(self.__pingAnimation)

    def hoverEnterEvent(self, event):
        self.__hover = True
        self.__updateShadowState()
        return GraphicsPathObject.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        self.__hover = False
        self.__updateShadowState()
        return GraphicsPathObject.hoverLeaveEvent(self, event)

    def paint(self, painter, option, widget):
        """
        Paint the shape and a progress meter.
        """
        # Let the default implementation draw the shape
        if option.state & QStyle.State_Selected:
            # Prevent the default bounding rect selection indicator.
            option.state = option.state ^ QStyle.State_Selected
        GraphicsPathObject.paint(self, painter, option, widget)

        if self.__progress >= 0:
            # Draw the progress meter over the shape.
            # Set the clip to shape so the meter does not overflow the shape.
            painter.setClipPath(self.shape(), Qt.ReplaceClip)
            color = self.palette.color(QPalette.ButtonText)
            pen = QPen(color, 5)
            painter.save()
            painter.setPen(pen)
            painter.setRenderHints(QPainter.Antialiasing)
            span = int(self.__progress * 57.60)
            painter.drawArc(self.__shapeRect, 90 * 16, -span)
            painter.restore()

    def __updateShadowState(self):
        if self.__hasFocus:
            color = QColor(FOCUS_OUTLINE_COLOR)
            self.setPen(QPen(color, 1.5))
        else:
            self.setPen(QPen(Qt.NoPen))

        radius = 3
        enabled = False

        if self.__isSelected:
            enabled = True
            radius = 7

        if self.__hover:
            radius = 17
            enabled = True

        if enabled and not self.shadow.isEnabled():
            self.shadow.setEnabled(enabled)

        if self.__animationEnabled:
            if self.__blurAnimation.state() == QPropertyAnimation.Running:
                self.__blurAnimation.pause()

            self.__blurAnimation.setStartValue(self.shadow.blurRadius())
            self.__blurAnimation.setEndValue(radius)
            self.__blurAnimation.start()
        else:
            self.shadow.setBlurRadius(radius)

    def __updateBrush(self):
        palette = self.palette
        if self.__isSelected:
            cg = QPalette.Active
        else:
            cg = QPalette.Inactive

        palette.setCurrentColorGroup(cg)
        c1 = palette.color(QPalette.Light)
        c2 = palette.color(QPalette.Button)
        grad = radial_gradient(c2, c1)
        self.setBrush(QBrush(grad))

    # TODO: The selected and focus states should be set using the
    # QStyle flags (State_Selected. State_HasFocus)

    def setSelected(self, selected):
        """
        Set the `selected` state.

        .. note:: The item does not have `QGraphicsItem.ItemIsSelectable` flag.
                  This property is instead controlled by the parent NodeItem.

        """
        self.__isSelected = selected
        self.__updateBrush()

    def setHasFocus(self, focus):
        """
        Set the `has focus` state.

        .. note:: The item does not have `QGraphicsItem.ItemIsFocusable` flag.
                  This property is instead controlled by the parent NodeItem.

        """
        self.__hasFocus = focus
        self.__updateShadowState()

    def __on_finished(self):
        if self.shadow.blurRadius() == 0:
            self.shadow.setEnabled(False)
Пример #23
0
class QSwitch(QSlider):
    """ Custom Switch Widget, inspired from some QML desktop components """
    style_knob, style_off, style_on = qss_knob, qss_off, qss_on
    clicked, animationOk = pyqtSignal(), pyqtSignal()

    def __init__(self, parent=None):
        """ Init Custom Switch Widget, set Animation and Glow effects """
        QSlider.__init__(self, parent)
        self.setOrientation(Qt.Horizontal)
        self.animationType = QEasingCurve.OutExpo
        self.animation = QPropertyAnimation(self, "value")
        self.animation.setDuration(1000)
        self.animation.finished.connect(self.animationDone)
        self.clicked.connect(self.changeValue)
        self.setStyleSheet(self.style_knob + self.style_off)
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)

    def changeValue(self):
        """ method to change the actual state ON <--> OFF """
        self.animation.setEasingCurve(self.animationType)
        if self.value() == self.maximum():
            self.animation.setStartValue(self.maximum())
            self.animation.setEndValue(self.minimum())
            self.animation.start()
            self.setStyleSheet(self.style_knob + self.style_off)
            self.glow.setEnabled(False)
            return
        else:
            self.animation.setStartValue(self.minimum())
            self.animation.setEndValue(self.maximum())
            self.setStyleSheet(self.style_knob + self.style_on)
            self.glow.setEnabled(True)
        self.animation.start()

    @pyqtSignature("setAtMax()")
    def setAtMax(self):
        """ method to set at Maximum, aka ON """
        if self.value() == self.minimum():
            self.animation.setEasingCurve(self.animationType)
            self.animation.setStartValue(self.minimum())
            self.animation.setEndValue(self.maximum())
            self.animation.start()
            self.setStyleSheet(self.style_knob + self.style_on)

    @pyqtSignature("setAtMin()")
    def setAtMin(self):
        """ method to set at Minimum, aka OFF """
        if self.value() == self.maximum():
            self.animation.setEasingCurve(self.animationType)
            self.animation.setStartValue(self.maximum())
            self.animation.setEndValue(self.minimum())
            self.animation.start()
            self.setStyleSheet(self.style_knob + self.style_off)

    def mousePressEvent(self, event):
        """ method to respond a signal to mouse pointer clicks """
        self.clicked.emit()

    def isChecked(self):
        """ method to return a bool based on actual state """
        return self.value() == self.maximum()

    def wheelEvent(self, event):
        """ dumb method, its not a bug leave it alone """
        return

    def animationDone(self):
        """ method to respond a signal to animation effects """
        self.animationOk.emit()
Пример #24
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip(
            "Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Close
                                          | QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
Пример #25
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(600, 600)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip("Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Close |
            QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
Пример #26
0
class CImprovedPanel(QFrame):
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)

        #FADING
        self.__opacity_effect = QGraphicsOpacityEffect()
        self.__fading_timer = QTimer(parent)
        self.__fading_timer.timeout.connect(self.__on_fading_timer)
        self.__FADE_TYPE = Enum("IN", "OUT")
        self.__fade_time = 20
        self.__opacity = 1.0
        self.__opacity_fading_coefficient = 0.02
        self.__selected_fade_type = self.__FADE_TYPE.IN
        self.resizeEvent = self.__onResize

        #MOVE
        self.__move_animation_type = QEasingCurve.Linear
        self.__move_time = 350
        self.__is_moving = False

        #RESIZE
        self.__resize_animation_type = QEasingCurve.Linear
        self.__resize_time = 700
        self.__is_resizing = False

        #PIXMAP & MASCHERA
        self.__pmap = QPixmap(self.size())
        self.__pmap_fname = ""
        self.__show_mask_preview = False

        #SHADOW
        self.__shadow_Xoffset = 3.0 #default value
        self.__shadow_Yoffset = 3.0 #default value
        self.__shadow_blur_radius = 8.0 #default value
        self.__shadow_color = QColor(38,38,38,150) #default value

        self.__shadow_effect = QGraphicsDropShadowEffect()
        self.__shadow_effect.setXOffset(self.__shadow_Xoffset)
        self.__shadow_effect.setYOffset(self.__shadow_Yoffset)
        self.__shadow_effect.setBlurRadius(self.__shadow_blur_radius)
        self.__shadow_effect.setColor(self.__shadow_color)
        self._shadow_visible = False


    ##FUNZIONI PER FADING
    def fadeIn(self):
        """
         Labels fades in from completely invisible to completely visible.
        """
        self.__opacity = 0.0
        self.__selected_fade_type = self.__FADE_TYPE.IN
        self.__fading_timer.start(self.__fade_time)

    def fadeOut(self):
        """
         Labels fades out from completely visible to completely invisible.
        """
        self.__selected_fade_type = self.__FADE_TYPE.OUT
        self.__fading_timer.start(self.__fade_time)

    def setFadeTime(self, value):
        """ Sets fading time. Everytime interval is reached, alpha is increased (or decreased) by __opacity_fading_coefficient.
        @param value: fade time (msec)
        @type value: int
        """
        self.__fade_time = value

    def getFadeTime(self):
        return self.__fade_time

    fadeInterval = QtCore.pyqtProperty("int", getFadeTime, setFadeTime)

    def setFadeCoefficient(self, value):
        """ Sets fading coefficient. Alpha is increased (or decreased) by this value.
        @param value: coefficient (min 0.0 - max 1.0)
        @type value: float
        """
        self.__opacity_fading_coefficient = value

    def getFadeCoefficient(self):
        return self.__opacity_fading_coefficient

    fadeCoefficient = QtCore.pyqtProperty("double", getFadeCoefficient, setFadeCoefficient)

    def __on_fading_timer(self):
        if self.__selected_fade_type == self.__FADE_TYPE.OUT:
            if self.__opacity > 0:
                self.__opacity -= self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

        if self.__selected_fade_type == self.__FADE_TYPE.IN:
            if self.__opacity <= 1.0:
                self.__opacity += self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

    ## FUNZIONI PER SPOSTAMENTO VERSO PUNTO (ANIMATO)
    def setMoveAnimationType(self, animation_type):
        """ Sets move animation type.
        @param animation_type: animation type
        @type animation_type: QtEasingCurve
        """
        self.__move_animation_type = animation_type

    def getMoveAnimationType(self):
        return self.__move_animation_type

    #asd = QtCore.pyqtProperty("QEasingCurve", getMoveAnimationType, setMoveAnimationType)
    #sembra nn essere supportato per ora (06/05/2013)

    def setMoveTime(self, value):
        """ Sets animation moving time.
        @param value: animation time (duration) (msec)
        @type value: int
        """
        self.__move_time = value

    def getMoveTime(self):
        return self.__move_time

    moveTime = QtCore.pyqtProperty("int", getMoveTime, setMoveTime)

    def setResizeTime(self, value):
        """ Sets animation resize time.
        @param value: animation time (duration) (msec)
        @type value: int
        """
        self.__resize_time = value

    def getResizeTime(self):
        return self.__resize_time

    resizeTime = QtCore.pyqtProperty("int", getResizeTime, setResizeTime)

    def moveTo(self, x, y):
        """ Move itself to a given point with the given animation in the given duration.
        @param x: X point coordinate
        @type x: int
        @param y: Y point coordinate
        @type y: int
        """
        if self.__is_moving:
            return
        self.__is_moving = True
        self.__starting_position = QPoint(self.pos())
        self.__moveAnimation = QPropertyAnimation(self, "pos", self)
        self.__moveAnimation.finished.connect(self.__on_finished_moving)
        self.__moveAnimation.setDuration(self.__move_time)
        self.__moveAnimation.setEasingCurve(self.__move_animation_type)
        self.__moveAnimation.setStartValue(self.__starting_position)
        self.__moveAnimation.setEndValue(QPoint(x, y))
        self.__moveAnimation.start()


    def hideLeft(self):
        """ Panel hides sliding on the left. The slide amount is equal to his width - 5px.
        """
        dest_x = self.geometry().x() - self.width() - 5
        dest_y = self.geometry().y()
        self.moveTo(dest_x, dest_y)

    def showFromLeft(self):
        """ Panel shows sliding from the left. The slide amount is equal to his width + 5px.
        """
        dest_x = self.geometry().x() + self.width() + 5
        dest_y = self.geometry().y()
        self.moveTo(dest_x, dest_y)

    def hideRight(self):
        """ Panel hides sliding on the right. The slide amount is equal to his width - 5px.
        """
        dest_x = self.geometry().x() + self.width() + 5
        dest_y = self.geometry().y()
        self.moveTo(dest_x, dest_y)

    def showFromRight(self):
        """ Panel shows sliding from the right. The slide amount is equal to his width + 5px.
        """
        dest_x = self.geometry().x() - self.width() - 5
        dest_y = self.geometry().y()
        self.moveTo(dest_x, dest_y)

    def hideTop(self):
        """ Panel hides sliding on the top. The slide amount is equal to his height - 5px.
        """
        dest_x = self.geometry().x()
        dest_y = self.geometry().y() - self.height() - 5
        self.moveTo(dest_x, dest_y)

    def showFromTop(self):
        """ Panel shows sliding from the top. The slide amount is equal to his height - 5px.
        """
        dest_x = self.geometry().x()
        dest_y = self.geometry().y() + self.height() - 5
        self.moveTo(dest_x, dest_y)

    def hideBottom(self):
        """ Panel hides sliding to the bottom. The slide amount is equal to his height - 5px.
        """
        dest_x = self.geometry().x()
        dest_y = self.geometry().y() + self.height() + 5
        self.moveTo(dest_x, dest_y)

    def showFromBottom(self):
        """ Panel hides sliding from the bottom. The slide amount is equal to his height - 5px.
        """
        dest_x = self.geometry().x()
        dest_y = self.geometry().y() - self.height() - 5
        self.moveTo(dest_x, dest_y)

    def returnToOriginalPoint(self):
        """ Panel returns in its original position. The original position is stored when calling moveTo() method.
        """
        if self.__is_moving:
            return
        self.__is_moving = True
        self.__moveAnimation = QPropertyAnimation(self, "pos", self)
        self.__moveAnimation.finished.connect(self.__on_finished_moving)
        self.__moveAnimation.setDuration(self.__move_time)
        self.__moveAnimation.setEasingCurve(self.__move_animation_type)
        self.__moveAnimation.setStartValue(QPoint(self.pos().x(), self.pos().y()))
        self.__moveAnimation.setEndValue(self.__starting_position)
        self.__moveAnimation.start()

    #FUNZIONI PER RIDIMENSIONAMENTO
    def setResizeAnimationType(self, animation_type):
        """ Sets move animation type.
        @param animation_type: animation type
        @type animation_type: QtEasingCurve
        """
        self.__resize_animation_type = animation_type

    def resizeTo(self, width, height):
        """ Resize itself to a given size with the given animation in the given duration.
        @param width: New width
        @type width: int
        @param height: New height
        @type height: int
        """
        if self.__is_resizing:
            return
        self.__is_resizing = True
        self.__original_size = self.geometry()
        self.__resizeAnimation = QPropertyAnimation(self, "geometry", self)
        self.__resizeAnimation.finished.connect(self.__on_finished_resizing)
        self.__resizeAnimation.setDuration(self.__resize_time)
        self.__resizeAnimation.setEasingCurve(self.__resize_animation_type)
        self.__resizeAnimation.setStartValue(self.__original_size)
        self.__resizeAnimation.setEndValue(QRect(self.pos().x(), self.pos().y(), width, height))
        self.__resizeAnimation.start()

    def foldLeft(self):
        """ Panel hides folding to the left.
        """
        new_width = 0
        new_height = self.height()
        self.resizeTo(new_width, new_height)

    def unfoldLeft(self):
        """ Panel shows folding from the left.
        """
        new_width = self.__original_size.width()
        new_height = self.height()
        self.resizeTo(new_width, new_height)

    def foldTop(self):
        """ Panel hides folding to the top.
        """
        new_width = self.width()
        new_height = 0
        self.resizeTo(new_width, new_height)

    def unfoldTop(self):
        """ Panel shows folding from the top.
        """
        new_width = self.width()
        new_height = self.__original_size.height()
        self.resizeTo(new_width, new_height)

    #FUNZIONI PER PIXMAP & MASCHERA
    def setPixmapFile(self, image_file):
        self.__pmap = image_file
        self.__pmap.scaled(self.size())
        #NB: Il pixmap deve essere BIANCO e NERO. Con heuristicMask il primo pixel in alto a sinistra (0,0) viene
        #usato per decidere il colore trasparente, tutto il resto è visibile.

    def getPixmapFile(self):
        return self.__pmap

    pixmapFile = QtCore.pyqtProperty("QPixmap", getPixmapFile, setPixmapFile)


    def applyMask(self, bool):
        self.__show_mask_preview = bool
        if bool:
            self.setMask(QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))
        else:
            self.setMask(QBitmap())

    def getMask(self):
        return self.__show_mask_preview

    appliedMask = QtCore.pyqtProperty("bool", fget=getMask, fset=applyMask)

    def __on_finished_moving(self):
        self.__is_moving = False

    def __on_finished_resizing(self):
        self.__is_resizing = False

    def __onResize(self, event):
        self.__pmap.scaled(self.size())
        if self.__show_mask_preview:
            self.setMask(QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))

        #FUNZIONI PER SHADOW

    def getShadow(self):
        return self._shadow_visible

    def setShadow(self, bool):
        self.setGraphicsEffect(self.__shadow_effect)
        self._shadow_visible = bool
        self.__shadow_effect.setEnabled(bool)

    shadow = QtCore.pyqtProperty("bool", fget=getShadow, fset=setShadow)

    def setShadowXOffset(self, value):
        """ Sets shadow offset on X.
        @param value: offset
        @type value: float
        """
        self.__shadow_Xoffset = value
        self.__shadow_effect.setXOffset(self.__shadow_Xoffset)

    def getShadowXOffset(self):
        return self.__shadow_Xoffset

    shadowXOffset = QtCore.pyqtProperty("double", getShadowXOffset, setShadowXOffset)

    def setShadowYOffset(self, value):
        """ Sets shadow offset on Y.
        @param value: offset
        @type value: float
        """
        self.__shadow_Yoffset = value
        self.__shadow_effect.setYOffset(self.__shadow_Yoffset)

    def getShadowYOffset(self):
        return self.__shadow_Yoffset

    shadowYOffset = QtCore.pyqtProperty("double", getShadowYOffset, setShadowYOffset)


    def setShadowBlur(self, value):
        """ Sets blurred effect on item's shadow.
        @param value: coefficient
        @type value: float
        """
        self.__shadow_blur_radius = value
        self.__shadow_effect.setBlurRadius(self.__shadow_blur_radius)

    def getShadowBlur(self):
        return self.__shadow_blur_radius


    shadowBlur = QtCore.pyqtProperty("double", getShadowBlur, setShadowBlur)


    def setShadowColor(self, color):
        """ Sets shadow's color.
        @param color: value
        @type color: color
        """
        self.__shadow_color = color
        self.__shadow_effect.setColor(self.__shadow_color)

    def getShadowColor(self):
        return self.__shadow_color
Пример #27
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        ec = ExplorerContainer()
        super(Main, self).initialize(*args, **kwargs)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.RUNS, self.FAILS = 0, 0
        self.group0 = QGroupBox()
        self.group0.setTitle(' Source and Target ')
        self.baseurl = QLineEdit('http://google.com')
        self.outfile = QLineEdit(path.join(path.expanduser("~"), 'test.py'))
        self.outfile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.clicked.connect(lambda: self.outfile.setText(
            QFileDialog.getSaveFileName(self.dock, "Save", path.expanduser(
                "~"), 'PYTHON(*.py)')))
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (QLabel('<b>Base URL'), self.baseurl,
                            QLabel('<b>Local File Target'), self.outfile,
                            self.open):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Selenium ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_group)
        self.ckcss1 = QCheckBox('Test for correct Page Loading behaviour')
        self.ckcss2 = QCheckBox('Test for Sucessfull Status Code return')
        self.ckcss3 = QCheckBox('Test for valid Title of the web page')
        self.ckcss4 = QCheckBox('Test for Cookies Basic functionality')
        self.ckcss5 = QCheckBox('Test for Back, Forward, Reload behaviour')
        self.ckcss6 = QCheckBox('Take a Screenshot of page (CSS Debug)')
        self.ckcss7 = QCheckBox('Test for Search Form Field of the page')
        self.ckcss8 = QCheckBox(
            'Test for Arbitrary Javascript (User provided)')
        self.ckcss9 = QCheckBox('Test for iFrame of the web page')
        self.ckcss10 = QCheckBox('Test for HTML5 Canvas element on the page')
        self.ckcss11 = QCheckBox('Test for HTML5 SVG element on the page')
        self.ckcss12 = QCheckBox('Test for HTML5 Audio element on the page')
        self.ckcss13 = QCheckBox('Test for HTML5 Video element on the page')
        self.ckcss14 = QCheckBox('Test for File Upload form on the page')
        self.ckcss15 = QCheckBox('Add ChromeDriver path to sys.path')
        self.webdriver = QComboBox()
        self.webdriver.addItems(
            ['firefox', 'chrome', 'zope.testbrowser', 'phantomjs'])
        self.titletxt = QLineEdit('Google')
        self.javascript = QLineEdit('console.log("test")')
        self.authdata, self.formdata = QLineEdit(), QLineEdit()
        self.authdata.setPlaceholderText(
            "{'username':'******','password':'******'}")
        self.formdata.setPlaceholderText("{'name': 'Joe', 'age': '25'}")
        self.iframurl = QLineEdit()
        self.chrmedrv = QLineEdit('/usr/bin/chromedriver')
        self.timeout = QSpinBox()
        self.timeout.setMaximum(99)
        self.timeout.setMinimum(0)
        self.timeout.setValue(9)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
                self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                self.ckcss9, self.ckcss10, self.ckcss11,
                self.ckcss12, self.ckcss13, self.ckcss14, self.ckcss15,
                QLabel('<b>WebDriver'), self.webdriver,
                QLabel('''<center><small><i>Firefox is only Driver that dont
                   require additional configuration'''),
                QLabel('<b>Title Content must contain'), self.titletxt,
                QLabel('<b>Minified Javascript for Test'), self.javascript,
                QLabel('<b>Arbitrary Authentication Data for Test'),
                self.authdata, QLabel('<b>Arbitrary Form Data for Test'),
                self.formdata, QLabel('<b>iFrame URL for Test'), self.iframurl,
                QLabel('<b>Chrome Driver'), self.chrmedrv,
                QLabel('<b>Timeout Timer Limit'), self.timeout):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())

        self.group4 = QGroupBox()
        self.group4.setTitle(' General ')
        self.chckbx1 = QCheckBox('Run the Tests after Writing')
        self.chckbx2 = QCheckBox('Open the Tests with Ninja after Writing')
        self.chckbx3 = QCheckBox('Add SheBang, Encoding and Metadata to Tests')
        self.nice = QSpinBox()
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.nice.setValue(20)
        self.help1 = QLabel(
            '''<a href="http://splinter.cobrateam.info/docs/api"
            ><center><b>API Reference</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (self.chckbx1, self.chckbx2, self.chckbx3,
                            QLabel('Backend CPU priority:'), self.nice,
                            self.help1):
            vboxg4.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        [
            a.setChecked(True)
            for a in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                      self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                      self.ckcss15, self.chckbx1, self.chckbx2, self.chckbx3)
        ]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Write and Run Test')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)
        self.output = QPlainTextEdit()
        self.runs = QLabel('<font color="green"><b>Runs: 0')
        self.failures = QLabel('<font color="red"><b>Failures: 0')

        class TransientWidget(QWidget):
            ' persistant widget thingy '

            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget(
            (QLabel('<b>Selenium Tests'), self.group0, self.group1,
             self.group4, QLabel('<b>Log'), self.output, self.runs,
             self.failures, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ec.addTab(self.dock, "Selenium")
        QPushButton(
            QIcon.fromTheme("help-about"), 'About', self.dock).clicked.connect(
                lambda: QMessageBox.information(self.dock, __doc__, HELPMSG))
        QPushButton(
            QIcon.fromTheme("media-record"),
            'Record',
            self.group1,
        ).clicked.connect(lambda: QMessageBox.information(
            self.dock, __doc__,
            'Not working. If you know how to make it Record, send me Pull Request'
        ))