Esempio n. 1
0
 def mouseDoubleClickEvent(self, e):
     super(View, self).mouseDoubleClickEvent(e)
     app = QtGui.QApplication.instance()
     self.tripleClickTimer.start(app.doubleClickInterval(), self)
     # make a copy here, otherwise tripleClickPoint will always = globalPos
     self.tripleClickPoint = QtCore.QPoint(e.globalPos())
Esempio n. 2
0
 def on_fetch_top_left(self,i):
     self.area.set_marker(self.transFormMatrix.map(QtCore.QPoint(self.spin_transformation_a_x.value(),self.spin_transformation_a_y.value())),False)
     self.transformationPointState = TransfomationPointState.TopLeft
Esempio n. 3
0
    def event(self, e):
        """ event(e: QEvent) -> depends on event type
        Handle movement of the dock widget to snap to the tab controller

        """
        # MOUSE PRESS (QtCore.QEvent.NonClientAreaMouseButtonPress=174)
        if e.type() in [QtCore.QEvent.MouseButtonPress,174]:
            if e.type()==174:
                gp = QtGui.QCursor.pos()
                ontitle = True
            else:
                gp = e.globalPos()
                ontitle = e.y()<self.widget().y() and e.buttons()&QtCore.Qt.LeftButton
            if ontitle:
                self.startDragPos = QtCore.QPoint(gp)
                self.grabMouse()
            return True

        elif e.type()==QtCore.QEvent.MouseMove:
            if not (e.buttons() & QtCore.Qt.LeftButton):
                self.windowRubberBand.hide()
                self.setMouseTracking(False)
                return QtGui.QDockWidget.event(self, e)
            gp = e.globalPos()
            if (not self.startDragging and
                self.startDragPos and
                (self.startDragPos-gp).manhattanLength()>=4):
                self.startDragging = True
                self.windowRubberBand.setGeometry(self.geometry())
                self.startDragPos = self.pos()-gp
                self.windowRubberBand.show()
                self.setMouseTracking(True)
            if self.startDragging:
                tb = QtGui.QApplication.widgetAt(gp)
                if tb==self.tabBar:
                    idx = tb.slotIndex(gp)
                    if idx>=0:
                        self.windowRubberBand.setGeometry(tb.slotGeometry(idx))
                elif (tb!=None and self.tabController.count()==0 and
                      self.isTabControllerUnderMouse(tb)):
                    r = self.tabController.frameGeometry()
                    r.moveTo(self.tabController.mapToGlobal(r.topLeft()))
                    self.windowRubberBand.setGeometry(r)
                else:
                    rect = QtCore.QRect(self.startDragPos+gp, self.size())
                    self.windowRubberBand.setGeometry(rect)
            return True

        # MOUSE RELEASE (QtCore.QEvent.NonClientAreaMouseRelease=175)
        elif e.type()==QtCore.QEvent.MouseButtonRelease:
            if self.startDragging:
                if e.type()==173:
                    gp = QtGui.QCursor.pos()
                else:
                    gp = e.globalPos()
                self.setMouseTracking(False)
                self.windowRubberBand.hide()
                self.startDragPos = None
                self.startDragging = False
                tb = QtGui.QApplication.widgetAt(gp)
                if tb==self.tabBar:
                    idx = tb.slotIndex(gp)
                    if idx>=0:
                        self.hide()
                        self.tabController.mergeTab(self, idx)
                elif (tb!=None and self.tabController.count()==0 and
                      self.isTabControllerUnderMouse(tb)):
                    self.hide()
                    self.tabController.mergeTab(self, 0)
                else:
                    self.move(self.windowRubberBand.pos())
            self.releaseMouse()
            self.setFocus(QtCore.Qt.MouseFocusReason)
            return True

        # MOUSE DOUBLE CLICK (QtCore.QEvent.NonClientAreaMouseButtonDblClick=176)
        elif e.type() in [QtCore.QEvent.MouseButtonDblClick, 176]:
            if (e.type()==176) or (e.buttons()&QtCore.Qt.LeftButton):
                self.hide()
                self.tabController.mergeTab(self, self.tabController.count())
                return True

        return QtGui.QDockWidget.event(self, e)
