예제 #1
1
    def init(self, parent):
        '''

        '''
        if self.control is None:
            self.control = qtLED()
            scene = QGraphicsScene()
            #             self.control.setStyleSheet("qtLED { border-style: none; }");
            #             self.control.setAutoFillBackground(True)

            # system background color
            scene.setBackgroundBrush(QBrush(QColor(237, 237, 237)))
            self.control.setStyleSheet("border: 0px")
            self.control.setMaximumWidth(35)
            self.control.setMaximumHeight(35)

            x, y = 10, 10
            rad = 20
            cx = x + rad / 1.75
            cy = y + rad / 1.75

            brush = self.get_color(self.value.state, cx, cy, rad / 2)
            pen = QPen()
            pen.setWidth(0)
            self.led = scene.addEllipse(x, y, rad, rad,
                                        pen=pen,
                                        brush=brush
            )

            self.control.setScene(scene)

            self.value.on_trait_change(self.update_object, 'state')
예제 #2
0
    def init(self, parent):
        """
        """
        rad = self.factory.radius
        if not rad:
            rad = 20

        if self.control is None:
            self.control = qtLED()
            scene = QGraphicsScene()
            #             self.control.setStyleSheet("qtLED { border-style: none; }");
            #             self.control.setAutoFillBackground(True)

            # system background color
            scene.setBackgroundBrush(QBrush(QColor(237, 237, 237)))
            self.control.setStyleSheet("border: 0px")
            self.control.setMaximumWidth(rad+15)
            self.control.setMaximumHeight(rad+15)

            x, y = 10, 10
            cx = x + rad / 1.75
            cy = y + rad / 1.75

            brush = self.get_color(self.value.state, cx, cy, rad / 2)
            pen = QPen()
            pen.setWidth(0)
            self.led = scene.addEllipse(x, y, rad, rad,
                                        pen=pen,
                                        brush=brush
                                        )

            self.control.setScene(scene)

            self.value.on_trait_change(self.update_object, 'state')
예제 #3
0
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        self.logger = logging.getLogger("zne")
        self.logger.setLevel(logging.DEBUG)

        self.setMinimumSize(560, 360)
        self.setWindowTitle("ZOCP Node Editor")
        self.setWindowIcon(QIcon('assets/icon.png'))

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self, self.scene, self.view)

        self.nodesEditor.onAddConnection = self.onAddConnection
        self.nodesEditor.onRemoveConnection = self.onRemoveConnection
        self.nodesEditor.onBlockMoved = self.onBlockMoved

        self.scale = 1
        self.installActions()

        self.initZOCP()

        self.nodes = {}
        self.pendingSubscribers = {}

        QTimer.singleShot(250, lambda: self.scene.invalidate())
예제 #4
0
    def setUp(self):
        #Acquire resources
        super(QColorOnSetBrush, self).setUp()

        self.scene = QGraphicsScene()
        poly = QPolygonF()
        self.item = self.scene.addPolygon(poly)
        self.color = QColor('black')
 def __init__(self, view, controller):
     self.view = view
     self.controller = controller
     self.scene = QGraphicsScene()
     self.view.setScene(self.scene)
     
     self.variables = {}
     self.variableOrder = []
     self.currentX = None
     self.currentY = None
예제 #6
0
 def __init__(self, mode, flags=[], **kwargs):
     QGraphicsScene.__init__(self, 0, 0, 2*1280, 2*1024)
     self.pts = []
     self.curpts = []
     self.flags = flags
     proc_map = {'tricavity': (self.tricavity, [2,2,2]),
                 'ruler': (self.ruler, [2,2,2,2])}
     self.process_points, self.numpts = proc_map[mode]
     self.pts_left = self.numpts[:] # Shallow copy
     self.kwargs = kwargs
예제 #7
0
class QNEMainWindow(QMainWindow):
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        quitAct = QAction("&Quit", self, shortcut="Ctrl+Q",
            statusTip="Exit the application", triggered=self.close)

        addAct = QAction("&Add", self, statusTip="Add a block", triggered=self.addBlock)

        fileMenu = self.menuBar().addMenu("&File")
        fileMenu.addAction(addAct)
        fileMenu.addSeparator()
        fileMenu.addAction(quitAct)

        self.setWindowTitle("Node Editor")

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self)
        self.nodesEditor.install(self.scene)

        block = QNEBlock(None)
        self.scene.addItem(block)
        block.addPort("test", 0, QNEPort.NamePort)
        block.addPort("TestBlock", 0, QNEPort.TypePort)
        block.addInputPort("in1");
        block.addInputPort("in2");
        block.addInputPort("in3");
        block.addOutputPort("out1");
        block.addOutputPort("out2");
        block.addOutputPort("out3");

        block = block.clone()
        block.setPos(150,0)

        block = block.clone()
        block.setPos(150,150)


    def addBlock(self):
        import random
        import math

        block = QNEBlock(None)

        self.scene.addItem(block)
        names = ["Vin", "Voutsadfasdf", "Imin", "Imax", "mul", "add", "sub", "div", "Conv", "FFT"]
        for i in range(0,math.floor(random.uniform(3,8))):
            block.addPort(random.choice(names), random.random()>0.5)
        block.setPos(self.view.sceneRect().center().toPoint())
예제 #8
0
    def test_setParentItem(self):
        global qgraphics_item_painted

        scene = QGraphicsScene()
        scene.addText("test")
        view = QGraphicsView(scene)

        rect = self.createRoundRect(scene)
        view.show()
        QTimer.singleShot(1000, self.quit_app)
        self.app.exec_()
        self.assert_(qgraphics_item_painted)
예제 #9
0
 def __init__(self, mode, flags=[], **kwargs):
     QGraphicsScene.__init__(self, 0, 0, 2 * 1280, 2 * 1024)
     self.pts = []
     self.curpts = []
     self.flags = flags
     proc_map = {
         'tricavity': (self.tricavity, [2, 2, 2]),
         'ruler': (self.ruler, [2, 2, 2, 2])
     }
     self.process_points, self.numpts = proc_map[mode]
     self.pts_left = self.numpts[:]  # Shallow copy
     self.kwargs = kwargs
예제 #10
0
    def _init_widgets(self):
        self.scene = QGraphicsScene(self.parent())
        self.setScene(self.scene)
        # self.setDragMode(QGraphicsView.ScrollHandDrag)
        self.setRenderHints(QPainter.Antialiasing
                            | QPainter.SmoothPixmapTransform
                            | QPainter.HighQualityAntialiasing)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.horizontalScrollBar().setSingleStep(16)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.verticalScrollBar().setSingleStep(16)
    def test_setParentItem(self):
        global qgraphics_item_painted

        scene = QGraphicsScene()
        scene.addText("test")
        view = QGraphicsView(scene)

        rect = self.createRoundRect(scene)
        view.show()
        QTimer.singleShot(1000, self.quit_app)
        self.app.exec_()
        self.assert_(qgraphics_item_painted)
    def mouseMoveEvent(self, event):

        QGraphicsScene.mouseMoveEvent(self, event)
        if event.isAccepted():
            return

        if (event.buttons() & QtCore.Qt.LeftButton):
            delta = event.scenePos() - event.lastScenePos()
            self.model.setXRotation(self.model.xRotation() - delta.y()*4)
            self.model.setYRotation(self.model.yRotation() + delta.x()*4)
        
        event.accept()
        self.update()
예제 #13
0
    def __init__(self, camera=None, scene=None):
        super(DrawableCameraView, self).__init__()
        if scene is None:
            self.scene = QGraphicsScene()
        else:
            self.scene = scene
        self.setScene(self.scene)
        self.camera = camera
        self.pixmapitem = None

        # Overlay variables
        self.overlay_visible = False
        self.overlay_images = None
    def mouseMoveEvent(self, event):

        QGraphicsScene.mouseMoveEvent(self, event)
        if event.isAccepted():
            return

        if (event.buttons() & QtCore.Qt.LeftButton):
            delta = event.scenePos() - event.lastScenePos()
            self.model.setXRotation(self.model.xRotation() - delta.y() * 4)
            self.model.setYRotation(self.model.yRotation() + delta.x() * 4)

        event.accept()
        self.update()
예제 #15
0
    def init(self, parent):
        """
        """
        rad = self.factory.radius
        if not rad:
            rad = 20

        if self.control is None:

            ctrl = qtLED()
            layout = QVBoxLayout()

            layout.addWidget(ctrl)

            scene = QGraphicsScene()
            #             ctrl.setStyleSheet("qtLED { border-style: none; }");
            #             ctrl.setAutoFillBackground(True)

            # system background color
            scene.setBackgroundBrush(QBrush(QColor(237, 237, 237)))
            ctrl.setStyleSheet("border: 0px")
            ctrl.setMaximumWidth(rad + 15)
            ctrl.setMaximumHeight(rad + 15)

            x, y = 10, 10
            cx = x + rad / 1.75
            cy = y + rad / 1.75

            brush = self.get_color(self.value.state, cx, cy, rad / 2)
            pen = QPen()
            pen.setWidth(0)
            self.led = scene.addEllipse(x, y, rad, rad,
                                        pen=pen,
                                        brush=brush)

            if self.factory.label:
                txt = QLabel(self.factory.label)
                layout.addWidget(txt)
                layout.setAlignment(txt, Qt.AlignHCenter)
                # txt = scene.addText(self.factory.label, QFont('arial 6'))
                # txt.setPos(cx, 10)

            ctrl.setScene(scene)

            layout.setAlignment(ctrl, Qt.AlignHCenter)

            self.value.on_trait_change(self.update_object, 'state')

            self.control = QWidget()
            self.control.setLayout(layout)