Esempio n. 4
0
class RenderArea(QtGui.QWidget):
    points = QtGui.QPolygon([
        QtCore.QPoint(10, 80),
        QtCore.QPoint(20, 10),
        QtCore.QPoint(80, 30),
        QtCore.QPoint(90, 70)
    ])

    Line, Points, Polyline, Polygon, Rect, RoundRect, Ellipse, Arc, \
    Chord, Pie, Path, Text, Pixmap = range(13)

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.shape = RenderArea.Polygon
        self.pen = QtGui.QPen()
        self.brush = QtGui.QBrush()
        self.antialiased = False
        self.transformed = False
        self.pixmap = QtGui.QPixmap()
        self.pixmap.load(":/images/qt-logo.png")

        self.setBackgroundRole(QtGui.QPalette.Base)

    def minimumSizeHint(self):
        return QtCore.QSize(100, 100)

    def sizeHint(self):
        return QtCore.QSize(400, 200)

    def setShape(self, shape):
        self.shape = shape
        self.update()

    def setPen(self, pen):
        self.pen = pen
        self.update()

    def setBrush(self, brush):
        self.brush = brush
        self.update()

    def setAntialiased(self, antialiased):
        self.antialiased = antialiased
        self.update()

    def setTransformed(self, transformed):
        self.transformed = transformed
        self.update()

    def paintEvent(self, event):
        rect = QtCore.QRect(10, 20, 80, 60)

        path = QtGui.QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QtGui.QPainter()
        painter.begin(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QtGui.QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundRect:
                    painter.drawRoundRect(rect)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, QtCore.Qt.AlignCenter,
                                     self.tr("Qt by\nTrolltech"))
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.end()
    def __init__(self,node=nuke.root(),knob="knobChanged"):

        super(KnobScripter,self).__init__()
        self.node = node
        self.knob = knob
        self.unsavedKnobs = {}
        self.scrollPos = {}
        self.fontSize = 11
        self.tabSpaces = 4
        self.windowDefaultSize = [500, 300]
        self.pinned = 1
        self.toLoadKnob = True

        # Load prefs
        self.prefs_txt = os.path.expandvars(os.path.expanduser("~/.nuke/KnobScripter_prefs_"+version+".txt"))
        self.loadedPrefs = self.loadPrefs()
        if self.loadedPrefs != []:
            try:
                self.fontSize = self.loadedPrefs['font_size']
                self.windowDefaultSize = [self.loadedPrefs['window_default_w'], self.loadedPrefs['window_default_h']]
                self.tabSpaces = self.loadedPrefs['tab_spaces']
                self.pinned = self.loadedPrefs['pin_default']
            except TypeError:
                print("KnobScripter: Failed to load preferences.")

        # KnobScripter Panel
        self.resize(self.windowDefaultSize[0],self.windowDefaultSize[1])
        self.setWindowTitle("KnobScripter - %s %s" % (self.node.fullName(),self.knob))
        self.move(QtGui.QCursor().pos() - QtCore.QPoint(32,74))

        # Node/Knob Selection menu
        self.current_node_label = QtGuiWidgets.QLabel("Node: <b> %s </b>"%self.node.fullName())
        self.current_node_change_button = QtGuiWidgets.QPushButton("Change")
        self.current_node_change_button.setToolTip("Change node to selected")
        self.current_node_change_button.clicked.connect(self.changeNode)
        self.current_knob_label = QtGuiWidgets.QLabel("Knob: ")
        self.current_knob_dropdown = QtGuiWidgets.QComboBox()
        self.current_knob_dropdown.setSizeAdjustPolicy(QtGuiWidgets.QComboBox.AdjustToContents)
        self.updateKnobDropdown()
        self.current_knob_dropdown.currentIndexChanged.connect(lambda: self.loadKnobValue(False,updateDict=True))
        self.current_knob_prefs_button = QtGuiWidgets.QPushButton("Preferences")
        self.current_knob_prefs_button.clicked.connect(self.openPrefs)

        # Script Editor (adapted from Wouter Gilsing's, read class definition below)
        self.scriptEditorScript = KnobScripterEditorWidget(self)
        self.scriptEditorScript.setMinimumHeight(100)
        self.scriptEditorScript.setStyleSheet('background:#282828;color:#EEE;') # Main Colors
        KSScriptEditorHighlighter(self.scriptEditorScript.document())
        self.scriptEditorFont = QtGui.QFont()
        self.scriptEditorFont.setFamily("Courier")
        self.scriptEditorFont.setStyleHint(QtGui.QFont.Monospace)
        self.scriptEditorFont.setFixedPitch(True)
        self.scriptEditorFont.setPointSize(self.fontSize)
        self.scriptEditorScript.setFont(self.scriptEditorFont)
        self.scriptEditorScript.setTabStopWidth(self.tabSpaces * QtGui.QFontMetrics(self.scriptEditorFont).width(' '))

        # Lower Buttons
        self.get_btn = QtGuiWidgets.QPushButton("Reload")
        self.get_btn.setToolTip("Reload the contents of the knob. Will overwrite the KnobScripter's script.")
        self.get_all_btn = QtGuiWidgets.QPushButton("Reload All")
        self.get_all_btn.setToolTip("Reload the contents of all knobs. Will clear the KnobScripter's memory.")
        self.arrows_label = QtGuiWidgets.QLabel("&raquo;")
        self.arrows_label.setTextFormat(QtCore.Qt.RichText)
        self.arrows_label.setStyleSheet('color:#BBB')
        self.set_btn = QtGuiWidgets.QPushButton("Save")
        self.set_btn.setToolTip("Save the script above into the knob. It won't be saved until you click this button.")
        self.set_all_btn = QtGuiWidgets.QPushButton("Save All")
        self.set_all_btn.setToolTip("Save all changes into the knobs.")
        self.pin_btn = QtGuiWidgets.QPushButton("PIN")
        self.pin_btn.setCheckable(True)
        if self.pinned:
            self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
            self.pin_btn.toggle()
        self.pin_btn.setToolTip("Keep the KnobScripter on top of all other windows.")
        self.pin_btn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.pin_btn.setMaximumWidth(self.pin_btn.fontMetrics().boundingRect("pin").width() + 12)
        self.close_btn = QtGuiWidgets.QPushButton("Close")
        self.get_btn.clicked.connect(self.loadKnobValue)
        self.get_all_btn.clicked.connect(self.loadAllKnobValues)
        self.set_btn.clicked.connect(lambda: self.saveKnobValue(False))
        self.set_all_btn.clicked.connect(self.saveAllKnobValues)
        self.pin_btn.clicked[bool].connect(self.pin)
        self.close_btn.clicked.connect(self.close)

        # Layouts
        master_layout = QtGuiWidgets.QVBoxLayout()
        nodeknob_layout = QtGuiWidgets.QHBoxLayout()
        nodeknob_layout.addWidget(self.current_node_label)
        nodeknob_layout.addWidget(self.current_node_change_button)
        nodeknob_layout.addSpacing(10)
        nodeknob_layout.addWidget(self.current_knob_label)
        nodeknob_layout.addWidget(self.current_knob_dropdown)
        nodeknob_layout.addSpacing(10)
        nodeknob_layout.addStretch()
        nodeknob_layout.addWidget(self.current_knob_prefs_button)
        self.btn_layout = QtGuiWidgets.QHBoxLayout()
        self.btn_layout.addWidget(self.get_btn)
        self.btn_layout.addWidget(self.get_all_btn)
        self.btn_layout.addWidget(self.arrows_label)
        self.btn_layout.addWidget(self.set_btn)
        self.btn_layout.addWidget(self.set_all_btn)
        self.btn_layout.addStretch()
        self.btn_layout.addWidget(self.pin_btn)
        self.btn_layout.addWidget(self.close_btn)
        master_layout.addLayout(nodeknob_layout)
        master_layout.addWidget(self.scriptEditorScript)
        master_layout.addLayout(self.btn_layout)
        self.setLayout(master_layout)

        # Set default values
        self.setCurrentKnob(self.knob)
        self.loadKnobValue(check = False)
        self.scriptEditorScript.setFocus()
Esempio n. 6
0
    def initializePuzzleRepresentation(self):
        self.scene = QtGui.QGraphicsScene(self)

        #        self.view.setScene(self.scene)
        self.puzzlePieces = {}

        self.hexSide = 100
        #self.blockPadding = 3

        self.selectedItems = set()

        for c in self.puzzle.getGrid().getCells():
            if (c.getPosition):

                # see for an explanation of the rotated version (i.e. horizontal iso vertical):
                # http://www.gamedev.net/page/resources/_/technical/game-programming/coordinates-in-hexagon-based-tile-maps-r1800
                tileR = self.hexSide / 2 * cos(pi / 6)
                hexH = self.hexSide / 2 * sin(pi / 6)
                #tileW = 2 * tileR
                #tileH = self.hexSide/2 + 2 * hexH

                pos = c.getPosition()
                if (pos.x() % 2):
                    hexPos = QtCore.QPointF(
                        pos.x() * (hexH + self.hexSide / 2),
                        pos.y() * 2 * tileR + tileR)
                else:
                    hexPos = QtCore.QPointF(
                        pos.x() * (hexH + self.hexSide / 2),
                        pos.y() * 2 * tileR)

                rect = ValueHexagon(c, self.hexSide, hexPos)
                self.scene.addItem(rect)
                c.valueChanged.connect(self.cellValueChanged)
                c.possibleValuesChanged.connect(self.cellPossibleValuesChanged)
                self.puzzlePieces[c] = rect
                proxy = PuzzlePieceProxy(rect)
                self.puzzlePieceProxies[c] = proxy

        for cg in self.puzzle.getConstraintGroups():
            for constraint in cg.getConstraints():
                if isinstance(constraint, TotalSumValueConstraint):
                    # TODO: refactor to utililty class, make much more general
                    # find the position and direction that is most likely:

                    if (cg.name.startswith('Column')):
                        cell = cg.getCells()[0]
                        pos = QtCore.QPoint(cell.position.x(), -1)
                    else:
                        pos = QtCore.QPoint(-1, cell.position.y())

                    if (pos.x() % 2):
                        hexPos = QtCore.QPointF(
                            pos.x() * (hexH + self.hexSide / 2),
                            pos.y() * 2 * tileR + tileR)
                    else:
                        hexPos = QtCore.QPointF(
                            pos.x() * (hexH + self.hexSide / 2),
                            pos.y() * 2 * tileR)

                    hex = ValueHexagon(constraint,
                                       self.hexSide,
                                       hexPos,
                                       edgeColor=QtCore.Qt.transparent)
                    self.puzzlePieces[constraint] = hex
                    self.scene.addItem(hex)
Esempio n. 7
0
 def mouseMoveEvent(self, event):
     if event.buttons() & QtCore.Qt.LeftButton:
         self.pixmapOffset += event.pos() - self.lastDragPos
         self.lastDragPos = QtCore.QPoint(event.pos())
         self.update()
Esempio n. 8
0
 def additems(self):
     n = Node(self, "pc", QtCore.QPoint(10, 10))
     n.show()
     self.items.append(n)
Esempio n. 9
0
 def setCursorPos(self, x, y):
     self.cursor().setPos(self.mapToGlobal(QtCore.QPoint(x, y)))
Esempio n. 10
0
 def mousePressEvent(self, event):
     if event.buttons() == QtCore.Qt.LeftButton:
         self.lastDragPos = QtCore.QPoint(event.pos())
Esempio n. 11
0
    def createCurveIcons(self):
        pix = QtGui.QPixmap(self.m_iconSize)
        painter = QtGui.QPainter()

        gradient = QtGui.QLinearGradient(0, 0, 0, self.m_iconSize.height())
        gradient.setColorAt(0.0, QtGui.QColor(240, 240, 240))
        gradient.setColorAt(1.0, QtGui.QColor(224, 224, 224))

        brush = QtGui.QBrush(gradient)

        # The original C++ code uses undocumented calls to get the names of the
        # different curve types.  We do the Python equivalant (but without
        # cheating)
        curve_types = [(n, c) for n, c in QtCore.QEasingCurve.__dict__.items()
                        if isinstance(c, QtCore.QEasingCurve.Type) \
                            and c != QtCore.QEasingCurve.Custom    \
                            and c != QtCore.QEasingCurve.NCurveTypes]
        curve_types.sort(key=lambda ct: ct[1])

        painter.begin(pix)

        for curve_name, curve_type in curve_types:
            painter.fillRect(
                QtCore.QRect(QtCore.QPoint(0, 0), self.m_iconSize), brush)
            curve = QtCore.QEasingCurve(curve_type)

            painter.setPen(QtGui.QColor(0, 0, 255, 64))
            xAxis = self.m_iconSize.height() / 1.5
            yAxis = self.m_iconSize.width() / 3.0
            painter.drawLine(0, xAxis, self.m_iconSize.width(), xAxis)
            painter.drawLine(yAxis, 0, yAxis, self.m_iconSize.height())

            curveScale = self.m_iconSize.height() / 2.0

            painter.setPen(QtCore.Qt.NoPen)

            # Start point.
            painter.setBrush(QtCore.Qt.red)
            start = QtCore.QPoint(
                yAxis, xAxis - curveScale * curve.valueForProgress(0))
            painter.drawRect(start.x() - 1, start.y() - 1, 3, 3)

            # End point.
            painter.setBrush(QtCore.Qt.blue)
            end = QtCore.QPoint(yAxis + curveScale,
                                xAxis - curveScale * curve.valueForProgress(1))
            painter.drawRect(end.x() - 1, end.y() - 1, 3, 3)

            curvePath = QtGui.QPainterPath()
            curvePath.moveTo(QtCore.QPointF(start))
            t = 0.0
            while t <= 1.0:
                to = QtCore.QPointF(
                    yAxis + curveScale * t,
                    xAxis - curveScale * curve.valueForProgress(t))
                curvePath.lineTo(to)
                t += 1.0 / curveScale

            painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
            painter.strokePath(curvePath, QtGui.QColor(32, 32, 32))
            painter.setRenderHint(QtGui.QPainter.Antialiasing, False)

            item = QtGui.QListWidgetItem()
            item.setIcon(QtGui.QIcon(pix))
            item.setText(curve_name)
            self.m_ui.easingCurvePicker.addItem(item)

        painter.end()