예제 #16
0
    def __init__(self):
        self.app = QApplication.instance()
        if self.app is None:
            self.app = QApplication(sys.argv)
        loader = QUiLoader()
        self.mainWindow = loader.load("timelineTest.ui")
        self.scene = QGraphicsScene()
        self.mainWindow.graphicsView.setScene(self.scene)

        track = timelineTrack()
        self.addTrack(track)
        self.readEDL(track, 'sample.edl')

        self.mainWindow.show()
        self.app.exec_()
예제 #17
0
    def init(self, parent):
        """
        """
        rad = self.factory.radius
        if not rad:
            rad = 20

        if self.control is None:

            ctrl = qtLED()
            layout = QVBoxLayout()

            layout.addWidget(ctrl)

            scene = QGraphicsScene()
            #             ctrl.setStyleSheet("qtLED { border-style: none; }");
            #             ctrl.setAutoFillBackground(True)

            # system background color
            scene.setBackgroundBrush(QBrush(QColor(237, 237, 237)))
            ctrl.setStyleSheet("border: 0px")
            ctrl.setMaximumWidth(rad + 15)
            ctrl.setMaximumHeight(rad + 15)

            x, y = 10, 10
            cx = x + rad / 1.75
            cy = y + rad / 1.75

            brush = self.get_color(self.value.state, cx, cy, rad / 2)
            pen = QPen()
            pen.setWidth(0)
            self.led = scene.addEllipse(x, y, rad, rad, pen=pen, brush=brush)

            if self.factory.label:
                txt = QLabel(self.factory.label)
                layout.addWidget(txt)
                layout.setAlignment(txt, Qt.AlignHCenter)
                # txt = scene.addText(self.factory.label, QFont('arial 6'))
                # txt.setPos(cx, 10)

            ctrl.setScene(scene)

            layout.setAlignment(ctrl, Qt.AlignHCenter)

            self.value.on_trait_change(self.update_object, 'state')

            self.control = QWidget()
            self.control.setLayout(layout)
예제 #18
0
    def setUp(self):
        #Acquire resources
        super(ItemRetrieve, self).setUp()
        self.scene = QGraphicsScene()

        self.topleft = QGraphicsRectItem(0, 0, 100, 100)
        self.topright = QGraphicsRectItem(100, 0, 100, 100)
        self.bottomleft = QGraphicsRectItem(0, 100, 100, 100)
        self.bottomright = QGraphicsRectItem(100, 100, 100, 100)

        self.items = [
            self.topleft, self.topright, self.bottomleft, self.bottomright
        ]

        for item in self.items:
            self.scene.addItem(item)
예제 #19
0
    def __init__(self, mainwindow):
        """ Initializes the GraphWidget. """
        super(GraphWidget, self).__init__(mainwindow)
        self.setupUi(self.mw)
        self.startRelation = None
        self.abstractGraph = None
        self.gv = pygraphviz.AGraph(strict=False)
        self.widget = self.layoutWidget
        self.log = logging.getLogger('.' + __name__)
        self.nodesToQNodes = {}
        self.qLines = []
        self.qpens = {}
        self.completer = QCompleter(list(""))
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setWidget(self.lineEdit)

        self.lastScale = 1
        self.initMenu()
        self.roots = set()
        self.doubleSpinBox.valueChanged[float].connect(self.changeScale)
        self.lineEdit.textChanged.connect(self.searchNode)
        self.rootSelector.insertItem(0, "---")
        self.rootSelector.currentIndexChanged[str].connect(self.newRoot)
        self.relations.currentIndexChanged[str].connect(self.newVariant)
        self.depth.valueChanged.connect(self.newRoot)
        self._updateActiveOntology()
        self.graphicsView.setScene(QGraphicsScene())
예제 #20
0
파일: zne.py 프로젝트: z25/pyZNodeEditor
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        self.logger = logging.getLogger("zne")
        self.logger.setLevel(logging.DEBUG)

        self.setMinimumSize(560,360)
        self.setWindowTitle("ZOCP Node Editor")
        self.setWindowIcon(QIcon('assets/icon.png'))

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self, self.scene, self.view)

        self.nodesEditor.onAddConnection = self.onAddConnection
        self.nodesEditor.onRemoveConnection = self.onRemoveConnection
        self.nodesEditor.onBlockMoved = self.onBlockMoved

        self.scale = 1
        self.installActions()

        self.initZOCP()

        self.nodes = {}
        self.pendingSubscribers = {}

        QTimer.singleShot(250, lambda: self.scene.invalidate())
예제 #21
0
	def __init__(self, graphicsView):
		self.scene = QGraphicsScene()
		self.scene.setSceneRect(0,0,SCENE_WIDTH,SCENE_HEIGHT)
		graphicsView.setScene(self.scene)

		# handles physics involved in collisiions/detection
		self.cm = collisionManager()
예제 #22
0
 def testIt(self):
     scene = QGraphicsScene()
     i1 = QGraphicsRectItem()
     scene.addItem(i1)
     i2 = QGraphicsRectItem(i1)
     i3 = QGraphicsRectItem()
     i4 = QGraphicsRectItem()
     group = scene.createItemGroup((i2, i3, i4))
     scene.removeItem(i1)
     del i1  # this shouldn't delete i2
     self.assertEqual(i2.scene(), scene)
     scene.destroyItemGroup(group)
     self.assertRaises(RuntimeError, group.type)
예제 #23
0
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        quitAct = QAction("&Quit",
                          self,
                          shortcut="Ctrl+Q",
                          statusTip="Exit the application",
                          triggered=self.close)

        addAct = QAction("&Add",
                         self,
                         statusTip="Add a block",
                         triggered=self.addBlock)

        fileMenu = self.menuBar().addMenu("&File")
        fileMenu.addAction(addAct)
        fileMenu.addSeparator()
        fileMenu.addAction(quitAct)

        self.setWindowTitle("Node Editor")

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self)
        self.nodesEditor.install(self.scene)

        block = QNEBlock(None)
        self.scene.addItem(block)
        block.addPort("test", 0, QNEPort.NamePort)
        block.addPort("TestBlock", 0, QNEPort.TypePort)
        block.addInputPort("in1")
        block.addInputPort("in2")
        block.addInputPort("in3")
        block.addOutputPort("out1")
        block.addOutputPort("out2")
        block.addOutputPort("out3")

        block = block.clone()
        block.setPos(150, 0)

        block = block.clone()
        block.setPos(150, 150)
예제 #24
0
class ConstructorWithRect(unittest.TestCase):
    '''QGraphicsScene qrect constructor and related sizes'''
    def setUp(self):
        #Acquire resources
        # PyQt4 doesn't accept a QRect as argument to constructor
        self.scene = QGraphicsScene(0, 200, 150, 175)

    def tearDown(self):
        #Release resources
        del self.scene

    def testHeight(self):
        #QGraphicsScene.height()
        self.assertEqual(self.scene.height(), 175)

    def testWidth(self):
        #QGraphicsScene.width()
        self.assertEqual(self.scene.width(), 150)
예제 #25
0
 def update_frame(self, img):
     '''
     update the image
     :return:
     '''
     #if not self.queue.empty():
     #    frame = self.queue.get()
     #img = frame['img']
     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
     size = self.video_view.size()
     img = cv2.resize(img, (size.width() - 10, size.height() - 10))
     height, width, bpc = img.shape
     bpl = bpc * width
     image = QImage(img.data, width, height, bpl, QImage.Format_RGB888)
     pitem = QGraphicsPixmapItem(QPixmap.fromImage(image))
     scene = QGraphicsScene()
     scene.addItem(pitem)
     self.video_view.setScene(scene)
예제 #26
0
class ConstructorWithRect(unittest.TestCase):
    """QGraphicsScene qrect constructor and related sizes"""

    def setUp(self):
        # Acquire resources
        # PyQt4 doesn't accept a QRect as argument to constructor
        self.scene = QGraphicsScene(0, 200, 150, 175)

    def tearDown(self):
        # Release resources
        del self.scene

    def testHeight(self):
        # QGraphicsScene.height()
        self.assertEqual(self.scene.height(), 175)

    def testWidth(self):
        # QGraphicsScene.width()
        self.assertEqual(self.scene.width(), 150)
예제 #27
0
class ReferenceCount(UsesQApplication):

    def setUp(self):
        super(ReferenceCount, self).setUp()
        self.scene = QGraphicsScene()

    def tearDown(self):
        super(ReferenceCount, self).tearDown()

    def beforeTest(self):
        points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
        pol = self.scene.addPolygon(QPolygonF(points))
        self.assert_(isinstance(pol, QGraphicsPolygonItem))
        self.wrp = weakref.ref(pol, pol_del)

        #refcount need be 3 because one ref for QGraphicsScene, and one to rect obj
        self.assertEqual(sys.getrefcount(pol), 3)

    def testReferenceCount(self):
        global destroyedRect
        global destroyedPol

        self.beforeTest()
        
        rect = self.scene.addRect(10.0, 10.0, 10.0, 10.0)
        self.assert_(isinstance(rect, QGraphicsRectItem))

        self.wrr = weakref.ref(rect, rect_del)

        #refcount need be 3 because one ref for QGraphicsScene, and one to rect obj
        self.assertEqual(sys.getrefcount(rect), 3)

        del rect
        #not destroyed because one ref continue in QGraphicsScene
        self.assertEqual(destroyedRect, False)
        self.assertEqual(destroyedPol, False)

        del self.scene

        #QGraphicsScene was destroyed and this destroy internal ref to rect
        self.assertEqual(destroyedRect, True)
        self.assertEqual(destroyedPol, True)