Esempio n. 12
0
    def paintEvent(self, event):
        geometry = self.geometry()
        self.W = geometry.width()
        self.H = geometry.height()-100   # space for lower bound

        (jobs, shares, totals) = (self.jobs, self.shares, self.totals)

        # print "paintEvent"
        qp = QtGui.QPainter()

        qp.begin(self)

        # background 
        qp.setPen(QtGui.QPen(QtGui.QColor("black")))
        qp.drawRect(0, 0, self.W-1, self.H-1+100)

        # polygons

        off = [0, 0, 0, 0]
        lastline = [ QtCore.QPoint(0,0), QtCore.QPoint(0,0), QtCore.QPoint(0,0), QtCore.QPoint(0,0), 
                     QtCore.QPoint(0,0), QtCore.QPoint(0,0), QtCore.QPoint(0,0), QtCore.QPoint(self.W,0) ]

        # mouseras contains tuples with y coordinates for jobnames
        self.mouseareas={}
        self.mouseareas["nodes"] = {}
        self.mouseareas["meta"]  = {}
        self.mouseareas["rqs"]   = {}
        self.mouseareas["bw"]    = {}

        counter = 1
        for job in jobs:
            j = job.name
            newline = [
                        # size
                        QtCore.QPoint(0 * self.W/8, self.H*shares[j]["nodes"] + off[0]),
                        QtCore.QPoint(2 * self.W/8, self.H*shares[j]["nodes"] + off[0]),
                        # transition
                        QtCore.QPoint(3 * self.W/8, self.H*shares[j]["meta"] + off[1]),
                        # meta
                        QtCore.QPoint(4 * self.W/8, self.H*shares[j]["meta"] + off[1]),
                        # transition
                        QtCore.QPoint(5 * self.W/8, self.H*shares[j]["rqs"] + off[2]),
                        # rqs
                        QtCore.QPoint(6 * self.W/8, self.H*shares[j]["rqs"] + off[2]),
                        # transition
                        QtCore.QPoint(7 * self.W/8, self.H*shares[j]["bw"] + off[3]),
                        # bw
                        QtCore.QPoint(8 * self.W/8, self.H*shares[j]["bw"] + off[3]),
                      ]

            self.mouseareas["nodes"][j] = (off[0], off[0]+self.H*shares[j]["nodes"])
            self.mouseareas["meta"][j]  = (off[1], off[1]+self.H*shares[j]["meta"])
            self.mouseareas["rqs"][j]   = (off[2], off[2]+self.H*shares[j]["rqs"])
            self.mouseareas["bw"][j]    = (off[3], off[3]+self.H*shares[j]["bw"])

            off[0] += self.H*shares[j]["nodes"]
            off[1] += self.H*shares[j]["meta"]
            off[2] += self.H*shares[j]["rqs"]
            off[3] += self.H*shares[j]["bw"]

            points=[]
            points.extend(list(reversed(lastline)))
            points.extend(newline)  

            lastline = newline
	        
            # print counter
            brush = QtGui.QBrush(QtGui.QColor(*rgb(1,len(jobs),len(jobs)-counter+1)))
            qp.setBrush(brush)
            pen = QtGui.QPen(QtGui.QColor(*rgb(1,len(jobs),len(jobs)-counter+1)))
            qp.setPen(pen)
            qp.drawPolygon(points, QtCore.Qt.OddEvenFill)

            # labels
            pen = QtGui.QPen(QtGui.QColor(0,0,0,255))
            qp.setPen(pen)
            qp.setFont(QtGui.QFont('Decorative', FONTSIZE))
            displayed=False
            # name + owner + nodes
            if self.H*shares[j]["nodes"] > FONTSIZE:
                qp.drawText(10, off[0], j.split("-")[0])
                qp.drawText(150, off[0], job.owner)
                qp.drawText(250, off[0], str(job.nodes)+" nodes")
                displayed=True

            # meta
            if self.H*shares[j]["meta"] > FONTSIZE:
                qp.drawText(2 + 3 * self.W/8, off[1], str(job.meta)+" meta ops/s")
                if (not displayed and (self.H*shares[j]["meta"] > FONTSIZE * 2)) or (self.H*shares[j]["meta"] > FONTSIZE * 3):
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE-2))
                    qp.drawText(2 + 3 * self.W/8, off[1]-FONTSIZE-2, j.split("-")[0]+" "+job.owner)
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE))
                    displayed=True

            # rqs
            if self.H*shares[j]["rqs"] > FONTSIZE:
                qp.drawText(2 + 5 * self.W/8, off[2], str(job.wrqs+job.rrqs)+" iops/s")
                if (not displayed and (self.H*shares[j]["rqs"] > FONTSIZE * 2)) or (self.H*shares[j]["rqs"] > FONTSIZE * 3):
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE-2))
                    qp.drawText(2 + 5 * self.W/8, off[2]-FONTSIZE-2, j.split("-")[0]+" "+job.owner)
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE))
                    displayed=True
                if self.H*shares[j]["rqs"] > FONTSIZE * 4:
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE-3))
                    qp.drawText(2 + 5 * self.W/8, off[2]-2*FONTSIZE-2, "read %-1.2f" % (job.rrqs))
                    qp.drawText(2 + 5 * self.W/8, off[2]-3*FONTSIZE-2, "write %-1.2f" % (job.wrqs))
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE))
                
            # bw
            if self.H*shares[j]["bw"] > FONTSIZE:
                (bw,unit) = normalize_bw(job.wbw+job.rbw)
                qp.drawText(2 + 7 * self.W/8, off[3], "%-1.2f" % (bw)+unit)
                if (not displayed and (self.H*shares[j]["bw"] > FONTSIZE * 2)) or (self.H*shares[j]["bw"] > FONTSIZE * 3):
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE-2))
                    qp.drawText(2 + 7 * self.W/8, off[3]-FONTSIZE-2, j.split("-")[0]+" "+job.owner)
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE))
                    displayed=True
                if self.H*shares[j]["bw"] > FONTSIZE * 4:
                    (wbw,wunit) = normalize_bw(job.wbw)
                    (rbw,runit) = normalize_bw(job.rbw)
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE-3))
                    qp.drawText(2 + 7 * self.W/8, off[3]-2*FONTSIZE-2, "read %-1.2f%s" % (rbw,runit))
                    qp.drawText(2 + 7 * self.W/8, off[3]-3*FONTSIZE-2, "write %-1.2f%s" % (wbw,wunit))
                    qp.setFont(QtGui.QFont('Decorative', FONTSIZE))



            counter += 1

        # fill remainder at bottom (in case the X jobs do not fill the 100%)
        
        newline = [ QtCore.QPoint(0,self.H), QtCore.QPoint(self.W,self.H) ]
        points=[]
        points.extend(list(reversed(lastline)))
        points.extend(newline)  
        brush = QtGui.QBrush(QtGui.QColor(180,180,180))
        qp.setBrush(brush)
        pen = QtGui.QPen(QtGui.QColor(200,200,200))
        qp.setPen(pen)
        qp.drawPolygon(points, QtCore.Qt.OddEvenFill)

        # search maxima
        
        changed = False
        for i in range(0,6):
            if totals[i] > self.maxima[i]:
                self.maxima[i] = totals[i]
                changed = True
        # update DB
        if changed:
            self.fs.writeFSMaxima(self.maxima)

        # print totals

        pen = QtGui.QPen(QtGui.QColor(0,0,0,255))
        qp.setPen(pen)
        brush = QtGui.QBrush(QtGui.QColor(0,0,0,0))
        qp.setBrush(brush)
        qp.setFont(QtGui.QFont('Decorative', FONTSIZE+2))
        qp.drawText(10, self.H+30, self.fsname+" TOTAL")
        setHeatMapColor(qp, 0, self.maxima[0],totals[0])
        qp.drawText(250, self.H+30, str(totals[0])+" nodes")
        s = 98.0*(float(totals[0])/float(self.maxima[0]))
        qp.drawRect(250-20, self.H+100-s-1, 10, s)

        # meta + bar
        setHeatMapColor(qp, 0, self.maxima[1],totals[1])
        qp.drawText(2 + 3 * self.W/8, self.H+30, str(totals[1])+" meta ops/s")
        s = 98.0*(float(totals[1])/float(self.maxima[1]))
        qp.drawRect(2 + 3 * self.W/8-20, self.H+100-s-1, 10, s)

        qp.setFont(QtGui.QFont('Decorative', (FONTSIZE+1)))

        # write iops + bar
        setHeatMapColor(qp, 0, self.maxima[2],totals[2])
        qp.drawText(2 + 5 * self.W/8, self.H+20, str(totals[2])+" write iops/s")
        s = 98.0*(float(totals[2])/float(self.maxima[2]))
        qp.drawRect(2 + 5 * self.W/8-30, self.H+100-s-1, 10, s)

        # read iops + bar
        setHeatMapColor(qp, 0, self.maxima[3],totals[3])
        qp.drawText(2 + 5 * self.W/8, self.H+40, str(totals[3])+" read iops/s")
        s = 98.0*(float(totals[3])/float(self.maxima[3]))
        qp.drawRect(2 + 5 * self.W/8-20, self.H+100-s-1, 10, s)

        # write BW + bar
        setHeatMapColor(qp, 0, self.maxima[4],totals[4])
        (bw,unit) = normalize_bw(totals[4])
        qp.drawText(2 + 7 * self.W/8, self.H+20, "write %6.2f" % (bw)+unit)
        s = 98.0*(float(totals[4])/float(self.maxima[4]))
        qp.drawRect(2 + 7 * self.W/8-30, self.H+100-s-1, 10, s)

        # read BW + bar
        setHeatMapColor(qp, 0, self.maxima[5],totals[5])
        (bw,unit) = normalize_bw(totals[5])
        qp.drawText(2 + 7 * self.W/8, self.H+40, "read %6.2f" % (bw)+unit)
        s = 98.0*(float(totals[5])/float(self.maxima[5]))
        qp.drawRect(2 + 7 * self.W/8-20, self.H+100-s-1, 10, s)

 

        # print maxima

        setBlack(qp)

        qp.setFont(QtGui.QFont('Decorative', FONTSIZE+2))
        qp.drawText(10, self.H+70, self.fsname+" MAXIMUM")
        qp.drawText(250, self.H+70, str(self.maxima[0])+" nodes")
        qp.drawText(2 + 3 * self.W/8, self.H+70, str(self.maxima[1])+" meta ops/s")

        qp.setFont(QtGui.QFont('Decorative', (FONTSIZE+1)))
        qp.drawText(2 + 5 * self.W/8, self.H+65, str(self.maxima[2])+" write iops/s")

        qp.drawText(2 + 5 * self.W/8, self.H+85, str(self.maxima[3])+" read iops/s")

        qp.setFont(QtGui.QFont('Decorative', (FONTSIZE+1)))
        (bw,unit) = normalize_bw(self.maxima[4])
        qp.drawText(2 + 7 * self.W/8, self.H+65, "write %1.2f" % (bw)+unit)
        (bw,unit) = normalize_bw(self.maxima[5])
        qp.drawText(2 + 7 * self.W/8, self.H+85, "read %1.2f" % (bw)+unit)

        qp.end()
Esempio n. 13
0
 def on_fetch_bottom_right(self,i):
     self.area.set_marker(self.transFormMatrix.map(QtCore.QPoint(self.spin_transformation_b_x.value(),self.spin_transformation_b_y.value())),False)
     self.transformationPointState = TransfomationPointState.BottomRight
Esempio n. 14
0
 def paintEvent(self, event):
     super(Versatyle, self).paintEvent(event)
     bgImage = self.pagesList[self.currentPageIndex].getBackgroundImage()
     qpainter = QtGui.QPainter(self)
     qpainter.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap(bgImage))
Esempio n. 15
0
 def __init__(self, parent=None):
     super(QCustomLabel, self).__init__(parent)
     self.setMouseTracking(True)
     self.coloring = QtGui.QGraphicsColorizeEffect()
     self.rubberBand = Selector(QtGui.QRubberBand.Rectangle, self)
     self.origin = QtCore.QPoint()
 def mousePressEvent(self, event):
     self.last_mouse_pos = QtCore.QPoint(event.pos())
Esempio n. 17
0
    def RedrawCallback(self):
        global D

        self.imageLock.acquire()
        try:
            self.PrintToLog("--- GUI UPDATE ---")

            # updating infoBox values
            # if USE_CM = 1, values are converted here
            xDisplay = round(100.0**USE_CM * (D.x - D.xDiff), 2)
            yDisplay = round(100.0**USE_CM * (D.y - D.yDiff), 2)
            self.xValue.setText(str(xDisplay))
            self.yValue.setText(str(yDisplay))

            # convert theta to degrees and set bounds
            thetaDisplay = int(round(math.degrees(D.theta - D.thetaDiff)))
            while thetaDisplay > 360:
                thetaDisplay -= 360
            while thetaDisplay < 0:
                thetaDisplay += 360
            self.thetaValue.setText(str(thetaDisplay))

            self.PrintToLog("D.x: " + str(D.x) + " | D.xDiff: " + str(D.xDiff) + " | xDisplay: " + str(xDisplay))
            self.PrintToLog("D.y: " + str(D.y) + " | D.yDiff: " + str(D.yDiff) + " | yDisplay: " + str(yDisplay))
            self.PrintToLog("D.theta: " + str(D.x) + " | D.thetaDiff: " + str(D.thetaDiff) + " | thetaDisplay: " + str(thetaDisplay))

            # updating lightBox values
            self.backLeftValue.setText(str(D.backLeftSensor))
            self.frontLeftValue.setText(str(D.frontLeftSensor))
            self.frontRightValue.setText(str(D.frontRightSensor))
            self.backRightValue.setText(str(D.backRightSensor))

            # updating imageBox
            # right now, it just redraws the entire image every time the GUI is
            # updated...
            if D.loadedImage.isNull():
                # Default image is just a white square
                WIDTH = 300
                HEIGHT = 300
                blank = QtGui.QPixmap.fromImage(\
                  QtGui.QImage(WIDTH, HEIGHT, QtGui.QImage.Format_RGB888))
                blank.fill(QtGui.QColor(255,255,255))

                image = blank
            else:
                WIDTH = D.loadedImage.width()
                HEIGHT = D.loadedImage.height()
                image = QtGui.QPixmap.fromImage(D.loadedImage)

            area = WIDTH*HEIGHT
            scale = 1.0 # how many distance units for one pixel?
            origin = [WIDTH/2, HEIGHT/2]
            # most graphics dealios consider top-left corner to be the origin,
            # so we need to adjust for that
            location = (origin[0] + scale*xDisplay,\
              origin[1] - scale*yDisplay,\
              D.theta)

            painter = QtGui.QPainter()
            painter.begin(image)

            # drawing MCL particles
            # hold on to yer britches son cause this is one wild ride
            if D.makeTrail >= 1 and D.makeMCL >= 1:
                self.PrintToLog("-- MCL UPDATE --")
                pDensity = int(area/100)
                if D.particles == []:
                    self.PrintToLog("- INITIAL SETUP -")
                    for n in range(pDensity-1):
                        # a point with random x, y, theta is generated
                        # initially, every point has an equal probability of
                        # being the robot's actual location
                        p = [random.randint(0, WIDTH-1),\
                          random.randint(0, HEIGHT-1),\
                          random.randint(0, 360),\
                          1.0/pDensity]
                        D.particles.append(p)
                    D.particles.append([location[0],location[1],location[2],1.0/pDensity])
                elif len(D.trail) > 1 and D.recentMove:
                    # from the most recent motion data, calculate how far the
                    # particles must move
                    difference = [D.trail[-1][0] - D.trail[-2][0],\
                      D.trail[-1][1] - D.trail[-2][1],\
                      D.trail[-1][2] - D.trail[-2][2]]
                    if D.recentMove:
                        move = math.hypot(difference[0], difference[1])
                        oldGen = D.particles
                        newGen = []
                        self.PrintToLog("Pre-move probs: " + str(map(lambda p: p[3], oldGen)))
                        for oldPt in oldGen:
                            # if the robot turned, the particles must turn
                            oldPt[2] += difference[2]
                            # apply robot's x and y displacement to particles
                            xParticle = move * math.sin(math.radians(oldPt[2]))
                            yParticle = move * math.cos(math.radians(oldPt[2]))
                            oldPt[0] += xParticle
                            oldPt[1] += yParticle
                            # particles that move off-screen are killed
                            if oldPt[0] < 0 or oldPt[0] > WIDTH or\
                              oldPt[1] < 0 or oldPt[1] > HEIGHT:
                                # killed particles unlikely to represent actual
                                # location, so we set their prob very low
                                oldPt[3] = 0.0001
                        self.PrintToLog("Post-move probs: " + str(map(lambda p: p[3], oldGen)))
                        oldProbSum = reduce(lambda m,n: m+n,\
                          map(lambda p: p[3], oldGen))
                        # begin populating new generation with copies from
                        # old generation, based on the points' probabilities
                        oldPtSet = []
                        for n in range(pDensity):
                            # dart-throwing approach
                            dart = random.uniform(0, oldProbSum)
                            counter = 0
                            cumulativeProb = oldGen[1][3]
                            while dart < cumulativeProb:
                                cumulativeProb += oldGen[counter][3]
                                counter += 1
                            newGen.append(oldGen[counter])
                            if oldGen[counter] not in oldPtSet:
                                oldPtSet.append(oldGen[counter])
                        # recalculate probabilities
                        adjusted = []
                        for n in range(len(oldPtSet)):
                            toCheck = oldPtSet.pop()
                            instances = filter(lambda p: p == toCheck, newGen)
                            adjusted+=map(lambda p: [p[0],p[1],p[2],len(instances)/pDensity], instances)
                        newGen = adjusted
                        # add some noise to each new point
                        noise = 4.0
                        noiseTheta = 2.5
                        newGen = map(lambda p: [random.gauss(p[0],noise),\
                                                random.gauss(p[1],noise),\
                                                random.gauss(p[2],noiseTheta),\
                                                p[3]],
                                                newGen)
                        # newGen is now ready
                        self.PrintToLog("New gen probs: " + str(map(lambda p: p[3], newGen)))
                        D.particles = newGen
                    else:
                        self.PrintToLog("- NO CHANGE -")
                # draw the particles now, if we want
                if D.makeMCL == 2:
                    pRadius = 2
                    probs = map(lambda p: p[3], D.particles)
                    mostRed = max(probs)
                    mostPurple = min(probs)
                    for p in D.particles:
                        # a point is more red (hue = 0) if it is more probable
                        if mostRed == mostPurple: hue = 150
                        else: hue = 300 * (p[3]-mostPurple)/(mostRed-mostPurple)
                        color = QtGui.QColor.fromHsv(hue,255,255)
                        painter.setPen(color)
                        painter.setBrush(color)
                        painter.drawEllipse(\
                          QtCore.QPoint(p[0],p[1]),pRadius,pRadius)

            # drawing robot trail
            # dreadfully inefficient as implemented
            if D.makeTrail >= 1:
                if D.trail == [] or location != D.trail[-1]:
                    D.trail.append(location)
                    D.recentMove = True
                else: D.recentMove = False
                if D.makeTrail == 2 and len(D.trail) > 1:
                    painter.setPen(QtGui.QColor(255,0,0)) # red outline and fill
                    painter.setBrush(QtGui.QColor(255,0,0))
                    for p in range(1,len(D.trail)):
                        painter.drawLine(D.trail[p-1][0],D.trail[p-1][1],\
                          D.trail[p][0],D.trail[p][1])

            # drawing robot location
            if D.showRobot:
                painter.setPen(QtGui.QColor(0,0,0)) # black outline
                painter.setBrush(QtGui.QColor(0,0,255)) # blue fill
                painter.drawEllipse(\
                    QtCore.QPoint(location[0],location[1]),6,6)

            painter.end()

        finally:
            self.imageLock.release()

        # We could  do more processing (eg OpenCV) here if we wanted to,
        # but for now lets just display the window.
        self.resize(image.width(),image.height())
        self.imageBox.setPixmap(image)

        # Status bar displays charge level only when updating previous level or
        # after a temporary message expires
        if self.statusBar().currentMessage() == "" or \
                "Charge" in self.statusBar().currentMessage():
            self.statusBar().showMessage("Charge: " + D.chargeLevel)
Esempio n. 18
0
 def series(self, painter, color, slot, arr, min_val, max_val, label):
     lines = self.get_lines(arr, slot, min_val, max_val)
     painter.setPen(QtGui.QPen(color, 0))
     painter.drawLines(lines)
     painter.fillRect(QtCore.QRect(0, (slot+1)*self.slot_height, self.text_width, self.text_height), self.white)
     painter.drawText(QtCore.QPoint(0, (slot+1)*self.slot_height+self.text_height), label)
Esempio n. 19
0
#*                                                                         *
#***************************************************************************