예제 #28
0
class ReferenceCount(UsesQApplication):

    def setUp(self):
        super(ReferenceCount, self).setUp()
        self.scene = QGraphicsScene()

    def tearDown(self):
        super(ReferenceCount, self).tearDown()

    def beforeTest(self):
        points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
        pol = self.scene.addPolygon(QPolygonF(points))
        self.assert_(isinstance(pol, QGraphicsPolygonItem))
        self.wrp = weakref.ref(pol, pol_del)

        #refcount need be 3 because one ref for QGraphicsScene, and one to rect obj
        self.assertEqual(sys.getrefcount(pol), 3)

    def testReferenceCount(self):
        global destroyedRect
        global destroyedPol

        self.beforeTest()
        
        rect = self.scene.addRect(10.0, 10.0, 10.0, 10.0)
        self.assert_(isinstance(rect, QGraphicsRectItem))

        self.wrr = weakref.ref(rect, rect_del)

        #refcount need be 3 because one ref for QGraphicsScene, and one to rect obj
        self.assertEqual(sys.getrefcount(rect), 3)

        del rect
        #not destroyed because one ref continue in QGraphicsScene
        self.assertEqual(destroyedRect, False)
        self.assertEqual(destroyedPol, False)

        del self.scene

        #QGraphicsScene was destroyed and this destroy internal ref to rect
        self.assertEqual(destroyedRect, True)
        self.assertEqual(destroyedPol, True)
예제 #29
0
 def testIt(self):
     scene = QGraphicsScene()
     i1 = QGraphicsRectItem()
     scene.addItem(i1)
     i2 = QGraphicsRectItem(i1)
     i3 = QGraphicsRectItem()
     i4 = QGraphicsRectItem()
     group = scene.createItemGroup((i2, i3, i4))
     scene.removeItem(i1)
     del i1  # this shouldn't delete i2
     self.assertEqual(i2.scene(), scene)
     scene.destroyItemGroup(group)
     self.assertRaises(RuntimeError, group.type)