import FreeCAD, FreeCADGui, Part
from PySide import QtGui, QtCore
import os, sys, math, copy
#from a2p_viewProviderProxies import *
from  FreeCAD import Base

import a2plib
from a2plib import *
from a2p_solversystem import solveConstraints
import a2p_constraints


CONSTRAINT_DIALOG_STORED_POSITION = QtCore.QPoint(-1,-1)

#==============================================================================
class a2p_ConstraintValueWidget(QtGui.QWidget):
#class a2p_ConstraintValueWidget(QtGui.QDialog):

    Deleted = QtCore.Signal()
    Accepted = QtCore.Signal()


    def __init__(self,parent,constraintObject, mode):
        super(a2p_ConstraintValueWidget,self).__init__(parent=parent)
        self.mode = mode # either "editConstraint" or "createConstraint"
        self.constraintObject = constraintObject # The documentObject of a constraint!

        self.savedOffset = None
Esempio n. 20
0
 def __init__(self, step):
     Item.__init__(self)
     self._step = step
     self._pos = QtCore.QPoint(0, 0)
     self._uid = str(uuid.uuid1())
     self._id = step.getIdentifier()
Esempio n. 21
0
 def mousePressEvent(self, event):
     self.mousePressPos = QtCore.QPoint(event.pos())
     self.scrollBarValuesOnMousePress.setX(self.horizontalScrollBar().value())
     self.scrollBarValuesOnMousePress.setY(self.verticalScrollBar().value())
     event.accept()
Esempio n. 22
0
 def QPoint(self):
     return QtCore.QPoint(self.x, self.y)
Esempio n. 23
0
 def mouseReleaseEvent(self, event):
     self.mousePressPos = QtCore.QPoint()
     event.accept()
Esempio n. 24
0
    def onRightClick(self, pos):

        parentPosition = self.dlg.matList.mapToGlobal(QtCore.QPoint(0, 0))
        self.contextMenu.move(parentPosition + pos)
        self.contextMenu.show()
Esempio n. 25
0
 def getInsidePoint(self):
     try:
         return self.insidePos
     except:
         return QtCore.QPoint(27, 2)
Esempio n. 26
0
    def __init__(self):
        super(hotboxManager, self).__init__()

        #--------------------------------------------------------------------------------------------------
        #main widget
        #--------------------------------------------------------------------------------------------------

        self.setWindowTitle('W_hotbox Manager')

        self.setMinimumWidth(1000)
        self.setMinimumHeight(400)

        #--------------------------------------------------------------------------------------------------

        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

        self.rootLocation = preferencesNode.knob('hotboxLocation').value()
        if self.rootLocation[-1] != '/':
            self.rootLocation += '/' 

        #--------------------------------------------------------------------------------------------------
        #classes list
        #--------------------------------------------------------------------------------------------------

        self.classesListLayout = QtGui.QVBoxLayout()

        self.scopeComboBox = QtGui.QComboBox()
        self.scopeComboBox.addItems(['Single','Multiple','All'])
        self.scopeComboBox.currentIndexChanged.connect( self.builtClassesList )

        self.classesList = QtGui.QListWidget()
        self.classesList.setFixedWidth(150)

        self.classesListLayout.addWidget(self.scopeComboBox)
        self.classesListLayout.addWidget(self.classesList)

        #buttons

        self.classesListButtonsLayout = QtGui.QVBoxLayout()

        self.classesListAddButton = QLabelButton('add')
        self.classesListRemoveButton = QLabelButton('remove')
        self.classesListRenameButton = QLabelButton('rename')

        self.connect(self.classesListAddButton, QtCore.SIGNAL('buttonClicked()'), self.addClass)
        self.connect(self.classesListRemoveButton, QtCore.SIGNAL('buttonClicked()'), self.removeClass)
        self.connect(self.classesListRenameButton, QtCore.SIGNAL('buttonClicked()'), self.renameClass)

        self.classesListButtonsLayout.addStretch()
        self.classesListButtonsLayout.addWidget(self.classesListAddButton)
        self.classesListButtonsLayout.addWidget(self.classesListRemoveButton)
        self.classesListButtonsLayout.addWidget(self.classesListRenameButton)
        self.classesListButtonsLayout.addStretch()

        #--------------------------------------------------------------------------------------------------
        #hotbox items tree
        #--------------------------------------------------------------------------------------------------
        
        self.hotboxItemsTree = QTreeViewCustom(self)
        self.hotboxItemsTree.setFixedWidth(150)
        self.rootPath = nuke.toNode('preferences').knob('hotboxLocation').value()

        self.classesList.itemSelectionChanged.connect(self.hotboxItemsTree.populateTree)

        #--------------------------------------------------------------------------------------------------
        #hotbox items tree actions
        #--------------------------------------------------------------------------------------------------

        self.hotboxItemsTreeButtonsLayout = QtGui.QVBoxLayout()

        self.hotboxItemsTreeAddButton = QLabelButton('add')
        self.hotboxItemsTreeAddFolderButton = QLabelButton('addFolder')
        self.hotboxItemsTreeRemoveButton = QLabelButton('remove')
        self.hotboxItemsTreeDuplicateButton = QLabelButton('duplicate')
        self.hotboxItemsTreeCopyButton = QLabelButton('copy')
        self.hotboxItemsTreePasteButton = QLabelButton('paste')

        self.connect(self.hotboxItemsTreeAddButton, QtCore.SIGNAL('buttonClicked()'), self.hotboxItemsTree.addItem)
        self.connect(self.hotboxItemsTreeAddFolderButton, QtCore.SIGNAL('buttonClicked()'), lambda: self.hotboxItemsTree.addItem(True))
        self.connect(self.hotboxItemsTreeRemoveButton, QtCore.SIGNAL('buttonClicked()'), self.hotboxItemsTree.removeItem)
        self.connect(self.hotboxItemsTreeDuplicateButton, QtCore.SIGNAL('buttonClicked()'), self.hotboxItemsTree.duplicateItem)
        self.connect(self.hotboxItemsTreeCopyButton, QtCore.SIGNAL('buttonClicked()'), self.hotboxItemsTree.copyItem)
        self.connect(self.hotboxItemsTreePasteButton, QtCore.SIGNAL('buttonClicked()'), self.hotboxItemsTree.pasteItem)


        self.hotboxItemsTreeButtonsLayout.addStretch()
        self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeAddButton)
        self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeAddFolderButton)
        self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeRemoveButton)
        self.hotboxItemsTreeButtonsLayout.addSpacing(25)
        self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeCopyButton)
        self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreePasteButton)
        self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeDuplicateButton)
        self.hotboxItemsTreeButtonsLayout.addStretch()

        #--------------------------------------------------------------------------------------------------
        #import/export
        #--------------------------------------------------------------------------------------------------

        self.archiveButtonsLayout = QtGui.QHBoxLayout()   

        self.clipboardArchive = QtGui.QRadioButton('Clipboard')
        self.importArchiveButton = QtGui.QPushButton('Import Archive')
        self.exportArchiveButton = QtGui.QPushButton('Export Archive')

        self.importArchiveButton.setMaximumWidth(100)
        self.exportArchiveButton.setMaximumWidth(100)

        self.importArchiveButton.clicked.connect(self.importHotboxArchive)
        self.exportArchiveButton.clicked.connect(self.exportHotboxArchive)

        self.archiveButtonsLayout.addStretch()
        self.archiveButtonsLayout.addWidget(self.clipboardArchive)
        self.archiveButtonsLayout.addWidget(self.importArchiveButton)
        self.archiveButtonsLayout.addWidget(self.exportArchiveButton)

        #--------------------------------------------------------------------------------------------------
        #scriptEditor
        #--------------------------------------------------------------------------------------------------
        
        self.loadedScript = None

        self.scriptEditorLayout = QtGui.QVBoxLayout()       

        #name
        self.scriptEditorNameLayout = QtGui.QHBoxLayout()

        self.scriptEditorNameLabel = QtGui.QLabel('Name')
        self.scriptEditorName = QtGui.QLineEdit()
        self.scriptEditorName.setAlignment(QtCore.Qt.AlignLeft)
        self.scriptEditorName.setReadOnly(True)
        self.scriptEditorName.setStyleSheet('background:#262626')

        self.scriptEditorNameLayout.addWidget(self.scriptEditorNameLabel)
        self.scriptEditorNameLayout.addWidget(self.scriptEditorName)

        self.scriptEditorScript = QtGui.QPlainTextEdit()
        self.scriptEditorScript.setMinimumHeight(200)
        self.scriptEditorScript.setMinimumWidth(500)
        self.scriptEditorScript.setReadOnly(True)
        self.scriptEditorScript.setStyleSheet('background:#262626')

        scriptEditorFont = QtGui.QFont()
        scriptEditorFont.setFamily("Courier")
        scriptEditorFont.setStyleHint(QtGui.QFont.Monospace)
        scriptEditorFont.setFixedPitch(True)
        scriptEditorFont.setPointSize(11)

        self.scriptEditorScript.setFont(scriptEditorFont)
        self.scriptEditorScript.setTabStopWidth(4 * QtGui.QFontMetrics(scriptEditorFont).width(' '))

            
        #buttons
        self.scriptEditorButtonsLayout = QtGui.QHBoxLayout()

        self.scriptEditorImportButton = QtGui.QPushButton('Import')
        self.scriptEditorSaveButton = QtGui.QPushButton('Save')
        
        self.scriptEditorImportButton.clicked.connect(self.importScriptEditor)
        self.scriptEditorSaveButton.clicked.connect(self.saveScriptEditor)

        self.scriptEditorSaveButton.setMaximumWidth(100)

        self.scriptEditorButtonsLayout.addStretch()
        self.scriptEditorButtonsLayout.addWidget(self.scriptEditorImportButton)
        self.scriptEditorButtonsLayout.addWidget(self.scriptEditorSaveButton)
        self.scriptEditorButtonsLayout.addStretch()

        self.scriptEditorLayout.addLayout(self.archiveButtonsLayout)
        self.scriptEditorLayout.addLayout(self.scriptEditorNameLayout)
        self.scriptEditorLayout.addWidget(self.scriptEditorScript)
        self.scriptEditorLayout.addLayout(self.scriptEditorButtonsLayout)

        #--------------------------------------------------------------------------------------------------
        #main buttons
        #--------------------------------------------------------------------------------------------------
        self.mainButtonLayout = QtGui.QHBoxLayout()

        self.aboutButton = QtGui.QPushButton('?')
        self.aboutButton.clicked.connect(self.openAboutDialog)
        self.aboutButton.setMaximumWidth(20)

        self.mainCloseButton = QtGui.QPushButton('Close')
        self.mainCloseButton.clicked.connect(self.closeManager)

        self.mainButtonLayout.addWidget(self.aboutButton)
        self.mainButtonLayout.addStretch()
        self.mainButtonLayout.addWidget(self.mainCloseButton)

        #--------------------------------------------------------------------------------------------------
        #main layout
        #--------------------------------------------------------------------------------------------------
        
        self.mainLayout = QtGui.QHBoxLayout()
        self.mainLayout.addLayout(self.classesListButtonsLayout)
        self.mainLayout.addLayout(self.classesListLayout)
        self.mainLayout.addLayout(self.hotboxItemsTreeButtonsLayout)
        self.mainLayout.addWidget(self.hotboxItemsTree)
        self.mainLayout.addLayout(self.scriptEditorLayout)

        #--------------------------------------------------------------------------------------------------
        #layouts
        #--------------------------------------------------------------------------------------------------
        
        self.masterLayout = QtGui.QVBoxLayout()

        self.masterLayout.addLayout(self.mainLayout)
        self.masterLayout.addLayout(self.mainButtonLayout)

        self.setLayout(self.masterLayout)

        #--------------------------------------------------------------------------------------------------
        #move to center of the screen
        #--------------------------------------------------------------------------------------------------
        
        self.adjustSize()

        screenRes = QtGui.QDesktopWidget().screenGeometry()
        self.move(QtCore.QPoint(screenRes.width()/2,screenRes.height()/2)-QtCore.QPoint((self.width()/2),(self.height()/2)))

        #--------------------------------------------------------------------------------------------------
        #set hotbox to current selection
        #--------------------------------------------------------------------------------------------------

        self.scopeComboBox.setCurrentIndex(1)
        self.scopeComboBox.setCurrentIndex(0)
        

        selection = nuke.selectedNodes()
        if selection > 0:
            classes = set(sorted([i.Class() for i in selection]))
            self.scopeComboBox.setCurrentIndex(max(min(len(classes)-1,1),0))
            for index in range(self.classesList.count()):
                if self.classesList.item(index).text() == '-'.join(classes):
                    self.classesList.setCurrentRow(index)
                    self.hotboxItemsTree.populateTree()
                    break

        #--------------------------------------------------------------------------------------------------
        #shortcuts
        #--------------------------------------------------------------------------------------------------

        #save
        self.saveAction = QtGui.QAction(self)
        self.saveAction.setShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_S))
        self.saveAction.triggered.connect(self.saveScriptEditor)
        self.addAction(self.saveAction)
    def __init__(self, subMenuMode=False, path='', name='', position=''):
        super(hotbox, self).__init__()

        self.active = True

        self.triggerMode = preferencesNode.knob(
            'hotboxTriggerDropdown').getValue()

        self.setWindowFlags(QtCore.Qt.FramelessWindowHint
                            | QtCore.Qt.WindowStaysOnTopHint)

        self.setAttribute(QtCore.Qt.WA_NoSystemBackground)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        #enable transparency on Linux

        if operatingSystem not in ['Darwin', 'Windows']:
            self.setAttribute(QtCore.Qt.WA_PaintOnScreen)

        masterLayout = QtWidgets.QVBoxLayout()
        self.setLayout(masterLayout)

        self.selection = nuke.selectedNodes()

        #check whether selection in group
        self.groupRoot = 'root'

        if len(self.selection) != 0:
            nodeRoot = self.selection[0].fullName()
            if nodeRoot.count('.') > 0:
                self.groupRoot = '.'.join(nodeRoot.split('.')[:-1])

        self.activeButton = None

        #--------------------------------------------------------------------------------------------------
        #main hotbox
        #--------------------------------------------------------------------------------------------------

        if not subMenuMode:

            if len(self.selection) > 1:

                if len(list(set([i.Class()
                                 for i in nuke.selectedNodes()]))) == 1:
                    self.mode = 'Single'
                else:
                    self.mode = 'Multiple'

            else:
                self.mode = 'Single'

            #Layouts
            centerLayout = QtWidgets.QHBoxLayout()

            centerLayout.addStretch()
            centerLayout.addWidget(
                hotboxButton('Reveal in %s' % getFileBrowser(),
                             'revealInBrowser()'))
            centerLayout.addSpacing(25)
            centerLayout.addWidget(hotboxCenter())
            centerLayout.addSpacing(25)
            centerLayout.addWidget(
                hotboxButton('Hotbox Manager', 'showHotboxManager()'))
            centerLayout.addStretch()

            self.topLayout = nodeButtons()
            self.bottomLayout = nodeButtons('bottom')
            spacing = 12

        #--------------------------------------------------------------------------------------------------
        #submenu
        #--------------------------------------------------------------------------------------------------

        else:

            allItems = [
                path + '/' + i for i in sorted(os.listdir(path))
                if i[0] not in ['.', '_']
            ]

            centerItems = allItems[:2]

            lists = [[], []]
            for index, item in enumerate(allItems[2:]):

                if int((index % 4) / 2):
                    lists[index % 2].append(item)
                else:
                    lists[index % 2].insert(0, item)

            #Stretch layout
            centerLayout = QtWidgets.QHBoxLayout()

            centerLayout.addStretch()
            for index, item in enumerate(centerItems):
                centerLayout.addWidget(hotboxButton(item))
                if index == 0:
                    centerLayout.addWidget(hotboxCenter(False, path))

            if len(centerItems) == 1:
                centerLayout.addSpacing(105)

            centerLayout.addStretch()

            self.topLayout = nodeButtons('SubMenuTop', lists[0])
            self.bottomLayout = nodeButtons('SubMenuBottom', lists[1])
            spacing = 0

        #--------------------------------------------------------------------------------------------------
        #Equalize layouts to make sure the center layout is the center of the hotbox
        #--------------------------------------------------------------------------------------------------

        difference = self.topLayout.count() - self.bottomLayout.count()

        if difference != 0:

            extraLayout = QtWidgets.QVBoxLayout()

            for i in range(abs(difference)):
                extraLayout.addSpacing(35)

            if difference > 0:
                self.bottomLayout.addLayout(extraLayout)
            else:
                self.topLayout.insertLayout(0, extraLayout)

        #--------------------------------------------------------------------------------------------------

        masterLayout.addLayout(self.topLayout)
        masterLayout.addSpacing(spacing)
        masterLayout.addLayout(centerLayout)
        masterLayout.addSpacing(spacing)
        masterLayout.addLayout(self.bottomLayout)

        #position
        self.adjustSize()

        self.spwanPosition = QtGui.QCursor().pos() - QtCore.QPoint(
            (self.width() / 2), (self.height() / 2))

        #set last position if a fresh instance of the hotbox is launched
        if position == '' and not subMenuMode:
            global lastPosition
            lastPosition = self.spwanPosition

        if subMenuMode:
            self.move(self.spwanPosition)

        else:
            self.move(lastPosition)

        #make sure the widgets closes when it loses focus
        self.installEventFilter(self)