예제 #30
0
class timelineTest(object):
    '''
    Main Class
    '''
    def __init__(self):
        self.app = QApplication.instance()
        if self.app is None:
            self.app = QApplication(sys.argv)
        loader = QUiLoader()
        self.mainWindow = loader.load("timelineTest.ui")
        self.scene = QGraphicsScene()
        self.mainWindow.graphicsView.setScene(self.scene)

        track = timelineTrack()
        self.addTrack(track)
        self.readEDL(track, 'sample.edl')

        self.mainWindow.show()
        self.app.exec_()

    def readEDL(self, track, edlfile):
        edlFile = open(edlfile)
        for line in edlFile.readlines():
            match = re.match(
                r"(\d{3})\s+\w+\s+\w+\s+\w+\s+(\d{2}:\d{2}:\d{2}:\d{2}) (\d{2}:\d{2}:\d{2}:\d{2}) (\d{2}:\d{2}:\d{2}:\d{2}) (\d{2}:\d{2}:\d{2}:\d{2})",
                line)
            if match is not None:
                editStart = tc2frames(match.group(2), 24)
                editEnd = tc2frames(match.group(3), 24)
                editLength = editStart - editEnd
                track.addClip(editStart, editLength)

        edlFile.close()

    def addTrack(self, track):
        '''
        Add track to timeline
        '''
        self.scene.addItem(track)

    """
예제 #31
0
    def __init__(self, camera=None, scene=None):
        super(DrawableCameraView, self).__init__()
        if scene is None:
            self.scene = QGraphicsScene()
        else:
            self.scene = scene
        self.setScene(self.scene)
        self.camera = camera
        self.pixmapitem = None

        # Overlay variables
        self.overlay_visible = False
        self.overlay_images = None
예제 #32
0
    def setUp(self):
        # Acquire resources
        super(ItemRetrieve, self).setUp()
        self.scene = QGraphicsScene()

        self.topleft = QGraphicsRectItem(0, 0, 100, 100)
        self.topright = QGraphicsRectItem(100, 0, 100, 100)
        self.bottomleft = QGraphicsRectItem(0, 100, 100, 100)
        self.bottomright = QGraphicsRectItem(100, 100, 100, 100)

        self.items = [self.topleft, self.topright, self.bottomleft, self.bottomright]

        for item in self.items:
            self.scene.addItem(item)
예제 #33
0
 def __init__(self, parent=None, controller=None):
     '''
     The initialization instanciates the GraphicsView/GraphicsScene
     combo. It sets up reference variables for handling nodes
     and edges of the graph. It register various signals.
     '''
     super(NetworkView, self).__init__(parent)
     
     self.parent = parent    # maybe needed later?
     self.controller = controller
     
     self.graphicsView = GraphicsView(self) 
     self.graphicsScene = QGraphicsScene(self)
     self.graphicsView.setScene(self.graphicsScene)
     
     self.modelSelectionInProgress = False
     
     self.registerSignals()
     
     self.statusBar = None   # can be set from the outside
     
     
     self.species = None
     self.reactions = None
     
     # TODO: check these
     self.nodes = []
     self.edges = []
     self.speciesNodesMapper = {}
     self.reactionEdgesMapper = {}        
     
     self.lock = QReadWriteLock()
     
     
     layout = QHBoxLayout()
     layout.addWidget(self.graphicsView, 1)
     self.setLayout(layout)
예제 #34
0
    def __init__(self,parent):
        global configuration
        super(OrderWorkflowDialog,self).__init__(parent)

        self.grey_pen = QPen(Qt.gray)

        title = _("Order workflow")
        self.setWindowTitle(title)
        self.title_widget = TitleWidget(title,self)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton( QDialogButtonBox.Ok)
        self.buttons.addButton( QDialogButtonBox.Cancel)

        self.thinfont = QFont()
        if configuration.font_select:
            self.thinfont.setPointSize(self.thinfont.pointSize()*2)

        self.scene = QGraphicsScene()
        self.scene.selectionChanged.connect(self.selectionChanged)

        self.view = QGraphicsView(self)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.view.setScene(self.scene)

        top_layout = QVBoxLayout()
        top_layout.addWidget(self.title_widget)
        top_layout.addWidget(self.view)
        top_layout.addWidget(self.buttons)

        self.setLayout(top_layout) # QWidget takes ownership of the layout
        self.buttons.accepted.connect(self.save_and_accept)
        self.buttons.rejected.connect(self.cancel)

        self.initial_state = None
        self.selected_state = None
        self._drawNodes(self.scene,self.selected_state,self.initial_state)
예제 #35
0
    def testIt(self):
        scene = QGraphicsScene()

        minSize = QSizeF(30, 100)
        prefSize = QSizeF(210, 100)
        maxSize = QSizeF(300, 100)

        a = createItem(minSize, prefSize, maxSize, "A")
        b = createItem(minSize, prefSize, maxSize, "B")
        c = createItem(minSize, prefSize, maxSize, "C")
        d = createItem(minSize, prefSize, maxSize, "D")

        view = QGraphicsView(scene)
        view.show()
        self.app.exec_()
예제 #36
0
    def testQGraphicsProxyWidget(self):
        scene = QGraphicsScene()

        proxy = QGraphicsProxyWidget(None, Qt.Window)
        widget = QLabel('Widget')
        proxy.setWidget(widget)
        proxy.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
        scene.addItem(proxy)
        scene.setSceneRect(scene.itemsBoundingRect())

        view = QGraphicsView(scene)
        view.setRenderHints(QPainter.Antialiasing|QPainter.SmoothPixmapTransform)
        view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
        view.show()

        timer = QTimer.singleShot(100, self.app.quit)
        self.app.exec_()
예제 #37
0
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        quitAct = QAction("&Quit", self, shortcut="Ctrl+Q",
            statusTip="Exit the application", triggered=self.close)

        addAct = QAction("&Add", self, statusTip="Add a block", triggered=self.addBlock)

        fileMenu = self.menuBar().addMenu("&File")
        fileMenu.addAction(addAct)
        fileMenu.addSeparator()
        fileMenu.addAction(quitAct)

        self.setWindowTitle("Node Editor")

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self)
        self.nodesEditor.install(self.scene)

        block = QNEBlock(None)
        self.scene.addItem(block)
        block.addPort("test", 0, QNEPort.NamePort)
        block.addPort("TestBlock", 0, QNEPort.TypePort)
        block.addInputPort("in1");
        block.addInputPort("in2");
        block.addInputPort("in3");
        block.addOutputPort("out1");
        block.addOutputPort("out2");
        block.addOutputPort("out3");

        block = block.clone()
        block.setPos(150,0)

        block = block.clone()
        block.setPos(150,150)
예제 #38
0
    def testCustomProxyWidget(self):
        scene = QGraphicsScene()

        proxy = CustomProxy(None, Qt.Window)
        widget = QLabel('Widget')
        proxy.setWidget(widget)
        proxy.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
        scene.addItem(proxy)
        scene.setSceneRect(scene.itemsBoundingRect())

        view = QGraphicsView(scene)
        view.setRenderHints(QPainter.Antialiasing|QPainter.SmoothPixmapTransform)
        view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
        view.show()

        timer = QTimer.singleShot(100, self.app.quit)
        self.app.exec_()
예제 #39
0
class QColorOnSetBrush(UsesQApplication):
    '''Test case for passing a QColor directly to setBrush'''

    def setUp(self):
        #Acquire resources
        super(QColorOnSetBrush, self).setUp()

        self.scene = QGraphicsScene()
        poly = QPolygonF()
        self.item = self.scene.addPolygon(poly)
        self.color = QColor('black')

    def tearDown(self):
        #Release resources
        del self.color
        del self.item
        del self.scene
        super(QColorOnSetBrush, self).tearDown()

    def testQColor(self):
        #QGraphicsAbstractShapeItem.setBrush(QColor)
        self.item.setBrush(self.color)
        self.assertEqual(QBrush(self.color), self.item.brush())
예제 #40
0
class ItemRetrieve(UsesQApplication):
    '''Tests for QGraphicsScene item retrieval methods'''

    qapplication = True

    def setUp(self):
        #Acquire resources
        super(ItemRetrieve, self).setUp()
        self.scene = QGraphicsScene()

        self.topleft = QGraphicsRectItem(0, 0, 100, 100)
        self.topright = QGraphicsRectItem(100, 0, 100, 100)
        self.bottomleft = QGraphicsRectItem(0, 100, 100, 100)
        self.bottomright = QGraphicsRectItem(100, 100, 100, 100)

        self.items = [
            self.topleft, self.topright, self.bottomleft, self.bottomright
        ]

        for item in self.items:
            self.scene.addItem(item)

    def tearDown(self):
        #Release resources
        del self.scene
        super(ItemRetrieve, self).tearDown()

    def testItems(self):
        #QGraphicsScene.items()
        items = self.scene.items()
        for i in items:
            self.assertTrue(i in self.items)

    def testItemAt(self):
        #QGraphicsScene.itemAt()
        self.assertEqual(self.scene.itemAt(50, 50), self.topleft)
        self.assertEqual(self.scene.itemAt(150, 50), self.topright)
        self.assertEqual(self.scene.itemAt(50, 150), self.bottomleft)
        self.assertEqual(self.scene.itemAt(150, 150), self.bottomright)
예제 #41
0
class ItemRetrieve(UsesQApplication):
    """Tests for QGraphicsScene item retrieval methods"""

    qapplication = True

    def setUp(self):
        # Acquire resources
        super(ItemRetrieve, self).setUp()
        self.scene = QGraphicsScene()

        self.topleft = QGraphicsRectItem(0, 0, 100, 100)
        self.topright = QGraphicsRectItem(100, 0, 100, 100)
        self.bottomleft = QGraphicsRectItem(0, 100, 100, 100)
        self.bottomright = QGraphicsRectItem(100, 100, 100, 100)

        self.items = [self.topleft, self.topright, self.bottomleft, self.bottomright]

        for item in self.items:
            self.scene.addItem(item)

    def tearDown(self):
        # Release resources
        del self.scene
        super(ItemRetrieve, self).tearDown()

    def testItems(self):
        # QGraphicsScene.items()
        items = self.scene.items()
        for i in items:
            self.assertTrue(i in self.items)

    def testItemAt(self):
        # QGraphicsScene.itemAt()
        self.assertEqual(self.scene.itemAt(50, 50), self.topleft)
        self.assertEqual(self.scene.itemAt(150, 50), self.topright)
        self.assertEqual(self.scene.itemAt(50, 150), self.bottomleft)
        self.assertEqual(self.scene.itemAt(150, 150), self.bottomright)
예제 #42
0
class SceneManager():
	
	def __init__(self, graphicsView):
		self.scene = QGraphicsScene()
		self.scene.setSceneRect(0,0,SCENE_WIDTH,SCENE_HEIGHT)
		graphicsView.setScene(self.scene)

		# handles physics involved in collisiions/detection
		self.cm = collisionManager()

	# add object to simulation scene (given parameters)
	# input:	'values'  contains (x,y,x_vel,y_vel,mass,radius)
	def addItem(self,param):
		values = self.decode(param)
		item = Ball(values[0],values[1],values[4],values[5])
		item.set_velocity(values[2],values[3])
		self.scene.addItem(item)

	def addItems(self,items):
		for item in items:
			values = self.decode(item)
			ball_obj = Ball(values[0],values[1],values[4],values[5])
			ball_obj.set_velocity(values[2],values[3])
			self.scene.addItem(ball_obj)

	# translate parameters received by TCP
	def decode(self,msg):
		delims = ['r','m','yv','xv','y','x']
		values = []

		# traverses delimeters to extract values
		for i in range(len(delims)):
			index = msg.index(delims[i])			# search for delimeter
			arg = msg[index + len(delims[i]) :]		# extract value
			values.append(int(float(arg)))					# store value
			msg = msg[:index]				# reduce message left to parse
		
		values.reverse()
		return values

	# access all items in the simulation scene
	def getItems(self):
		return self.scene.items()

	def deleteItems(self):
		return self.scene.clear()

	def getItemsForTCP(self):
		items = self.scene.items()
		tcp_list = []

		for item in items:
			tcp_list.append(str(item))

		return tcp_list

	# determine an item's next location
	def next_move(self,item):
		
		# check whether any ball-to-ball collisions will occur
		collisions = self.cm.if_ball_collision(item,self.getItems())
		
		if (len(collisions) > 0):	# colllision identified
			# print '\nInside next_move()'
			# print ('Item: ' + str(item) + ' List: ' )#+ str(collisions))
			# for ball in collisions:
			# 	print str(ball)				#DEBUG
			# obtain velocities so that balls just collide
			delta_x, delta_y = self.cm.vel_to_ball(item,collisions[0])
			# delta_x = item.x_vel
			# delta_y = item.y_vel
			self.cm.ball_to_ball(item,collisions[0])
		else:
			# determine if a wall will be hit in the next move
			hit_wall = self.cm.if_wall_collision(item,SCENE_HEIGHT,SCENE_WIDTH)

			if (hit_wall != 'NONE'):	# if wall collision will occur
				# determine displacement left to collide with wall
				delta_x, delta_y = self.cm.vel_to_wall(item,hit_wall,SCENE_HEIGHT,SCENE_WIDTH)
				# set object's velocity after impacting the wall
				self.cm.ball_to_wall(item,hit_wall)
			else:
				#keep the ball in the same trajectory
				delta_x = item.x_vel
				delta_y = item.y_vel

		# next x/y destination of the item in LOCAL coordinates
        # require the offsets (-item.x_start and -item.y_start)
        # given the fact that the item.x_pos and item.y_pos values
        # represent locations in global coordinates
		next_x = item.x_pos + delta_x - item.x_start
		next_y = item.y_pos + delta_y - item.y_start

		return next_x,next_y
예제 #43
0
 def setUp(self):
     #Acquire resources
     super(AddItem, self).setUp()
     self.scene = QGraphicsScene()
예제 #44
0
 def setUp(self):
     super(ReferenceCount, self).setUp()
     self.scene = QGraphicsScene()
예제 #45
0
 def setUp(self):
     #Acquire resources
     # PyQt4 doesn't accept a QRect as argument to constructor
     self.scene = QGraphicsScene(0, 200, 150, 175)
예제 #46
0
class AddItem(UsesQApplication):
    '''Tests for QGraphicsScene.add*'''

    qapplication = True

    def setUp(self):
        #Acquire resources
        super(AddItem, self).setUp()
        self.scene = QGraphicsScene()
        # While the scene does not inherits from QWidget, requires
        # an application to make the internals work.

    def tearDown(self):
        #Release resources
        del self.scene
        super(AddItem, self).tearDown()

    def testEllipse(self):
        #QGraphicsScene.addEllipse
        item = self.scene.addEllipse(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsEllipseItem))

    def testLine(self):
        #QGraphicsScene.addLine
        item = self.scene.addLine(100, 100, 200, 200)
        self.assertTrue(isinstance(item, QGraphicsLineItem))

    def testPath(self):
        #QGraphicsScene.addPath
        item = self.scene.addPath(QPainterPath())
        self.assertTrue(isinstance(item, QGraphicsPathItem))

    def testPixmap(self):
        #QGraphicsScene.addPixmap
        item = self.scene.addPixmap(QPixmap())
        self.assertTrue(isinstance(item, QGraphicsPixmapItem))

    def testPolygon(self):
        #QGraphicsScene.addPolygon
        points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
        item = self.scene.addPolygon(QPolygonF(points))
        self.assertTrue(isinstance(item, QGraphicsPolygonItem))

    def testRect(self):
        #QGraphicsScene.addRect
        item = self.scene.addRect(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsRectItem))

    def testSimpleText(self):
        #QGraphicsScene.addSimpleText
        item = self.scene.addSimpleText('Monty Python 42')
        self.assertTrue(isinstance(item, QGraphicsSimpleTextItem))

    def testText(self):
        #QGraphicsScene.addText
        item = self.scene.addText('Monty Python 42')
        self.assertTrue(isinstance(item, QGraphicsTextItem))

    def testWidget(self):
        #QGraphicsScene.addWidget
        # XXX: printing some X11 error when using under PyQt4
        item = self.scene.addWidget(QPushButton())
        self.assertTrue(isinstance(item, QGraphicsProxyWidget))
예제 #47
0
 def setUp(self):
     # Acquire resources
     super(AddItem, self).setUp()
     self.scene = QGraphicsScene()
예제 #48
0
class AddItem(UsesQApplication):
    """Tests for QGraphicsScene.add*"""

    qapplication = True

    def setUp(self):
        # Acquire resources
        super(AddItem, self).setUp()
        self.scene = QGraphicsScene()
        # While the scene does not inherits from QWidget, requires
        # an application to make the internals work.

    def tearDown(self):
        # Release resources
        del self.scene
        super(AddItem, self).tearDown()

    def testEllipse(self):
        # QGraphicsScene.addEllipse
        item = self.scene.addEllipse(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsEllipseItem))

    def testLine(self):
        # QGraphicsScene.addLine
        item = self.scene.addLine(100, 100, 200, 200)
        self.assertTrue(isinstance(item, QGraphicsLineItem))

    def testPath(self):
        # QGraphicsScene.addPath
        item = self.scene.addPath(QPainterPath())
        self.assertTrue(isinstance(item, QGraphicsPathItem))

    def testPixmap(self):
        # QGraphicsScene.addPixmap
        item = self.scene.addPixmap(QPixmap())
        self.assertTrue(isinstance(item, QGraphicsPixmapItem))

    def testPolygon(self):
        # QGraphicsScene.addPolygon
        points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
        item = self.scene.addPolygon(QPolygonF(points))
        self.assertTrue(isinstance(item, QGraphicsPolygonItem))

    def testRect(self):
        # QGraphicsScene.addRect
        item = self.scene.addRect(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsRectItem))

    def testSimpleText(self):
        # QGraphicsScene.addSimpleText
        item = self.scene.addSimpleText("Monty Python 42")
        self.assertTrue(isinstance(item, QGraphicsSimpleTextItem))

    def testText(self):
        # QGraphicsScene.addText
        item = self.scene.addText("Monty Python 42")
        self.assertTrue(isinstance(item, QGraphicsTextItem))

    def testWidget(self):
        # QGraphicsScene.addWidget
        # XXX: printing some X11 error when using under PyQt4
        item = self.scene.addWidget(QPushButton())
        self.assertTrue(isinstance(item, QGraphicsProxyWidget))
예제 #49
0
# This is the magic:
    def paint(self, painter, option, widget=None):
        painter_inverted = QPainter()
        brect= QGraphicsProxyWidget.boundingRect(self)
        invertedColor = QImage(brect.width(),brect.height(),QImage.Format_RGB32)
        painter_inverted.begin(invertedColor)
        QGraphicsProxyWidget.paint(self,painter_inverted, option, widget)
        painter_inverted.end()
        painter.drawImage(0,0,invertedColor.rgbSwapped())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setApplicationName("tete")

    scene = QGraphicsScene()

    media = Phonon.MediaObject()
    video = Phonon.VideoWidget()
    Phonon.createPath(media, video)

    proxy = CustomProxy()
    proxy.setWidget(video)
    rect = proxy.boundingRect()
    #proxy.setPos(0, 0)
    #proxy.show()
    scene.addItem(proxy)

    media.setCurrentSource("/home/amit/Videos/Kung Fu Panda 3 (2015) 1080p R6 [DayT.se].mp4")
    media.play()
예제 #50
0
class NetworkView(QAbstractItemView):
    '''
    The NetworkView is sort of a wrapper around the Qt Canvas concept
    with QGraphicsView and QGraphicsScene.
    It inherits from QAbstractItemView to live in the world of Qt Model
    View Controller (MVC). Basically, it is there to bring these two worlds 
    together. (Why the hell Qt does not provide something like this, I
    don't know.)
    
    NetworkView handles the usual model update methods (e.g. dataChanged)
    and handles selection changes between the model-based views and the 
    internal GraphicsView. (Which itself is not a QGraphicsView directly but
    a simple wrapper to support mousewheel zooming, etc.)
    
    @param parent: The standard Qt parent
    @type parent: QWidget (probably ;))
    
    @param controller: The network controller that belongs to this view.
    @type controller: ModelController
    
    @since: 2010-04-12
    '''

    __author__ = "Moritz Wade"
    __contact__ = "*****@*****.**"
    __copyright__ = "Zuse Institute Berlin 2010"

    def __init__(self, parent=None, controller=None):
        '''
        The initialization instanciates the GraphicsView/GraphicsScene
        combo. It sets up reference variables for handling nodes
        and edges of the graph. It register various signals.
        '''
        super(NetworkView, self).__init__(parent)
        
        self.parent = parent    # maybe needed later?
        self.controller = controller
        
        self.graphicsView = GraphicsView(self) 
        self.graphicsScene = QGraphicsScene(self)
        self.graphicsView.setScene(self.graphicsScene)
        
        self.modelSelectionInProgress = False
        
        self.registerSignals()
        
        self.statusBar = None   # can be set from the outside
        
        
        self.species = None
        self.reactions = None
        
        # TODO: check these
        self.nodes = []
        self.edges = []
        self.speciesNodesMapper = {}
        self.reactionEdgesMapper = {}        
        
        self.lock = QReadWriteLock()
        
        
        layout = QHBoxLayout()
        layout.addWidget(self.graphicsView, 1)
        self.setLayout(layout)


    def draw_graph(self, graph):
        '''
        Invokes a layout algorithm of the networkx package in another
        Thread and calls self.redraw.

        @param graph: A network graph
        @type graph: Graph

        @todo: See, that threading works correctly.
        '''
        logging.info("Drawing network...")

        self.graph = graph
        self.speciesNodesMapper = {}
        self.draw() # draws the current positions (may be None), creates Nodes/Edges

        # just testing a progress dialog
        #        progressDialog = QProgressDialog()
        #        progressDialog.setMinimum(0)
        #        progressDialog.setMaximum(100)
        #        progressDialog.show()
        #
        #        for i in range(100):
        #          time.sleep(0.2)
        #          progressDialog.setValue(i)
        self.positions = {}

        #        time.sleep(0.5)
        #
        #        dummyThread = DummyProgressThread()
        #        #dummyThread = DummyThrobberThread()
        #        progressService = ProgressBarService()
        #        progressService.connectToThread(dummyThread)
        #        dummyThread.start()

        # doing the layout
        threadedLayouter = LayoutThread(self.lock, self)

        self.connect(threadedLayouter, SIGNAL("finished(bool)"), self.layout_finished)
        #threadedLayouter.finished.connect(self.layout_finished)
        threadedLayouter.initialize(self.graph, "spring", self.positions)
        threadedLayouter.start()
#        threadedLayouter.run() # for debugging purposes


    def createEdge(self, graphEdge):
        '''
        Creates a graphical Edge given a networkX edge (which is basically
        a 3-tuple with ([reactants],[products],{"reaction": wrappedReaction}).
        '''
        species1 = graphEdge[0]
        species2 = graphEdge[1]
        try:
            reactionWrapper = graphEdge[2]["reaction"]
        except:
            pass
        sourceNode = self.speciesNodesMapper[species1]
        targetNode = self.speciesNodesMapper[species2]
        edge = Edge(sourceNode, targetNode, self.graphicsScene, wrappedObject=reactionWrapper)
        sourceNode.edges.append(edge)
        if reactionWrapper is not None:
            self.reactionEdgesMapper[edge] = reactionWrapper # 1 Edge corresponds to exactly 1 Reaction
            if reactionWrapper in self.reactionEdgesMapper:  # 1 Reaction can correspond to n Edges
                self.reactionEdgesMapper[reactionWrapper].append(edge)
            else:
                self.reactionEdgesMapper[reactionWrapper] = [edge]
        return edge

    def draw(self):
        self.isRedrawing = True

        self.graphicsScene.clear()
        #
        self.nodes = []
        self.speciesNodesMapper = {}
        self.reactionEdgesMapper = {}

        for speciesOrHyperNode in self.graph.nodes():
            (x, y) = speciesOrHyperNode.Position
            node = self.createNode(speciesOrHyperNode, x, y)


        for edge in self.graph.edges(data=True):
            edge = self.createEdge(edge)

        logging.info("Finished drawing network...")

        self.isRedrawing = False


    def layout_finished(self, finished):
        '''
        This is a slot. It calls self.redraw if finished = true.

        @param finished: Tells if the layout is finished.
        @type finished: bool
        '''
        if finished:
            for speciesOrHyperNode in self.graph.nodes(): # setting the updated coordinates
                (xRel, yRel) = self.positions[speciesOrHyperNode]
                x = xRel * self.width() / 2
                y = yRel * self.height() / 2
                speciesOrHyperNode.Position = (x, y)
            self.redraw()

    def redraw(self):
        '''
        Rewrite of the previous redraw approach. It is based on the node positions
        as stored in the SBMLEntitys' Position property.
        Nodes and Edges are only created once (on drawGraph). They are not
        recreated here, only repositioned.

        @since: 2010-09-20
        '''
        self.isRedrawing = True
        for speciesOrHyperNode in self.graph.nodes():
            (x, y) = speciesOrHyperNode.Position
            if speciesOrHyperNode not in self.speciesNodesMapper:
                logging.debug("Encountered unknown node while redrawing. %s" % speciesOrHyperNode)
                continue
                #self.addNode(speciesOrHyperNode)
            node = self.speciesNodesMapper[speciesOrHyperNode]
            node.isRedrawing = True
            node.setPos(x, y)
            node.isRedrawing = False


        self.isRedrawing = False

    def addNode(self, node):
        if type(node) is not HyperEdgeNode:
            x = self.width()/2
            y = self.height()/2
        else:
            x, y = self.calculateHyperNodePosition(node)

        self.createNode(node, x, y)


    def calculateHyperNodePosition(self, hyperNode):
        '''
        Gets the positions of node adjacent to the given hyper node
        and calculates an average position between them.
        '''
        #edges = self.graph.edges([hyperNode], data=True)
        neighbors = self.graph.neighbors(hyperNode)
        x = 0
        y = 0
        for neighbor in neighbors:
            currX,currY = neighbor.Position
            x += currX
            y += currY
        x /= len(neighbors)
        y /= len(neighbors)

        return x,y

    def registerSignals(self):
        '''
        Connects all the necessary signals.
        '''
        self.connect(self.graphicsScene, SIGNAL("selectionChanged()"), self.sceneSelectionChanged)

        
        
    def findItemInModel(self, item):
        '''
        Finds the QModelIndex corresponding to the given
        item. The given item is a Node or Edge.
        
        @param item: The item to find
        @type item: SBMLEntity
        
        @return: The model index of the given item
        @rtype: QModelIndex
        '''
        
        sbmlEntity = item.wrappedObject
        map = self.model().modelIndexToEntityMap
        
        if map is None:
            return
        
        if sbmlEntity in map:
            index = map[sbmlEntity]
            return index
        
        #print sbmlEntity
        
        
        
    def changeViewSelection(self, modelSelection, state):
        '''
        Gets a Qt selection object and works through it to
        set the given selection state on all the affected items.
        This syncs the selection (Model)View -> NetworkView
        
        @param modelSelection: A Qt selection consisting of indexes
        @todo: Include type of modelSelection in doc
        '''
        #self.setSelectedAll(False)
        for selectionRange in modelSelection:
            #logging.debug("Creating View selection for %s items" % len(selectionRange.indexes()))
            for itemIndex in selectionRange.indexes():
                item = itemIndex.internalPointer()
                #if item in self.speciesNodesMapper:
                try:    # fast then "if item in"
                    self.speciesNodesMapper[item].setSelected(state)
                except:
                    try:
                        
                #elif item in self.reactionEdgesMapper:
                # item will be a list for all the Edges that this Reaction
                # potentially has (in case of hyper-edge)
                        for edge in self.reactionEdgesMapper[item]:
                            edge.setSelected(state)
                    except:
                        pass
                                
        
        #return itemIndex, edge, selectionRange, item
        
        
    def setSelectedAll(self, state):
        self.setSelectedNodes(state)
        self.setSelectedEdges(state)
        
    def setSelectedNodes(self, state):
        for node in self.nodes:
            node.setSelected(state)
            
    def setSelectedEdges(self, state):
        for edge in self.edges:
            edge.setSelected(state)
        
    
    def createNode(self, speciesOrHyperNode, x, y):
        speciesOrHyperNode.Position = (x,y)
        node = Node(position=(x, y), scene=self.graphicsScene, wrappedObject=speciesOrHyperNode)
        self.speciesNodesMapper[speciesOrHyperNode] = node
        self.speciesNodesMapper[node] = speciesOrHyperNode

        if type(speciesOrHyperNode) == HyperEdgeNode:
            self.speciesNodesMapper[speciesOrHyperNode.Reaction] = node # to get from the wrapped reaction to the node
#        self.connect(speciesOrDummyNode, SIGNAL("PositionChanged"), lambda who = speciesOrDummyNode: self.nodeMoved(who))
        return node

    def removeSpeciesNode(self, sbmlEntity):
#        logging.debug("Remove Entity from NetworkView: %s\n\ID: %s" % (sbmlEntity.Item, sbmlEntity.getId()))
        if sbmlEntity in self.speciesNodesMapper:
            node = self.speciesNodesMapper[sbmlEntity]
            self.graphicsScene.removeItem(node)
            self.speciesNodesMapper.pop(sbmlEntity)
#        else:
#            print "Remove Entity from NetworkView: %s\n\ID: %s" % (sbmlEntity.Item, sbmlEntity.getId())
#            print


    def removeReaction(self, reaction):
        #for reaction in reactions:
        if not self.reactionEdgesMapper.has_key(reaction):
            return
        
        edges = self.reactionEdgesMapper[reaction]
        for edge in edges:
            # handle nodes that are connected to this Edge
            nodes = [edge.sourceNode, edge.targetNode]
            for node in nodes:
                if edge in node.edges:
                    node.edges.remove(edge)

            # handle the Edge itself
            self.graphicsScene.removeItem(edge)
            self.reactionEdgesMapper.pop(edge) # just remove it from the dict

        self.reactionEdgesMapper.pop(reaction)

        # reactions are also linked to hypernodes; clear this, too
        if reaction in self.speciesNodesMapper.keys():
            hyperNode = self.speciesNodesMapper[reaction]
            self.speciesNodesMapper.pop(reaction)
            self.graphicsScene.removeItem((hyperNode))
            self.speciesNodesMapper.pop(hyperNode)


    def addReaction(self, edge):
        self.createEdge(edge)

    def updateNodesAndEdges(self):
        '''
        Works through the graph and adds missing Nodes and Edges.

        @since: 2010-10-04
        '''
        # handling Nodes
        for node in self.graph.nodes():
            if node not in self.speciesNodesMapper.keys():
                self.addNode(node)

        # handling Edges
        for edge in self.graph.edges(data=True):
            reaction = edge[2]["reaction"]
            if not reaction:
                continue
            if reaction not in self.reactionEdgesMapper.keys():
                # reaction is totally new, just create this edge
                self.createEdge(edge)
            else:
                # have to check if the reaction is already there, but maybe
                # with a different edge (happens in the case of hyper-edges)

                reactionEdges = self.reactionEdgesMapper[reaction]
                edgeIsThere = False
                for existingEdge in reactionEdges:    # we have to compare based on source and target nodes
                    source = existingEdge.sourceNode.wrappedObject
                    target = existingEdge.targetNode.wrappedObject
                    reactionSource = edge[0]
                    reactionTarget = edge[1]
#                    if reactionSource == source:
#                        logging.debug("Source is identical")
#                    if reactionTarget == target:
#                        logging.debug("Target is identical")
#                    if reactionSource == source and reactionTarget == target:
#                        logging.debug("Edge is there")
                    if reactionSource == source and reactionTarget == target:
                        edgeIsThere = True

                if not edgeIsThere:
                    self.createEdge(edge)
                    # some debugging info
#                    logging.debug("About to add an edge between...")
#                    logging.debug("Source: %s" % edge[0].getId())
#                    logging.debug("Target: %s" % edge[1].getId())
#                if edge not in reactionEdges:
#                    edge = self.createEdge(edge)


        
    #==========================================================================
    # Slots
    #==========================================================================
    
    @Slot()
    def sceneSelectionChanged(self):
        '''
        C++: void sceneSelectionChanged()
        
        This syncs the selection 
        NetworkView -> (Model)View
        To do this it uses the QSelectionModel that the ModelController
        has as a reference.
        '''
        if self.modelSelectionInProgress:   # don't create an selection update loop
            return
        
        itemSelection = QItemSelection()
        selectionModel = self.controller.getGlobalSelectionModel()

        if not self.graphicsScene:
            return

        selectedItems = self.graphicsScene.selectedItems()
        #logging.debug("Creating model selection for %s items" % len(selectedItems))
        for item in selectedItems:
            index = self.findItemInModel(item)
            if index is not None:
                itemSelection.select(index, index)
            
        selectionModel.select(itemSelection, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
        
        
        
    @Slot(QModelIndex)
    def update(self, index):
        '''
        C++: void update(const QModelIndex&)
        '''
        pass
        
    @Slot(QModelIndex, QModelIndex)
    def dataChanged(self, topLeftIndex, bottomRightIndex):
        '''
        C++: void dataChanged(const QModelIndex&,const QModelIndex&)
        
        Gets the range of changed indexes and updates all the nodes
        therein.
        
        Currently, only the topLeftIndex is used. The possible span
        of indexes is ignored.
        
        @todo: Use whole span of indexes.
        
        @param topLeftIndex: Starting index
        @type topLeftIndex: QModelIndex
        @param bottomRightIndex: Ending index
        @type bottomRightIndex: QModelIndex
        '''
        
        item = topLeftIndex.internalPointer()
        if item is None:
            return
        
        if item not in self.speciesNodesMapper:
            return
        
        node = self.speciesNodesMapper[item]
        if node is None:
            return
        
        node.redraw()
        

    #==========================================================================
    # base class methods that we override to enable the binding of the model 
    # (selection, etc.) to the GraphicsView
    #==========================================================================
        


    def selectionChanged(self, currentSelection, previousSelection):
        self.modelSelectionInProgress = True
        self.changeViewSelection(previousSelection, False)
        self.changeViewSelection(currentSelection, True)
        self.modelSelectionInProgress = False
            
        
        
    #==========================================================================
    # abstract base classes that need to be implemented but that we don't 
    # really use (maybe some of them later?)
    #==========================================================================
    
    def indexAt(self, point):
        return QModelIndex()
    
    def moveCursor(self, cursorAction, modifiers):
        return QModelIndex()
        
    def verticalOffset(self):
        return 0
    
    def horizontalOffset(self):
        return 0
    
    def visualRegionForSelection(self, selection):
        return QRegion()
    
    def visualRect(self, index):
        return QRect()
    
    def scrollTo(self, index, hint):
        pass



        
예제 #51
0
 def setUp(self):
     super(ReferenceCount, self).setUp()
     self.scene = QGraphicsScene()
예제 #52
0
from PySide.QtGui import (QApplication, QGraphicsView, QGraphicsScene,
                          QMainWindow, QPixmap, QPainter)
from PySide.QtCore import Qt
import sys

if __name__ == '__main__':
    app = QApplication(sys.argv)
    scene = QGraphicsScene()
    view = QGraphicsView(scene)
    view.scale(15, 15)

    pix = QPixmap(200, 50)
    pix.fill(Qt.white)
    p = QPainter(pix)
    p.setPen(Qt.black)
    #p.setBrush(Qt.red)
    for i in range(1, 10):
        p.drawEllipse(0, 0, i, i)
        p.translate(i+5, 0)
    p.end()
    pixItem = scene.addPixmap(pix)

    win = QMainWindow()
    win.setCentralWidget(view)
    win.resize(700, 200)
    win.show()

    sys.exit(app.exec_())
예제 #53
0
class DrawableCameraView(QGraphicsView):
    overlay_changed = Signal()

    def __init__(self, camera=None, scene=None):
        super(DrawableCameraView, self).__init__()
        if scene is None:
            self.scene = QGraphicsScene()
        else:
            self.scene = scene
        self.setScene(self.scene)
        self.camera = camera
        self.pixmapitem = None

        # Overlay variables
        self.overlay_visible = False
        self.overlay_images = None

    def set_overlays(self, filenames):
        if not self.overlay_images:
            self.overlay_filenames = filenames
            self.overlay_images = [None] * len(filenames)
            self.overlay_index = len(filenames)  # Start at live video
        else:
            old_fnames = self.overlay_filenames
            old_images = self.overlay_images
            new_fnames = filenames
            new_images = [None] * len(new_fnames)

            for old_fname in old_fnames:
                i = new_fnames.index(old_fname)
                new_images[i] = old_images[i]

            self.overlay_filenames = new_fnames
            self.overlay_images = new_images
            self.overlay_index = len(filenames)

    def hide_overlay(self):
        if self.overlay_index < len(self.overlay_images):
            self.overlay_images[self.overlay_index].hide()
        self.overlay_visible = False

    def show_overlay(self):
        if self.overlay_index < len(self.overlay_images):
            self.overlay_images[self.overlay_index].show()
        self.overlay_visible = True

    def keyPressEvent(self, event):
        key = event.key()
        if self.overlay_visible and self.overlay_images is not None:
            # We have overlays active and visible
            if key == Qt.Key_Left:
                self.overlay_index -= 1
                if self.overlay_index < 0:
                    self.overlay_index = 0  # No wraparound
                else:
                    self.overlay_changed.emit()
                    if self.overlay_images[self.overlay_index] is None:
                        self._add_overlay_image()

                self.overlay_images[self.overlay_index].show()
                if self.overlay_index+1 < len(self.overlay_images):
                    self.overlay_images[self.overlay_index+1].hide()
            elif key == Qt.Key_Right:
                self.overlay_index += 1
                if self.overlay_index > len(self.overlay_images):
                    self.overlay_index = len(self.overlay_images)
                else:
                    if self.overlay_index < len(self.overlay_images):
                        self.overlay_images[self.overlay_index].show()
                    self.overlay_changed.emit()
                    self.overlay_images[self.overlay_index-1].hide()
        else:
            # Pass event through to base class
            QGraphicsView.keyPressEvent(self, event)

    def _add_overlay_image(self):
        fname = self.overlay_filenames[self.overlay_index]
        self.overlay_images[self.overlay_index] = self.scene.addPixmap(QPixmap(fname))
        self.overlay_images[self.overlay_index].setZValue(10000000)

    def start_video(self, framerate=None):
        timer = QTimer()
        timer.timeout.connect(self._wait_for_frame)
        self.camera.start_live_video(framerate)
        timer.start(int(1000/self.camera.framerate))
        self.timer = timer
        self.centerOn(self.camera.width/2, self.camera.height/2)

    def stop_video(self):
        self.camera.stop_live_video()
        self.timer.stop()

    def _wait_for_frame(self):
        if self.camera.wait_for_frame(0):
            data = self.camera.image_buffer()
            bpl = self.camera.bytes_per_line
            format = QImage.Format_RGB32
            image = QImage(data, self.camera.width, self.camera.height, bpl, format)
            if self.pixmapitem is None:
                self.pixmapitem = self.scene.addPixmap(QPixmap.fromImage(image))
            else:
                self.pixmapitem.setPixmap(QPixmap.fromImage(image))
예제 #54
0
    def setupUi(self):

        scene = QGraphicsScene(self)
        self.view = QGraphicsView(scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVisible(True)
        self.view.setInteractive(True)

        self.createPixmapIcon()

        self.mapWidget = MapWidget(self.mapManager)
        scene.addItem(self.mapWidget)
        self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95))
        self.mapWidget.setZoomLevel(5)

        #...
        self.slider = QSlider(Qt.Vertical, self)
        self.slider.setTickInterval(1)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setMaximum(self.mapManager.maximumZoomLevel())
        self.slider.setMinimum(self.mapManager.minimumZoomLevel())

        self.slider.valueChanged[int].connect(self.sliderValueChanged)
        self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged)

        mapControlLayout = QVBoxLayout()

        self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged)

        for mapType in self.mapWidget.supportedMapTypes():
            radio = QRadioButton(self)
            if mapType == QGraphicsGeoMap.StreetMap:
                radio.setText('Street')
            elif mapType == QGraphicsGeoMap.SatelliteMapDay:
                radio.setText('Sattelite')
            elif mapType == QGraphicsGeoMap.SatelliteMapNight:
                radio.setText('Sattelite - Night')
            elif mapType == QGraphicsGeoMap.TerrainMap:
                radio.setText('Terrain')

            if mapType == self.mapWidget.mapType():
                radio.setChecked(True)

            radio.toggled[bool].connect(self.mapTypeToggled)

            self.mapControlButtons.append(radio)
            self.mapControlTypes.append(mapType)
            mapControlLayout.addWidget(radio)

        self.latitudeEdit = QLineEdit()
        self.longitudeEdit = QLineEdit()

        formLayout = QFormLayout()
        formLayout.addRow('Latitude', self.latitudeEdit)
        formLayout.addRow('Longitude', self.longitudeEdit)

        self.captureCoordsButton = QToolButton()
        self.captureCoordsButton.setText('Capture coordinates')
        self.captureCoordsButton.setCheckable(True)

        self.captureCoordsButton.toggled[bool].connect(
                self.mapWidget.setMouseClickCoordQuery)
        self.mapWidget.coordQueryResult.connect(self.updateCoords)

        self.setCoordsButton = QPushButton()
        self.setCoordsButton.setText('Set coordinates')
        self.setCoordsButton.clicked.connect(self.setCoordsClicked)

        buttonLayout = QHBoxLayout()

        buttonLayout.addWidget(self.captureCoordsButton)
        buttonLayout.addWidget(self.setCoordsButton)

        coordControlLayout = QVBoxLayout()
        coordControlLayout.addLayout(formLayout)
        coordControlLayout.addLayout(buttonLayout)

        widget = QWidget(self)
        layout = QGridLayout()
        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, 0)

        topLayout = QGridLayout()
        bottomLayout = QGridLayout()

        topLayout.setColumnStretch(0, 0)
        topLayout.setColumnStretch(1, 1)

        bottomLayout.setColumnStretch(0, 0)
        bottomLayout.setColumnStretch(1, 1)

        topLayout.addWidget(self.slider, 0, 0)
        topLayout.addWidget(self.view, 0, 1)

        bottomLayout.addLayout(mapControlLayout, 0, 0)
        bottomLayout.addLayout(coordControlLayout, 0, 1)

        layout.addLayout(topLayout, 0, 0)
        layout.addLayout(bottomLayout, 1, 0)

        self.layout = layout
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)

        self.view.customContextMenuRequested.connect(self.customContextMenuRequest)
예제 #55
0
파일: zne.py 프로젝트: z25/pyZNodeEditor
class QNEMainWindow(QMainWindow):
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        self.logger = logging.getLogger("zne")
        self.logger.setLevel(logging.DEBUG)

        self.setMinimumSize(560,360)
        self.setWindowTitle("ZOCP Node Editor")
        self.setWindowIcon(QIcon('assets/icon.png'))

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self, self.scene, self.view)

        self.nodesEditor.onAddConnection = self.onAddConnection
        self.nodesEditor.onRemoveConnection = self.onRemoveConnection
        self.nodesEditor.onBlockMoved = self.onBlockMoved

        self.scale = 1
        self.installActions()

        self.initZOCP()

        self.nodes = {}
        self.pendingSubscribers = {}

        QTimer.singleShot(250, lambda: self.scene.invalidate())


    def closeEvent(self, *args):
        self.zocp.stop()


    def installActions(self):
        quitAct = QAction("&Quit", self, shortcut="Ctrl+Q",
            statusTip="Exit the application", triggered=self.close)
        if zconfigmanager_found:
            openAct = QAction("&Open...", self, shortcut="Ctrl+O",
                statusTip="Restore the network from a saved description", triggered=self.readNetwork)
            saveAct = QAction("&Save...", self, shortcut="Ctrl+S",
                statusTip="Write a description of the network to disc", triggered=self.writeNetwork)

        fileMenu = self.menuBar().addMenu("&File")
        if zconfigmanager_found:
            fileMenu.addAction(openAct)
            fileMenu.addAction(saveAct)
            fileMenu.addSeparator()
        fileMenu.addAction(quitAct)

        # for shortcuts
        self.view.addAction(quitAct)

        selectAllAct = QAction("Select &All", self, shortcut="Ctrl+A",
            triggered=self.nodesEditor.selectAll)
        selectNoneAct = QAction("Select &None", self, shortcut="Ctrl+D",
            triggered=self.nodesEditor.selectNone)
        selectInverseAct = QAction("Select &Inverse", self, shortcut="Ctrl+I",
            triggered=self.nodesEditor.selectInverse)
        deleteSelectedAct = QAction("&Delete Selected", self, shortcut="Del",
            triggered=self.nodesEditor.deleteSelected)

        editMenu = self.menuBar().addMenu("&Edit")
        editMenu.addAction(selectAllAct)
        editMenu.addAction(selectNoneAct)
        editMenu.addAction(selectInverseAct)
        editMenu.addSeparator()
        editMenu.addAction(deleteSelectedAct)

        self.view.addAction(selectAllAct)
        self.view.addAction(selectNoneAct)
        self.view.addAction(selectInverseAct)
        self.view.addAction(deleteSelectedAct)

        zoomInAct = QAction("Zoom &In", self, shortcut="Ctrl++",
            triggered=self.zoomIn)
        zoomOutAct = QAction("Zoom &Out", self, shortcut="Ctrl+-",
            triggered=self.zoomOut)
        zoomResetAct = QAction("&Reset Zoom", self, shortcut="Ctrl+0",
            triggered=self.zoomReset)

        viewMenu = self.menuBar().addMenu("&View")
        viewMenu.addAction(zoomInAct)
        viewMenu.addAction(zoomOutAct)
        viewMenu.addSeparator()
        viewMenu.addAction(zoomResetAct)

        self.view.addAction(zoomInAct)
        self.view.addAction(zoomOutAct)
        self.view.addAction(zoomResetAct)

        aboutAct = QAction("&About", self,
             triggered=self.about)

        helpMenu = self.menuBar().addMenu("&Help")
        helpMenu.addAction(aboutAct)

        self.view.addAction(aboutAct)


    def writeNetwork(self):
        fileName, filter = QFileDialog.getSaveFileName(self,
                                                       caption="Save as",
                                                       filter="ZOCP (*.zocp);;JSON (*.json)",
                                                       selectedFilter="ZOCP (*.zocp)")
        if fileName:
            # setup ZOCP node, and run it for some time to discover
            # the current network
            configManager = ZConfigManagerNode("ConfigManager@%s" % socket.gethostname())
            configManager.discover(0.5)

            # write network description to file
            configManager.write(fileName)

            # shut down ZOCP node
            configManager.stop()
            configManager = None


    def readNetwork(self):
        fileName, filter = QFileDialog.getOpenFileName(self,
                                                       caption="Open",
                                                       filter="All files (*.*);;ZOCP (*.zocp);;JSON (*.json)",
                                                       selectedFilter="ZOCP (*.zocp)")
        if fileName:
            # setup ZOCP node, and run it for some time to discover
            # the current network
            configManager = ZConfigManagerNode("ConfigManager@%s" % socket.gethostname())
            configManager.discover(0.5)

            # write network description to file
            configManager.read(fileName)

            # shut down ZOCP node
            configManager.stop()
            configManager = None


    def zoomIn(self):
        if self.scale < 4:
            self.scale *= 1.2
            self.view.scale(1.2, 1.2)


    def zoomOut(self):
        if self.scale > 0.1:
            self.scale /= 1.2
            self.view.scale(1/1.2, 1/1.2)


    def zoomReset(self):
        self.scale = 1
        self.view.setTransform(QTransform())


    def about(self):
        QMessageBox.about(self, "About ZOCP Node Editor",
            "<p>A monitor/editor for ZOCP nodes, implemented in PySide"
             "(Python/Qt4).</p><p>ZOCP is the Z25 Orchestration Control "
             "Protocol, currently in development at "
             "<a href='http://z25.org'>z25.org</a></p>")


    #########################################
    # Node editor callbacks
    #########################################
    def onAddConnection(self, connection, fromPort, toPort):
        fromBlock = fromPort.block()
        toBlock = toPort.block()

        emitter = fromPort.portName()
        emit_peer = fromBlock.uuid()
        receiver = toPort.portName()
        recv_peer = toBlock.uuid()

        self.zocp.signal_subscribe(recv_peer, receiver, emit_peer, emitter)

        self.logger.debug("added subscription from %s on %s to %s on %s" %
               (receiver, fromBlock.name(), emitter, toBlock.name()))


    def onRemoveConnection(self, connection, fromPort, toPort):
        fromBlock = fromPort.block()
        toBlock = toPort.block()

        emitter = fromPort.portName()
        emit_peer = fromBlock.uuid()
        receiver = toPort.portName()
        recv_peer = toBlock.uuid()

        self.zocp.signal_unsubscribe(recv_peer, receiver, emit_peer, emitter)

        self.logger.debug("removed subscription from %s on %s to %s on %s" %
               (receiver, fromBlock.name(), emitter, toBlock.name()))


    def onBlockMoved(self, block):
        pos = block.pos()
        peer = block.uuid()
        self.zocp.peer_set(peer, {"_zne_position": [pos.x(), pos.y()]})


    def onChangeValue(self, block, port, value):
        self.logger.debug("block %s port %s changed to %s" % (block.name(), port.portName(), value))
        peer = block.uuid()
        portName = port.portName()
        capability = self.zocp.peers_capabilities[peer][portName]
        typeHint = capability["typeHint"]
        validValue = True
        if typeHint == "int":
            try:
                value = int(float(value))
            except:
                validValue = False
        elif typeHint == "flt":
            try:
                value = float(value.strip())
            except:
                validValue = False
        elif typeHint == "percent":
            try:
                value = float(value.strip())
            except:
                validValue = False
        elif typeHint == "bool":
            value = (value.strip().lower() in ["true", "yes", "1"])
        elif typeHint == "string":
            pass
        elif typeHint.startswith("vec" ) and typeHint.endswith("f") and len(typeHint) == 5:
            try:
                value = [float(num) for num in ((value.strip())[1:-1]).split(",")]
            except:
                validValue = False

            if validValue:
                if len(value) != int(typeHint[3]):
                    validValue = False

        if validValue:
            self.zocp.peer_set(peer, {portName: {"value": value}})
            port.setValue(str(value))
        else:
            port.setValue(str(capability["value"]))



    #########################################
    # ZOCP implementation
    #########################################
    def initZOCP(self):
        self.zocp = ZOCP("ZOCP Node Editor@%s" % socket.gethostname())
        self.notifier = QSocketNotifier(
            self.zocp.inbox.getsockopt(zmq.FD),
            QSocketNotifier.Read)
        self.notifier.setEnabled(True)
        self.notifier.activated.connect(self.onZOCPEvent)
        self.zocp.on_peer_enter = self.onPeerEnter
        self.zocp.on_peer_exit = self.onPeerExit
        self.zocp.on_peer_modified = self.onPeerModified
        self.zocp.on_peer_signaled = self.onPeerSignaled
        self.zocp.start()

        zl = logging.getLogger("zocp")
        zl.setLevel(logging.INFO)


    def onZOCPEvent(self):
        self.zocp.run_once(0)


    def onPeerEnter(self, peer, name, *args, **kwargs):
        # Subscribe to any and all value changes
        self.zocp.signal_subscribe(self.zocp.uuid(), None, peer, None)

        # Add named block; ports are not known at this point
        block = QNEBlock(None)
        self.scene.addItem(block)
        block.setNodeEditor(self)
        block.setName(name)
        block.setUuid(peer)
        block.addPort(name, False, False, QNEPort.NamePort)
        block.setVisible(False)

        node = {}
        node["block"] = block
        node["ports"] = dict()

        self.nodes[peer.hex] = node


    def onPeerExit(self, peer, name, *args, **kwargs):
        # Unsubscribe from value changes
        self.zocp.signal_unsubscribe(self.zocp.uuid(), None, peer, None)

        # Remove block
        if peer.hex in self.nodes:
            self.nodes[peer.hex]["block"].delete()
            self.nodes.pop(peer.hex)


    def onPeerModified(self, peer, name, data, *args, **kwargs):
        for portname in data:
            portdata = data[portname]

            if portname not in self.nodes[peer.hex]["ports"]:
                if "access" in portdata:
                    hasInput = "s" in portdata["access"]
                    hasOutput = "e" in portdata["access"]
                    port = self.nodes[peer.hex]["block"].addPort(portname, hasInput, hasOutput)
                    port.setValue(str(portdata["value"]))
                    port.setAccess(str(portdata["access"]))
                    self.nodes[peer.hex]["ports"][portname] = port

                else:
                    # Metadata, not a capability
                    if portname == "_zne_position":
                        block = self.nodes[peer.hex]["block"]
                        block.setPos(portdata[0], portdata[1])

            else:
                port = self.nodes[peer.hex]["ports"][portname]
                if "value" in portdata:
                    port.setValue(str(portdata["value"]))
                if "access" in portdata:
                    port.setAccess(str(portdata["access"]))

            if "subscribers" in portdata:
                self.updateSubscribers(port, portdata["subscribers"])

        if len(self.nodes[peer.hex]["ports"]) > 0:
            self.nodes[peer.hex]["block"].setVisible(True)
        self.updatePendingSubscribers(peer)


    def onPeerSignaled(self, peer, name, data, *args, **kwargs):
        [portname, value] = data
        if portname in self.nodes[peer.hex]["ports"]:
            self.nodes[peer.hex]["ports"][portname].setValue(str(value))


    def updateSubscribers(self, port, subscribers):
        port1 = port.outputPort

        # check if any current connections should be removed
        connections = port.connections()
        for connection in connections:
            if(connection.port1() == port1):
                port2 = connection.port2()
            else:
                port2 = connection.port1()

            if not port2.isOutput():
                subscriber = [port2.block().uuid().hex, port2.portName()]
                if subscriber not in subscribers:
                    connection.delete()
                    self.logger.debug("peer removed subscription from %s on %s to %s on %s" %
                        (port1.portName(), port1.block().name(), port2.portName(), port2.block().name()))

        # add new connections for new subscriptions
        for subscriber in subscribers:
            [uuid, portname] = subscriber
            if uuid in self.nodes:
                node = self.nodes[uuid]
                if portname in node["ports"]:
                    port2 = node["ports"][portname]
                    if not port2.isConnected(port1):
                        # create new connection
                        connection = QNEConnection(None)
                        connection.setPort1(port1)
                        connection.setPort2(port2)
                        connection.updatePosFromPorts()
                        connection.updatePath()
                        self.scene.addItem(connection)
                        self.logger.debug("peer added subscription from %s on %s to %s on %s" %
                            (port1.portName(), port1.block().name(), port2.portName(), port2.block().name()))
                    continue

            # if the connection could not be made yet, add it to a list of
            # pending subscriber-connections
            if uuid not in self.pendingSubscribers:
                self.pendingSubscribers[uuid] = []
            self.pendingSubscribers[uuid].append([port1, portname])


    def updatePendingSubscribers(self, peer):
        if peer.hex in self.pendingSubscribers:
            for subscriber in self.pendingSubscribers[peer.hex]:
                [port1, portname] = subscriber
                if peer.hex in self.nodes and portname in self.nodes[peer.hex]["ports"]:
                    port2 = self.nodes[peer.hex]["ports"][portname]

                    connection = QNEConnection(None)
                    connection.setPort1(port1)
                    connection.setPort2(port2)
                    connection.updatePosFromPorts()
                    connection.updatePath()
                    self.scene.addItem(connection)
                else:
                    # TODO: handle case where port is still not available
                    pass

            self.pendingSubscribers.pop(peer.hex)