Esempio n. 28
0
 def readSettings(self):
     settings = QtCore.QSettings('Trolltech', 'SDI Example')
     pos = settings.value('pos', QtCore.QPoint(200, 200))
     size = settings.value('size', QtCore.QSize(400, 400))
     self.move(pos)
     self.resize(size)
Esempio n. 29
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.transformationPointState = TransfomationPointState.Nope
        self.svg_filename_top = ''

        self.currentPath = ""
        self.pcb_fileName = ""
        
        self.area = SvgWindow(self)

        fileMenu = QtGui.QMenu(self.tr("&File"), self)
        self.openAction = fileMenu.addAction(self.tr("&Open..."))
        self.openAction.setShortcut(QtGui.QKeySequence(self.tr("Ctrl+O")))
        self.openRecentAction = fileMenu.addAction(self.tr("&Open recent..."))
        self.openTransformationAction = fileMenu.addAction(self.tr("&Open transformation..."))
        self.quitAction = fileMenu.addAction(self.tr("E&xit"))
        self.quitAction.setShortcut(QtGui.QKeySequence(self.tr("Ctrl+Q")))

        self.menuBar().addMenu(fileMenu)
        
        self.connect(self.openAction, QtCore.SIGNAL("triggered()"), self.openFile)
        self.connect(self.openRecentAction, QtCore.SIGNAL("triggered()"), self.openRecent)
        self.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()"))
        self.connect(self.openTransformationAction, QtCore.SIGNAL("triggered()"), self.openTransformation)

        self.spin_transformation_a_x = QtGui.QSpinBox()
        self.spin_transformation_a_y = QtGui.QSpinBox()
        self.spin_transformation_b_x = QtGui.QSpinBox()
        self.spin_transformation_b_y = QtGui.QSpinBox()
        
        self.btn_find_top_left = QtGui.QPushButton("fetch on top left");
        self.btn_find_bot_right = QtGui.QPushButton("fetch on bot right");
        
        self.c_widget = QtGui.QWidget(self)
        
        self.spin_offset_x = QtGui.QSpinBox()
        self.spin_offset_y = QtGui.QSpinBox()
        
        #self.setCentralWidget(self.area)
        self.gridlayout = QtGui.QGridLayout()
        self.gridlayout.addWidget(QtGui.QLabel("offset x:"),0,0)
        self.gridlayout.addWidget(self.spin_offset_x,0,1)
        self.gridlayout.addWidget(QtGui.QLabel("offset y:"),1,0)
        self.gridlayout.addWidget(self.spin_offset_y,1,1)
        self.gridlayout.addWidget(QtGui.QLabel("transformation point left:"),0,2)
        self.gridlayout.addWidget(QtGui.QLabel("transformation point top:"),1,2)
        self.gridlayout.addWidget(self.spin_transformation_a_x,0,3)
        self.gridlayout.addWidget(self.spin_transformation_a_y,1,3)
        self.gridlayout.addWidget(QtGui.QLabel("mm@:"),0,4)
        self.gridlayout.addWidget(QtGui.QLabel("mm@"),1,4)  
        
        self.gridlayout.addWidget(self.btn_find_top_left,0,5)
        
        self.gridlayout.addWidget(QtGui.QLabel("transformation point right:"),0,6)
        self.gridlayout.addWidget(QtGui.QLabel("transformation point bottom:"),1,6)  
        
        self.gridlayout.addWidget(self.spin_transformation_b_x,0,7)
        self.gridlayout.addWidget(self.spin_transformation_b_y,1,7)
        self.gridlayout.addWidget(QtGui.QLabel("mm@:"),0,8)
        self.gridlayout.addWidget(QtGui.QLabel("mm@"),1,8)  
        self.gridlayout.addWidget(self.btn_find_bot_right,0,9)
        self.gridlayout.addWidget(self.area,2,0,2,0)
        self.c_widget.setLayout(self.gridlayout)
        self.setCentralWidget(self.c_widget)
        self.setWindowTitle(self.tr("Kicad Solder Tool"))
        
        self.spin_transformation_a_x.setMaximum(100000)
        self.spin_transformation_a_x.setMinimum(-100000)
        self.spin_transformation_a_x.setValue(0)
        
        self.spin_transformation_a_y.setMaximum(100000)
        self.spin_transformation_a_y.setMinimum(-100000)
        self.spin_transformation_a_y.setValue(0)
        
        self.spin_transformation_b_x.setMaximum(100000)
        self.spin_transformation_b_x.setMinimum(-100000)
        self.spin_transformation_b_x.setValue(160)
        
        self.spin_transformation_b_y.setMaximum(100000)
        self.spin_transformation_b_y.setMinimum(-100000)
        self.spin_transformation_b_y.setValue(100)
        
        self.spin_offset_x.setMaximum(100000)
        self.spin_offset_x.setMinimum(-100000)
        
        self.spin_offset_y.setMaximum(100000)
        self.spin_offset_y.setMinimum(-100000)
        
        self.spin_offset_x.setSingleStep(10)
        self.spin_offset_y.setSingleStep(10)
        self.connect(self.spin_transformation_a_x, QtCore.SIGNAL("valueChanged(int)"), self.calc_transform)
        self.connect(self.spin_transformation_a_y, QtCore.SIGNAL("valueChanged(int)"), self.calc_transform)
        self.connect(self.spin_transformation_b_x, QtCore.SIGNAL("valueChanged(int)"), self.calc_transform)
        self.connect(self.spin_transformation_b_y, QtCore.SIGNAL("valueChanged(int)"), self.calc_transform)        
        self.connect(self.spin_offset_x, QtCore.SIGNAL("valueChanged(int)"), self.on_offset_change)
        self.connect(self.spin_offset_y, QtCore.SIGNAL("valueChanged(int)"), self.on_offset_change)
        self.connect(self.btn_find_top_left, QtCore.SIGNAL("clicked(bool)"), self.on_fetch_top_left)
        self.connect(self.btn_find_bot_right, QtCore.SIGNAL("clicked(bool)"), self.on_fetch_bottom_right)
        self.transFormMatrix = QtGui.QMatrix();
        self.transform_target_topleft = QtCore.QPoint(0,0)
        self.transform_target_bottom_right = QtCore.QPoint(1,2)
        
        self.area.cursor().setShape(QtCore.Qt.CrossCursor)
        self.startTimer(250);