Example #1
0
    def mouseMoveEvent(self, event):
        """Summary

        Args:
            event (TYPE): Description

        Returns:
            TYPE: Description
        """
        if self._drag_enable is True:

            # map the item to the scene coordinates
            # to help keep coordinates uniform
            rf = self.getR(self.mapFromScene(QPointF(event.scenePos())))
            # for some reason we need to skip the first mouseMoveEvent
            if self._dragged is False:
                self._dragged = True
                self._r0 = rf
            # end if
            else:
                delta = self.selectionbox.delta(rf, self._r0)
                self.translateR(delta)
                # logger.debug('mouse move path selectionbox', delta, rf, self._r0)
            # end else
            self._r = rf
        # end if
        else:
            QGraphicsItemGroup.mouseMoveEvent(self, event)
	def __init__(self, parentItem, segments, colour):
		QGraphicsItem.__init__(self, parent=parentItem)
		self.colour_name = colour
		self.shape = QPainterPath()
		self.labels = QGraphicsItemGroup(self)
		self.bbox = QRectF(0, 0, 0, 0)
		for (p1, p2), label in segments:
			lvect = QVector2D(p2 - p1)
			lpath = QPainterPath()
			m = TWY_line_margin
			l = lvect.length()
			plst = [QPointF(-m, 0), QPointF(-m/3, -m), QPointF(l + m/3, -m), QPointF(l + m, 0), QPointF(l + m/3, m), QPointF(-m/3, m)]
			lpath.addPolygon(QPolygonF(plst))
			lrot = QTransform()
			lrot.rotateRadians(atan2(lvect.y(), lvect.x()))
			lpath = lrot.map(lpath)
			lpath.translate(p1)
			self.shape.addPath(lpath)
			rect = QRectF(p1, p2).normalized()
			if label != None:
				self.labels.addToGroup(TaxiwayLabelItem(label, rect.center(), self))
			self.bbox |= rect
		self.shape.setFillRule(Qt.WindingFill)
		self.mouse_highlight = False
		self.labels.setVisible(False)
Example #3
0
class Tank(GameObject):
    FIRE_CD = 1.0
    MAX_MOVE_SPEED = UNIT * 2
    MAX_CANNON_ROTATION_SPEED = math.pi / 1.0
    MAX_BODY_ROTATION_SPEED = math.pi / 4.0
    MISSILE_SPEED = 2.5 * UNIT

    def __init__(self, color, group):
        super(Tank, self).__init__()
        self.graphics = QGraphicsItemGroup()
        self.body_graphics = TankGraphics(color)
        self.graphics.addToGroup(self.body_graphics)
        self.cannon_graphics = CannonGraphics(color)
        self.graphics.addToGroup(self.cannon_graphics)

        self.cannon_rotation = 0
        self.cannon_rotate_speed = 0
        self.group = group
        self.hp = 50

        self.fire_cd = 0

    def start(self):
        pass

    def update_logic(self):
        super(Tank, self).update_logic()
        self.cannon_rotation += self.cannon_rotate_speed * self.arena.dt
        self.fire_cd -= self.arena.dt

    def update_graphics(self):
        super(Tank, self).update_graphics()
        a = math.degrees(self.cannon_rotation)
        self.cannon_graphics.setRotation(a)

    def get_world_aiming(self):
        return self.rotation + self.cannon_rotation

    def adjust_aim_clockwise(self, w):
        self.cannon_rotate_speed = w

    def open_fire(self):
        if self.fire_cd <= 0:
            self.fire_cd = self.FIRE_CD
            orient = self.get_world_aiming()
            dv = QPointF(math.cos(orient), math.sin(orient)) * 0.6 * UNIT
            pos = self.position + dv
            m = Missile(pos, orient, self.MISSILE_SPEED)
            self.arena.add(m)
            return True
        else:
            return False

    def update(self):
        super(Tank, self).update()

    def take_damage(self, dmg):
        self.hp -= dmg
        if self.hp <= 0:
            self.cleanup()
Example #4
0
 def makeCoords(self):
     """ draws Coordinates """
     xLabels = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
     yLabels = list(range(1, 26))
     botGrid = []
     leftGrid = []
     # generate pixel coordinates grids
     for n in range(self.board.size):
         (xBot, yBot) = self.grid[self.board.size - 1][n]
         yBot += self.baseWidth * 0.4 / self.baseRectRatio
         xBot -= self.baseWidth * 0.1
         botGrid.append((xBot, yBot))
         (xLeft, yLeft) = self.grid[n][0]
         xLeft -= self.baseWidth * 1.2
         yLeft -= self.baseWidth * 0.3 / self.baseRectRatio
         leftGrid.append((xLeft, yLeft))
     # generate Text items and add them to group
     self.coordGroup = QGraphicsItemGroup()
     for n in range(self.board.size):
         leftText = QGraphicsSimpleTextItem(str(yLabels[n]))
         leftText.setPos(*leftGrid[n])
         self.coordGroup.addToGroup(leftText)
         bottomText = QGraphicsSimpleTextItem(xLabels[n])
         bottomText.setPos(*botGrid[n])
         self.coordGroup.addToGroup(bottomText)
     # draw coordinates and update visibility according to self.showCoords
     self.scene.addItem(self.coordGroup)
     self.updateCoords()
Example #5
0
class Tank(GameObject):
    FIRE_CD = 1.0
    MAX_MOVE_SPEED = UNIT * 2
    MAX_CANNON_ROTATION_SPEED = math.pi / 1.0
    MAX_BODY_ROTATION_SPEED = math.pi / 4.0
    MISSILE_SPEED = 2.5 * UNIT

    def __init__(self, color, group):
        super(Tank, self).__init__()
        self.graphics = QGraphicsItemGroup()
        self.body_graphics = TankGraphics(color)
        self.graphics.addToGroup(self.body_graphics)
        self.cannon_graphics = CannonGraphics(color)
        self.graphics.addToGroup(self.cannon_graphics)

        self.cannon_rotation = 0
        self.cannon_rotate_speed = 0
        self.group = group
        self.hp = 50

        self.fire_cd = 0

    def start(self):
        pass

    def update_logic(self):
        super(Tank, self).update_logic()
        self.cannon_rotation += self.cannon_rotate_speed * self.arena.dt
        self.fire_cd -= self.arena.dt

    def update_graphics(self):
        super(Tank, self).update_graphics()
        a = math.degrees(self.cannon_rotation)
        self.cannon_graphics.setRotation(a)

    def get_world_aiming(self):
        return self.rotation + self.cannon_rotation

    def adjust_aim_clockwise(self, w):
        self.cannon_rotate_speed = w

    def open_fire(self):
        if self.fire_cd <= 0:
            self.fire_cd = self.FIRE_CD
            orient = self.get_world_aiming()
            dv = QPointF(math.cos(orient), math.sin(orient)) * 0.6 * UNIT
            pos = self.position + dv
            m = Missile(pos, orient, self.MISSILE_SPEED)
            self.arena.add(m)
            return True
        else:
            return False

    def update(self):
        super(Tank, self).update()

    def take_damage(self, dmg):
        self.hp -= dmg
        if self.hp <= 0:
            self.cleanup()
Example #6
0
    def mousePressEvent(self, event):
        # self.show()
        if event.button() != Qt.LeftButton:
            return QGraphicsItemGroup.mousePressEvent(self, event)
        else:
            self._drag_enable = True

            # required to get the itemChanged event to work
            # correctly for this
            self.setSelected(True)

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.refreshPath()

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.show()

            # for some reason we need to skip the first mouseMoveEvent
            self._dragged = False

            if self._added_to_press_list == False:
                self._added_to_press_list = True
                self.scene().views()[0].addToPressList(self)
            return QGraphicsItemGroup.mousePressEvent(self, event)
Example #7
0
    def visualize(self):
        """
        called when user clicks draw lsystem. This visualizes the lsystem to allow setup
        before the actual lsystification takes place
        """
        self.getdata()
        self.run_lsystem()

        old_group = self.layersModel.itemFromIndex(
            self.parent.layersList.currentIndex()).get_graphics_items_group()
        if old_group:
            self.parent.scene.removeItem(old_group)

        group = QGraphicsItemGroup()
        path = QPainterPath()
        for idx, point in enumerate(
                self.lsysteminterpreter.globalstate["pts"]):
            x = point[0][0][0]
            y = point[0][1][0]
            direction = point[1]
            x = x * self.xscale + self.xoffs
            y = y * self.yscale + self.yoffs
            if idx == 0:
                path.moveTo(x, y)
            else:
                path.lineTo(x, y)
        item = QGraphicsPathItem(path)
        pen = QPen()
        pen.setWidth(self.strokeWidth)
        item.setPen(pen)
        group.addToGroup(item)
        self.addNewGraphicsItems(group)
Example #8
0
    def mouseMoveEvent(self, event):
        """Summary

        Args:
            event (TYPE): Description

        Returns:
            TYPE: Description
        """
        if self._drag_enable is True:

            # map the item to the scene coordinates
            # to help keep coordinates uniform
            rf = self.getR(self.mapFromScene(QPointF(event.scenePos())))
            # for some reason we need to skip the first mouseMoveEvent
            if self._dragged is False:
                self._dragged = True
                self._r0 = rf
            # end if
            else:
                delta = self.selectionbox.delta(rf, self._r0)
                self.translateR(delta)
                # print("mouse move path selectionbox", delta, rf, self._r0)
            # end else
            self._r = rf
        # end if
        else:
            QGraphicsItemGroup.mouseMoveEvent(self, event)
Example #9
0
    def __init__(self, qPointList, bot, rType):  #

        QGraphicsItemGroup.__init__(self)
        self.rType = rType

        #射线类型雷达
        if rType == "poly":
            self.item = QGraphicsPolygonItem()  #提供一个多边形item
            self.polygon = QPolygonF(qPointList)
            self.item.setPolygon(self.polygon)
            self.robot = bot

        #范围类型雷达
        elif rType == "round":
            self.item = QGraphicsEllipseItem()  #提供一个椭圆item
            self.item.setRect(qPointList[0], qPointList[1], qPointList[2],
                              qPointList[3])
            self.robot = bot

        color = QColor(255, 100, 6, 10)  #设置雷达的颜色,
        brush = QBrush(color)
        pen = QPen(color)
        self.item.setBrush(brush)
        self.item.setPen(pen)
        self.addToGroup(self.item)
Example #10
0
    def mousePressEvent(self, event):
        """Handler for user mouse press.

        Args:
            event (QGraphicsSceneMouseEvent): Contains item, scene, and screen
            coordinates of the the event, and previous event.

        Returns:
            TYPE: Description
        """
        # self.show()
        if event.button() != Qt.LeftButton:
            return QGraphicsItemGroup.mousePressEvent(self, event)
        else:
            self._drag_enable = True

            # required to get the itemChanged event to work
            # correctly for this
            self.setSelected(True)

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.refreshPath()

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.show()

            # for some reason we need to skip the first mouseMoveEvent
            self._dragged = False

            if self._added_to_press_list is False:
                self._added_to_press_list = True
                self.scene().views()[0].addToPressList(self)
            return QGraphicsItemGroup.mousePressEvent(self, event)
Example #11
0
    def mouseMoveEvent(self, event, image_item):
        if self._aiming:
            if self._helpLines is not None and self._helpLines.scene(
            ) is not None:
                self._scene.removeItem(self._helpLines)

            self._helpLines = QGraphicsItemGroup()
            group = self._helpLines

            verticalHelpLine = QGraphicsLineItem(event.scenePos().x(), 0,
                                                 event.scenePos().x(),
                                                 self._scene.height())
            horizontalHelpLine = QGraphicsLineItem(0,
                                                   event.scenePos().y(),
                                                   self._scene.width(),
                                                   event.scenePos().y())

            horizontalHelpLine.setPen(self._helpLinesPen)
            verticalHelpLine.setPen(self._helpLinesPen)

            group.addToGroup(verticalHelpLine)
            group.addToGroup(horizontalHelpLine)

            self._scene.addItem(self._helpLines)
        else:
            if self._item is not None:
                assert self._init_pos is not None
                rect = QRectF(self._init_pos, event.scenePos()).normalized()
                self._item.setRect(rect)

        event.accept()
Example #12
0
    def imgInit(self):
        self.cv_img = cv2.imread(
            os.path.join(sampleDataPath, "color_filter_test.png"))

        self.frameBuffer = Queue()
        self.frameBufferItemGroup = QGraphicsItemGroup()
        self.frameBufferItemGroup.hide()
        self.inputPixmapRenderScene = QGraphicsScene()
        self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup)

        self.inputScene = QGraphicsScene()
        self.inputGraphicsView.setScene(self.inputScene)
        self.inputGraphicsView.resizeEvent = self.graphicsViewResized
        # self.inputScene.addItem(self.frameBufferItemGroup)

        qimg = misc.cvMatToQImage(self.cv_img)
        self.inputPixmap = QPixmap.fromImage(qimg)
        self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
        self.inputScene.addItem(self.inputPixmapItem)

        self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent
        self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent
        self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent
        self.inputGraphicsView.keyPressEvent = self.inputGraphicsViewKeyPressEvent
        self.inputGraphicsView.keyReleaseEvent = self.inputGraphicsViewKeyReleaseEvent
        self.inputGraphicsView.wheelEvent = self.inputGraphicsViewwheelEvent
        #self.inputGraphicsView.focusInEvent = self.inputGraphicsViewfocusInEvent
        self.inputGraphicsView.viewport().installEventFilter(self)

        self.inputGraphicsView.setMouseTracking(True)
        self.overlayScene = QGraphicsScene()
        self.inputGraphicsView.setOverlayScene(self.overlayScene)
Example #13
0
    def mousePressEvent(self, event):
        # self.show()
        if event.button() != Qt.LeftButton:
            return QGraphicsItemGroup.mousePressEvent(self, event)
        else:
            self._drag_enable = True

            # required to get the itemChanged event to work
            # correctly for this
            self.setSelected(True)

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.refreshPath()

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.show()

            # for some reason we need to skip the first mouseMoveEvent
            self._dragged = False

            if self._added_to_press_list == False:
                self._added_to_press_list = True
                self.scene().views()[0].addToPressList(self)
            return QGraphicsItemGroup.mousePressEvent(self, event)
Example #14
0
    def mousePressEvent(self, event):
        """Handler for user mouse press.

        Args:
            event (QGraphicsSceneMouseEvent): Contains item, scene, and screen
            coordinates of the the event, and previous event.

        Returns:
            TYPE: Description
        """
        # self.show()
        if event.button() != Qt.LeftButton:
            return QGraphicsItemGroup.mousePressEvent(self, event)
        else:
            self._drag_enable = True

            # required to get the itemChanged event to work
            # correctly for this
            self.setSelected(True)

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.refreshPath()

            # self.selectionbox.resetTransform()
            self.selectionbox.resetPosition()
            self.selectionbox.show()

            # for some reason we need to skip the first mouseMoveEvent
            self._dragged = False

            if self._added_to_press_list is False:
                self._added_to_press_list = True
                self.scene().views()[0].addToPressList(self)
            return QGraphicsItemGroup.mousePressEvent(self, event)
Example #15
0
class ReviewView(QGraphicsView):
    """Simple extension of QGraphicsView
    - containing an image and click-to-zoom/unzoom
    """
    def __init__(self, fnames):
        QGraphicsView.__init__(self)
        self.initUI(fnames)

    def initUI(self, fnames):
        # Make QGraphicsScene
        self.scene = QGraphicsScene()
        # TODO = handle different image sizes.
        self.images = {}
        self.imageGItem = QGraphicsItemGroup()
        self.scene.addItem(self.imageGItem)
        self.updateImage(fnames)
        self.setBackgroundBrush(QBrush(Qt.darkCyan))

    def updateImage(self, fnames):
        """Update the image with that from filename"""
        for n in self.images:
            self.imageGItem.removeFromGroup(self.images[n])
            self.images[n].setVisible(False)
        if fnames is not None:
            x = 0
            n = 0
            for fn in fnames:
                self.images[n] = QGraphicsPixmapItem(QPixmap(fn))
                self.images[n].setTransformationMode(Qt.SmoothTransformation)
                self.images[n].setPos(x, 0)
                self.images[n].setVisible(True)
                self.scene.addItem(self.images[n])
                x += self.images[n].boundingRect().width() + 10
                self.imageGItem.addToGroup(self.images[n])
                n += 1

        # Set sensible sizes and put into the view, and fit view to the image.
        br = self.imageGItem.boundingRect()
        self.scene.setSceneRect(
            0,
            0,
            max(1000, br.width()),
            max(1000, br.height()),
        )
        self.setScene(self.scene)
        self.fitInView(self.imageGItem, Qt.KeepAspectRatio)

    def mouseReleaseEvent(self, event):
        """Left/right click to zoom in and out"""
        if (event.button() == Qt.RightButton) or (
                QGuiApplication.queryKeyboardModifiers() == Qt.ShiftModifier):
            self.scale(0.8, 0.8)
        else:
            self.scale(1.25, 1.25)
        self.centerOn(event.pos())

    def resetView(self):
        """Reset the view to its reasonable initial state."""
        self.fitInView(self.imageGItem, Qt.KeepAspectRatio)
    def __init__(self):
        QDialog.__init__(self)
    
        self.__mapWidgetUi = Ui_MapWidget()
        self.__mapWidgetUi.setupUi(self)
        
        self.__view = self.__mapWidgetUi.graphicsView
        self.__view.setObjectName("ACS_Map_View")
        self.__scene = QGraphicsScene()
                
        self.__view.setScene(self.__scene)

        self.__current_lat = 35.720428
        self.__current_lon = -120.769924
        self.__current_ground_width = 41000000. #meters(start w/ view of whole earth)
        #TODO: don't hard code location
        self.__tiler = acs_map_tiler.ACS_MapTiler(35.720428, -120.769924)

        self.__current_detail_layer = 0 #corresponds to "zoom" in map_tiler module
        self.__detail_layers = []
        self.__rect_tiles = OrderedDict() #see rectKey method for how key works

        #detail layers are various levels of raster detail for the map.
        #0 is lowest level of detail, 20 highest.  0 loads fast and the 
        #entire world can fit on a single tile.  20 loads slow, and it is unwise
        #to try to show the entire world due to the number of tiles required 
        #(higher numbered detail layers are intended for "zooming in")
        self.setupDetailLayers()

        self.__plane_layer = QGraphicsItemGroup()
        self.__scene.addItem(self.__plane_layer)
        self.__plane_icons = {}
        self.__plane_labels = {}
        self.__plane_icon_pixmaps = {}
        img_bytes = pkg_resources.resource_stream("acs_dashboards", "data/images/flyingWingTiny.png").read()
        self.__plane_icon_pixmaps[0] = QPixmap()
        self.__plane_icon_pixmaps[0].loadFromData(img_bytes)
        img_bytes2 = pkg_resources.resource_stream("acs_dashboards", "data/images/flyingWingTiny2.png").read()
        self.__plane_icon_pixmaps[1] = QPixmap()
        self.__plane_icon_pixmaps[1].loadFromData(img_bytes2)

        #for drawing waypoints:
        self.__mission_layer = QGraphicsItemGroup()
        self.__scene.addItem(self.__mission_layer)
        self.__wp_diameter = 0.0001
        self.__prev_drawn_nav_wp = None  #needed when drawing lines between wps
        self.__wp_loiter_radius = None #NOTE: this is in meters; the map itself
                                       #is in degrees

        #for drawing fence:
        self.__fence_layer = QGraphicsItemGroup()
        self.__scene.addItem(self.__fence_layer)

        #slots
        self.__view.just_zoomed.connect(self.onZoom)
        self.__mapWidgetUi.zoom_sb.valueChanged.connect(self.onZoomSBValueChanged)
        self.__view.just_panned.connect(self.onPan)
Example #17
0
 def initUI(self, fnames):
     # Make QGraphicsScene
     self.scene = QGraphicsScene()
     # TODO = handle different image sizes.
     self.images = {}
     self.imageGItem = QGraphicsItemGroup()
     self.scene.addItem(self.imageGItem)
     self.updateImage(fnames)
     self.setBackgroundBrush(QBrush(Qt.darkCyan))
Example #18
0
    def mousePressEvent(self, event):
        """Handler for user mouse press.

        Args:
            event (QGraphicsSceneMouseEvent): Contains item, scene, and screen
            coordinates of the the event, and previous event.

        Returns:
            TYPE: Description
        """
        tool = self.tool
        if event.button() != Qt.LeftButton:
            """ do context menu?
            """
            # slice_graphics_view = self.tool.slice_graphics_view
            # print(slice_graphics_view)
            # self.getCustomContextMenu(event.screenPos())
            tool.individual_pick = False
            return QGraphicsItemGroup.mousePressEvent(self, event)
        else:
            # print("the right event")
            modifiers = event.modifiers()
            is_shift = modifiers == Qt.ShiftModifier
            print("Is_shift is %s" % is_shift)
            # check to see if we are clicking on a previously selected item
            if tool.is_selection_active:
                # print("clicking the box")
                pos = event.scenePos()
                for item in tool.sgv.scene().items(pos):
                    if isinstance(item, GridVirtualHelixItem):
                        doc = tool.manager.document
                        part = item.part()
                        if is_shift:
                            id_num = item.idNum()
                            if doc.isVirtualHelixSelected(
                                    part,
                                    id_num):  # maybe should ask the model?
                                doc.removeVirtualHelicesFromSelection(
                                    part, [id_num])
                        else:
                            origin_id_num = item.idNum()
                            is_alt = modifiers == Qt.AltModifier
                            if (doc.isVirtualHelixSelected(
                                    part, origin_id_num) and not is_alt):
                                print("origin", origin_id_num)
                                if tool.snap_origin_item is not None:
                                    tool.snap_origin_item.setSnapOrigin(False)
                                tool.snap_origin_item = item
                                item.setSnapOrigin(True)
                                break
                            else:
                                item.mousePressEvent(event)
            self.drag_start_position = sp = self.pos()
            self.drag_last_position = sp

            return QGraphicsItemGroup.mousePressEvent(self, event)
 def __init__(self, levels: List[int], parent=None):
     super().__init__(parent)
     self.levels = levels
     self.level_group = {}
     for level in levels:
         group = QGraphicsItemGroup(self)
         group.setVisible(False)
         self.level_group[level] = group
     self.visible_level = None
     self.setAcceptedMouseButtons(Qt.NoButton)
     self.setAcceptHoverEvents(False)
Example #20
0
 def __init__(self, parent=None):
     QGraphicsItemGroup.__init__(self)
     self.setFlags(QGraphicsItem.ItemIsSelectable)
     self.parent = parent
     TreeItem.scene.addItem(self)
     self.aItem = None
     self.lineCache = []
     self.children = []
     # cached draw params
     self.x = 0
     self.y = 0
     self.nextDown = False
Example #21
0
def build_tiles_level(level, tile_size, slide_helper: SlideHelper):
    level_size = slide_helper.get_level_size(level)
    tiles_rects = slice_rect(level_size, tile_size)
    tiles_graphics_group = QGraphicsItemGroup()
    downsample = slide_helper.get_downsample_for_level(level)
    for tile_rect in tiles_rects:
        item = TileGraphicsItem(tile_rect, slide_helper.slide_path, level,
                                downsample)
        item.moveBy(tile_rect[0], tile_rect[1])
        tiles_graphics_group.addToGroup(item)

    return tiles_graphics_group
Example #22
0
 def keyPressEvent(self, event):
     """
     Must intercept invalid input events.  Make changes here
     """
     key = event.key()
     if key in [Qt.Key_Backspace, Qt.Key_Delete]:
         self.selectionbox.deleteSelection()
         # self.document().deleteSelection()
         self.clearSelection(False)
         return QGraphicsItemGroup.keyPressEvent(self, event)
     else:
         return QGraphicsItemGroup.keyPressEvent(self, event)
Example #23
0
 def keyPressEvent(self, event):
     """
     Must intercept invalid input events.  Make changes here
     """
     key = event.key()
     if key in [Qt.Key_Backspace, Qt.Key_Delete]:
         self.selectionbox.deleteSelection()
         # self.document().deleteSelection()
         self.clearSelection(False)
         return QGraphicsItemGroup.keyPressEvent(self, event)
     else:
         return QGraphicsItemGroup.keyPressEvent(self, event)
class TaxiRouteItem(QGraphicsItem):
	'''
	Draws a set of edges that turn on/off together, each possibly labelled.
	Call prepareGeometryChange after building to initialise correctly.
	'''
	def __init__(self, parentItem, segments, colour):
		QGraphicsItem.__init__(self, parent=parentItem)
		self.colour_name = colour
		self.shape = QPainterPath()
		self.labels = QGraphicsItemGroup(self)
		self.bbox = QRectF(0, 0, 0, 0)
		for (p1, p2), label in segments:
			lvect = QVector2D(p2 - p1)
			lpath = QPainterPath()
			m = TWY_line_margin
			l = lvect.length()
			plst = [QPointF(-m, 0), QPointF(-m/3, -m), QPointF(l + m/3, -m), QPointF(l + m, 0), QPointF(l + m/3, m), QPointF(-m/3, m)]
			lpath.addPolygon(QPolygonF(plst))
			lrot = QTransform()
			lrot.rotateRadians(atan2(lvect.y(), lvect.x()))
			lpath = lrot.map(lpath)
			lpath.translate(p1)
			self.shape.addPath(lpath)
			rect = QRectF(p1, p2).normalized()
			if label != None:
				self.labels.addToGroup(TaxiwayLabelItem(label, rect.center(), self))
			self.bbox |= rect
		self.shape.setFillRule(Qt.WindingFill)
		self.mouse_highlight = False
		self.labels.setVisible(False)
	
	def hoverEnterEvent(self, event):
		self.mouse_highlight = self.scene().mouseover_highlights_groundnet_edges
		if self.mouse_highlight and not self.labels.isVisible():
			self.labels.setVisible(True)
		self.setVisible(False)
		self.setVisible(True)
	
	def hoverLeaveEvent(self, event):
		self.mouse_highlight = False
		self.labels.setVisible(self.scene().show_taxiway_names)
		self.setVisible(False)
		self.setVisible(True)
	
	def boundingRect(self):
		return withMargins(self.bbox, TWY_line_margin)
	
	def shape(self):
		return self.shape

	def paint(self, painter, option, widget):
		if self.mouse_highlight or self.scene().show_ground_networks:
			painter.setPen(QPen(Qt.NoPen))
			brushcol = settings.colour(self.colour_name)
			brushcol.setAlpha(96 if self.mouse_highlight else 64)
			painter.setBrush(QBrush(brushcol))
			painter.drawPath(self.shape)
Example #25
0
    def mousePressEvent(self, event):
        """Handler for user mouse press.

        Args:
            event (QGraphicsSceneMouseEvent): Contains item, scene, and screen
            coordinates of the the event, and previous event.

        Returns:
            TYPE: Description
        """
        tool = self.tool
        if event.button() != Qt.LeftButton:
            """ do context menu?
            """
            # sgv = self.tool.sgv
            # print(sgv)
            # self.getCustomContextMenu(event.screenPos())
            tool.individual_pick = False
            return QGraphicsItemGroup.mousePressEvent(self, event)
        else:
            # print("the right event")
            modifiers = event.modifiers()
            is_shift = modifiers == Qt.ShiftModifier
            # check to see if we are clicking on a previously selected item
            if tool.is_selection_active:
                # print("clicking the box")
                pos = event.scenePos()
                for item in tool.sgv.scene().items(pos):
                    if isinstance(item, SliceVirtualHelixItem):
                        doc = tool.manager.document
                        part = item.part()
                        if is_shift:
                            id_num = item.idNum()
                            if doc.isVirtualHelixSelected(part, id_num):    # maybe should ask the model?
                                doc.removeVirtualHelicesFromSelection(part, [id_num])
                        else:
                            origin_id_num = item.idNum()
                            is_alt = modifiers == Qt.AltModifier
                            if (    doc.isVirtualHelixSelected(part, origin_id_num) and
                                    not is_alt):
                                print("origin", origin_id_num)
                                if tool.snap_origin_item is not None:
                                    tool.snap_origin_item.setSnapOrigin(False)
                                tool.snap_origin_item = item
                                item.setSnapOrigin(True)
                                break
                            else:
                                item.mousePressEvent(event)
            self.drag_start_position = sp = self.pos()
            self.drag_last_position = sp

            return QGraphicsItemGroup.mousePressEvent(self, event)
Example #26
0
 def initUI(self, fnames):
     # set background
     self.setStyleSheet("background: transparent")
     self.setBackgroundBrush(BackGrid())
     self.setRenderHint(QPainter.Antialiasing, True)
     self.setRenderHint(QPainter.SmoothPixmapTransform, True)
     # Make QGraphicsScene
     self.scene = QGraphicsScene()
     # TODO = handle different image sizes.
     self.images = {}
     self.imageGItem = QGraphicsItemGroup()
     self.scene.addItem(self.imageGItem)
     self.updateImage(fnames)
Example #27
0
 def __init__(self, minBrightness, maxBrightness, minRadius, maxRadius,
              minStepSize, maxStepSize, clipToBitmap, strokeWidth,
              imageWidth, imageHeight):
     self.group = QGraphicsItemGroup()
     self.minBrightness = minBrightness
     self.maxBrightness = maxBrightness
     self.minRadius = minRadius
     self.maxRadius = maxRadius
     self.minStepSize = minStepSize
     self.maxStepSize = maxStepSize
     self.clipToBitmap = clipToBitmap
     self.strokeWidth = strokeWidth
     self.width = imageWidth
     self.height = imageHeight
Example #28
0
    def __init__(self, color, group):
        super(Tank, self).__init__()
        self.graphics = QGraphicsItemGroup()
        self.body_graphics = TankGraphics(color)
        self.graphics.addToGroup(self.body_graphics)
        self.cannon_graphics = CannonGraphics(color)
        self.graphics.addToGroup(self.cannon_graphics)

        self.cannon_rotation = 0
        self.cannon_rotate_speed = 0
        self.group = group
        self.hp = 50

        self.fire_cd = 0
    def make_cursor(self):
        pen = QPen(QColor(0, 255, 0))
        h_line = QGraphicsLineItem(-10, 0, 10, 0)
        v_line = QGraphicsLineItem(0, -10, 0, 10)

        pen.setWidth(1)
        h_line.setPen(pen)
        v_line.setPen(pen)

        self.point_cursor = QGraphicsItemGroup()
        self.point_cursor.addToGroup(h_line)
        self.point_cursor.addToGroup(v_line)
        self.point_cursor.setZValue(1)
        self.point_cursor.setVisible(False)
        self.scene().addItem(self.point_cursor)
Example #30
0
 def addToGroup(self, item, name):
     '''
     Määrittää saman ryhmänimen omaaville yhteisen ryhmän ja palauttaa sen
     '''
     if name.strip() == 'None':
         return None
     elif name not in self.groups:
         group = QGraphicsItemGroup()
         self.piirtoalusta.scene.addItem(group)
         group.setFlag(QGraphicsItem.ItemIsSelectable)
         group.setFlag(QGraphicsItem.ItemIsMovable)
         group.addToGroup(item)
         self.groups.update({name: group})
     else:
         group = self.groups[name]
         group.addToGroup(item)
Example #31
0
    def itemChange(self, change, value):
        """docstring for itemChange

        Arguments:
            change (GraphicsItemChange): see http://doc.qt.io/qt-5/qgraphicsitem.html#GraphicsItemChange-enum
            value (QVariant): resolves in Python as an integer
        """
        # print("ps itemChange")
        if change == QGraphicsItem.ItemSelectedChange:
            # print("isc", value)
            if value == False:  # noqa
                self.clearSelection(False)
                return False
            else:
                return True
        elif change == QGraphicsItem.ItemChildAddedChange:
            # print("icac")
            if self._added_to_press_list is False:
                # print("kid added")
                self.setFocus()  # this is to get delete keyPressEvents
                self.selectionbox.boxParent()
                # self.setParentItem(self.selectionbox.boxParent())
                self._added_to_press_list = True
                self.scene().views()[0].addToPressList(self)
            return
        return QGraphicsItemGroup.itemChange(self, change, value)
Example #32
0
    def itemChange(self, change, value):
        """docstring for itemChange

        Arguments:
            change (GraphicsItemChange): see http://doc.qt.io/qt-5/qgraphicsitem.html#GraphicsItemChange-enum
            value (QVariant): resolves in Python as an integer
        """
        # logger.debug("ps itemChange")
        if change == QGraphicsItem.ItemSelectedChange:
            # logger.debug("isc", value)
            if value == False:  # noqa
                self.clearSelection(False)
                return False
            else:
                return True
        elif change == QGraphicsItem.ItemChildAddedChange:
            # logger.debug("icac")
            if self._added_to_press_list is False:
                # logger.debug("kid added")
                self.setFocus()  # this is to get delete keyPressEvents
                self.selectionbox.boxParent()
                # self.setParentItem(self.selectionbox.boxParent())
                self._added_to_press_list = True
                self.scene().views()[0].addToPressList(self)
            return
        return QGraphicsItemGroup.itemChange(self, change, value)
Example #33
0
 def makeCoords(self):
     """ draws Coordinates """
     xLabels = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
     yLabels = list(range(1, 26))
     botGrid = []
     leftGrid = []
     # generate pixel coordinates grids
     for n in range(self.board.size):
         (xBot, yBot) = self.grid[self.board.size-1][n]
         yBot += self.baseWidth*0.4/self.baseRectRatio
         xBot -= self.baseWidth*0.1
         botGrid.append((xBot, yBot))
         (xLeft, yLeft) = self.grid[n][0]
         xLeft -= self.baseWidth*1.2
         yLeft -= self.baseWidth*0.3/self.baseRectRatio
         leftGrid.append((xLeft, yLeft))
     # generate Text items and add them to group
     self.coordGroup = QGraphicsItemGroup()
     for n in range(self.board.size):
         leftText = QGraphicsSimpleTextItem(str(yLabels[n]))
         leftText.setPos(*leftGrid[n])
         self.coordGroup.addToGroup(leftText)
         bottomText = QGraphicsSimpleTextItem(xLabels[n])
         bottomText.setPos(*botGrid[n])
         self.coordGroup.addToGroup(bottomText)
     # draw coordinates and update visibility according to self.showCoords
     self.scene.addItem(self.coordGroup)
     self.updateCoords()
    def imgInit(self):
        self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png"))


        self.frameBuffer = Queue()
        self.frameBufferItemGroup = QGraphicsItemGroup()
        self.frameBufferItemGroup.hide()
        self.inputPixmapRenderScene = QGraphicsScene()
        self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup)

        self.inputScene = QGraphicsScene()
        self.inputGraphicsView.setScene(self.inputScene)
        self.inputGraphicsView.resizeEvent = self.graphicsViewResized
        # self.inputScene.addItem(self.frameBufferItemGroup)

        qimg = misc.cvMatToQImage(self.cv_img)
        self.inputPixmap = QPixmap.fromImage(qimg)
        self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
        self.inputScene.addItem(self.inputPixmapItem)

        self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self.inputGraphicsView)
        self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent
        self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent
        self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent

        self.inputGraphicsView.viewport().installEventFilter(self)

        self.inputGraphicsView.setMouseTracking(True)
        self.overlayScene = QGraphicsScene()
        self.inputGraphicsView.setOverlayScene(self.overlayScene)

        self.zoomedGraphicsView.setScene(self.inputScene)
        self.zoomedGraphicsView.setOverlayScene(self.overlayScene)
Example #35
0
    def __loadGraphicItem(self,
                          shapes,
                          images,
                          condition_variables=None,
                          default_color=Qt.blue):

        if not images:
            return ObjectGraphicsItem(shapes, color=default_color)

        gitem = QGraphicsItemGroup()

        for image in images:
            gitem.addToGroup(
                self.__loadGraphicItemImagePart(image, condition_variables))

        return gitem
    def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
        """Handler for user mouse press.

        Args:
            event: Contains item, scene, and screen
            coordinates of the the event, and previous event.
        """
        return QGraphicsItemGroup.mousePressEvent(self, event)
Example #37
0
    def initUI(self, fnames):
        # Make QGraphicsScene
        self.scene = QGraphicsScene()
        # TODO = handle different image sizes.
        self.images = {}
        self.imageGItem = QGraphicsItemGroup()
        self.scene.addItem(self.imageGItem)
        self.updateImage(fnames)
        self.setBackgroundBrush(QBrush(Qt.darkCyan))
        self.parent.tool = "zoom"

        self.boxFlag = False
        self.originPos = QPointF(0, 0)
        self.currentPos = self.originPos
        self.boxItem = QGraphicsRectItem()
        self.boxItem.setPen(QPen(Qt.darkCyan, 1))
        self.boxItem.setBrush(QBrush(QColor(0, 255, 0, 64)))
Example #38
0
    def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
        """Handler for user mouse press.

        Args:
            event: Contains item, scene, and screen
            coordinates of the the event, and previous event.
        """
        return QGraphicsItemGroup.mousePressEvent(self, event)
Example #39
0
 def __init__(self, minBrightness, maxBrightness, strength, detail,
              minStepSize, maxStepSize, clipToBitmap, strokeWidth,
              imageWidth, imageHeight):
     self.group = QGraphicsItemGroup()
     self.path = QPainterPath()
     self.minBrightness = minBrightness
     self.maxBrightness = maxBrightness
     self.strength = strength
     self.detail = detail
     self.minStepSize = minStepSize
     self.maxStepSize = maxStepSize
     self.clipToBitmap = clipToBitmap
     self.strokeWidth = strokeWidth
     self.width = imageWidth
     self.height = imageHeight
     self.prevPos = None
     self.disturbance_direction = 1
     self.previous_stepsize = 1
Example #40
0
 def mouseMoveEvent(self, event):
     if self._drag_enable == True:
         # map the item to the scene coordinates
         # to help keep coordinates uniform
         rf = self.getR(self.mapFromScene(QPointF(event.scenePos())))
         # for some reason we need to skip the first mouseMoveEvent
         if self._dragged == False:
             self._dragged = True
             self._r0 = rf
         # end if
         else:
             delta = self.selectionbox.delta(rf, self._r0)
             self.translateR(delta)
         # end else
         self._r = rf
     # end if
     else:
         QGraphicsItemGroup.mouseMoveEvent(self, event)
Example #41
0
 def mouseMoveEvent(self, event):
     if self._drag_enable == True:
         # map the item to the scene coordinates
         # to help keep coordinates uniform
         rf = self.getR(self.mapFromScene(QPointF(event.scenePos())))
         # for some reason we need to skip the first mouseMoveEvent
         if self._dragged == False:
             self._dragged = True
             self._r0 = rf
         # end if
         else:
             delta = self.selectionbox.delta(rf, self._r0)
             self.translateR(delta)
         # end else
         self._r = rf
     # end if
     else:
         QGraphicsItemGroup.mouseMoveEvent(self, event)
Example #42
0
    def __init__(self):
        super(AMANDisplay, self).__init__()
        self.setGeometry(0, 0, 500, 600)
        self.setStyleSheet('background-color:#233370')
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scene = QGraphicsScene(0, 0, 500, 600)

        # Timeline boundaries
        pen = QPen(QColor('white'))
        brush = QBrush(QColor('#233370'))
        self.scene.addLine(220, 0, 220, 600, pen)
        self.scene.addLine(280, 0, 280, 600, pen)
        self.scene.addLine(0, 30, 500, 30, pen)

        timelinebox = self.scene.addRect(220, 30, 60, 540, pen, brush)
        timelinebox.setFlag(timelinebox.ItemClipsChildrenToShape, True)

        # Timeline scale
        self.timeline = QGraphicsItemGroup()
        self.timeline.setParentItem(timelinebox)
        self.timeticks = []
        for i in range(40):
            y = 15 * i
            w = 6
            if i % 5 == 0:
                w = 10
                self.timeticks.append(
                    self.scene.addText('%02d' % (40 - i), QFont('Courier',
                                                                10)))
                self.timeticks[-1].setPos(240, y - 10)
                self.timeticks[-1].setDefaultTextColor(QColor('white'))
                self.timeline.addToGroup(self.timeticks[-1])
            self.timeline.addToGroup(
                self.scene.addLine(220, y, 220 + w, y, pen))
            self.timeline.addToGroup(
                self.scene.addLine(280 - w, y, 280, y, pen))

        self.lrwy = self.scene.addText('18R', QFont('Arial', 20, 50))
        self.lrwy.setPos(1, 1)
        self.lrwy.setDefaultTextColor(QColor('white'))
        # Finalize
        self.setScene(self.scene)
        self.show()
Example #43
0
class SymbolItem(QGraphicsItemGroup):
    _cache = {}

    def __init__(self, symbol, parent=None, cache_dir=None):
        super().__init__(parent)

        self._symbol = symbol

        try:
            renderer, svg_symbol = self._cache[self._symbol]
        except KeyError:
            path = os.path.join(DATA_DIR, 'symbols', '%s.svg' % self._symbol)
            svg_symbol = SvgSymbol(path, cache_dir=cache_dir)
            renderer = QSvgRenderer(svg_symbol.get_xml())
            self._cache[self._symbol] = (renderer, svg_symbol)

        self.grp = QGraphicsItemGroup(self)
        origin_x, origin_y = svg_symbol.get_origin()
        self.grp.setPos(-origin_x, -origin_y)

        self.body = QGraphicsSvgItem(self.grp)
        self.body.setSharedRenderer(renderer)
Example #44
0
    def __init__(self, color, group):
        super(Tank, self).__init__()
        self.graphics = QGraphicsItemGroup()
        self.body_graphics = TankGraphics(color)
        self.graphics.addToGroup(self.body_graphics)
        self.cannon_graphics = CannonGraphics(color)
        self.graphics.addToGroup(self.cannon_graphics)

        self.cannon_rotation = 0
        self.cannon_rotate_speed = 0
        self.group = group
        self.hp = 50

        self.fire_cd = 0
Example #45
0
 def itemChange(self, change, value):
     """docstring for itemChange"""
     if change == QGraphicsItem.ItemSelectedChange:
         if value == False:
             self.clearSelection(False)
             return False
         else:
             return True
     elif change == QGraphicsItem.ItemChildAddedChange:
         if self._added_to_press_list == False:
             # print "kid added"
             self.setFocus()  # this is to get delete keyPressEvents
             self.setParentItem(self.selectionbox.boxParent())
             self._added_to_press_list = True
             self.scene().views()[0].addToPressList(self)
         return
     return QGraphicsItemGroup.itemChange(self, change, value)
Example #46
0
    def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):
        """because :class:`GridSelectionGroup` has the flag
        ``QGraphicsItem.ItemIsMovable`` we need only get the position of the
        item to figure out what to submit to the model

        Args:
            event: the mouse evenet
        """
        # 1. call this super class method first to get the item position updated
        res = QGraphicsItemGroup.mouseMoveEvent(self, event)
        # watch out for bugs here?  everything seems OK for now, but
        # could be weird window switching edge cases
        if not self.tool.individual_pick and event.buttons() == Qt.LeftButton:
            new_pos = self.pos()
            delta = new_pos - self.drag_last_position
            self.drag_last_position = new_pos
            dx, dy = delta.x(), delta.y()
            self.tool.moveSelection(dx, dy, False, use_undostack=False)
        return res
Example #47
0
    def mouseReleaseEvent(self, event: QGraphicsSceneMouseEvent):
        """because :class:`GridSelectionGroup` has the flag
        ``QGraphicsItem.ItemIsMovable`` we need only get the position of the
        item to figure out what to submit to the model

        Args:
            event: the mouse event
        """
        MOVE_THRESHOLD = 0.01   # ignore small moves
        # print("mouse mouseReleaseEvent", self.tool.individual_pick)
        if not self.tool.individual_pick and event.button() == Qt.LeftButton:
            delta = self.pos() - self.drag_start_position
            dx, dy = delta.x(), delta.y()
            # print(abs(dx), abs(dy))
            if abs(dx) > MOVE_THRESHOLD or abs(dy) > MOVE_THRESHOLD:
                # print("finalizling", dx, dy)
                self.tool.moveSelection(dx, dy, True)
        self.tool.individual_pick = False
        return QGraphicsItemGroup.mouseReleaseEvent(self, event)
Example #48
0
    def __init__(self):
        super(AMANDisplay, self).__init__()
        self.setGeometry(0, 0, 500, 600)
        self.setStyleSheet("background-color:#233370")
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scene = QGraphicsScene(0, 0, 500, 600)

        # Timeline boundaries
        pen = QPen(QColor("white"))
        brush = QBrush(QColor("#233370"))
        self.scene.addLine(220, 0, 220, 600, pen)
        self.scene.addLine(280, 0, 280, 600, pen)
        self.scene.addLine(0, 30, 500, 30, pen)

        timelinebox = self.scene.addRect(220, 30, 60, 540, pen, brush)
        timelinebox.setFlag(timelinebox.ItemClipsChildrenToShape, True)

        # Timeline scale
        self.timeline = QGraphicsItemGroup()
        self.timeline.setParentItem(timelinebox)
        self.timeticks = []
        for i in range(40):
            y = 15 * i
            w = 6
            if i % 5 == 0:
                w = 10
                self.timeticks.append(self.scene.addText("%02d" % (40 - i), QFont("Courier", 10)))
                self.timeticks[-1].setPos(240, y - 10)
                self.timeticks[-1].setDefaultTextColor(QColor("white"))
                self.timeline.addToGroup(self.timeticks[-1])
            self.timeline.addToGroup(self.scene.addLine(220, y, 220 + w, y, pen))
            self.timeline.addToGroup(self.scene.addLine(280 - w, y, 280, y, pen))

        self.lrwy = self.scene.addText("18R", QFont("Arial", 20, 50))
        self.lrwy.setPos(1, 1)
        self.lrwy.setDefaultTextColor(QColor("white"))
        # Finalize
        self.setScene(self.scene)
        self.show()
	def cloneBody(self, bodyspecName, dropPos, itemId=None, width=0):
		bodyDef = self.bodies[bodyspecName];
		if not itemId:
			if bodyspecName not in self.nameIndex:
				self.nameIndex[bodyspecName] = 0;
			self.nameIndex[bodyspecName] += 1;
			itemId = "{}{}".format(bodyspecName, self.nameIndex[bodyspecName]);
		body = BodyItem(itemId, bodyspecName, 2);
		self.bodyInstances.append(body);
		body.setPos(dropPos);
		group = QGraphicsItemGroup(body);
		self.renderScene.addItem(body);
		width = width*self.UNITS_PER_METER or self.DEFAULT_BODY_SIZE;

		for shape in bodyDef["shapes"]:
			vertices = shape["vertices"];
			if shape["type"] == "POLYGON":
				newItem = QGraphicsPolygonItem(QPolygonF(vertices));
			if shape["type"] == "CIRCLE":
				p1, p2 = vertices
				radius = math.hypot(p2.x()-p1.x(), p2.y()-p1.y());
				newItem = QGraphicsEllipseItem(p1.x()-radius, p1.y()-radius, radius*2, radius*2);
			pen = QPen();
			pen.setWidth(0);			
			newItem.setPen(pen);
			newItem.setParentItem(group);
		bounding = group.childrenBoundingRect();
		imagePath = None;
		height = 0;
		if (bodyDef["image"]):
			imagePath = bodyDef["image"];
			pixmap = QPixmap(imagePath);
			body.setPixmap(pixmap);
			pm = QGraphicsPixmapItem(pixmap.scaledToWidth(width), body);
			body.setImg(pm);
			pm.setFlags(QGraphicsItem.ItemStacksBehindParent);
			pm.setOffset(0, -pm.boundingRect().height());
			group.setScale(width/self.TRANSCOORD_X);
			height = pm.boundingRect().height();
		else:
			group.setScale(width/bounding.width());
			height = bounding.height();
		for item in body.childItems():
			item.setPos(item.pos().x(), item.pos().y() + height)
		body.updateBorder();

		return body;
class MapWidget(QDialog):
    def __init__(self):
        QDialog.__init__(self)
    
        self.__mapWidgetUi = Ui_MapWidget()
        self.__mapWidgetUi.setupUi(self)
        
        self.__view = self.__mapWidgetUi.graphicsView
        self.__view.setObjectName("ACS_Map_View")
        self.__scene = QGraphicsScene()
                
        self.__view.setScene(self.__scene)

        self.__current_lat = 35.720428
        self.__current_lon = -120.769924
        self.__current_ground_width = 41000000. #meters(start w/ view of whole earth)
        #TODO: don't hard code location
        self.__tiler = acs_map_tiler.ACS_MapTiler(35.720428, -120.769924)

        self.__current_detail_layer = 0 #corresponds to "zoom" in map_tiler module
        self.__detail_layers = []
        self.__rect_tiles = OrderedDict() #see rectKey method for how key works

        #detail layers are various levels of raster detail for the map.
        #0 is lowest level of detail, 20 highest.  0 loads fast and the 
        #entire world can fit on a single tile.  20 loads slow, and it is unwise
        #to try to show the entire world due to the number of tiles required 
        #(higher numbered detail layers are intended for "zooming in")
        self.setupDetailLayers()

        self.__plane_layer = QGraphicsItemGroup()
        self.__scene.addItem(self.__plane_layer)
        self.__plane_icons = {}
        self.__plane_labels = {}
        self.__plane_icon_pixmaps = {}
        img_bytes = pkg_resources.resource_stream("acs_dashboards", "data/images/flyingWingTiny.png").read()
        self.__plane_icon_pixmaps[0] = QPixmap()
        self.__plane_icon_pixmaps[0].loadFromData(img_bytes)
        img_bytes2 = pkg_resources.resource_stream("acs_dashboards", "data/images/flyingWingTiny2.png").read()
        self.__plane_icon_pixmaps[1] = QPixmap()
        self.__plane_icon_pixmaps[1].loadFromData(img_bytes2)

        #for drawing waypoints:
        self.__mission_layer = QGraphicsItemGroup()
        self.__scene.addItem(self.__mission_layer)
        self.__wp_diameter = 0.0001
        self.__prev_drawn_nav_wp = None  #needed when drawing lines between wps
        self.__wp_loiter_radius = None #NOTE: this is in meters; the map itself
                                       #is in degrees

        #for drawing fence:
        self.__fence_layer = QGraphicsItemGroup()
        self.__scene.addItem(self.__fence_layer)

        #slots
        self.__view.just_zoomed.connect(self.onZoom)
        self.__mapWidgetUi.zoom_sb.valueChanged.connect(self.onZoomSBValueChanged)
        self.__view.just_panned.connect(self.onPan)
        
    def getView(self):
        return self.__view
    
    def rectKey(self, x, y):
        '''rect_tiles key'''
        return (self.__current_detail_layer, x, y)

    #returns (min_lat, max_lat, min_lon, max_lon) as a tuple
    def extentsOfVisibleWorld(self):
        topLeft = self.__view.mapToScene(0,0)
        bottomRight = self.__view.mapToScene(self.__view.width(), 
                                             self.__view.height())

        return (-topLeft.y(), -bottomRight.y(), topLeft.x(), bottomRight.x())

    #returns a list of TileInfos that are currently visible
    def tilesInVisibleWorld(self):
        (latTop, latBottom, lonLeft, lonRight) = self.extentsOfVisibleWorld()
        #print("Extents:", latTop, latBottom, lonLeft, lonRight, "\n")
        tile_info_list = self.__tiler.area_to_tile_list_lat_lon(latTop, latBottom,
                lonLeft, lonRight, self.__current_detail_layer)

        return tile_info_list

    def setupDetailLayers(self):
        #setup detail layers 0-20
        for i in range(0,21):
            self.__detail_layers.append(QGraphicsItemGroup())
            #add layer to scene:
            self.__scene.addItem(self.__detail_layers[i])            
            #hide all detail layers until it's time to show one:
            self.__detail_layers[i].hide()

        #show only the current detail layer
        self.setCurrentDetailLayer(0)

    def setCurrentDetailLayer(self, layerNum):
        self.__detail_layers[self.__current_detail_layer].hide()
        self.__detail_layers[layerNum].show()
        self.__current_detail_layer = layerNum

        self.__tiler.set_max_zoom(self.__current_detail_layer+1)
        #self.__tiler.prefetch()

        self.addTilesToCurrentDetailLayer()

    def createRectFromTileInfo(self, tile_info):
        #if Rectangle already exists, don't create it again
        key = self.rectKey(tile_info.x, tile_info.y)
        if key in self.__rect_tiles:
            return self.__rect_tiles[key]

        (y, x) = tile_info.coord()
        #TODO: do something about the hard coded 256s
        (end_y, end_x) = tile_info.coord((256, 256))
        
        #y values need to reflect across the equator due to the origin in scene space
        #being on the top right (as opposed to bottom left in tile space) 
        y = -y
        end_y = -end_y

        #keep things simple at the edges of the map:
        if y < -85.0:
            y = -85.0
        if end_y > 85.0:
            end_y = 85.0

        width = end_x - x
        height = end_y - y

        #create rectangle for the TileInfo and put it into the scene
        self.__rect_tiles[key] = QGraphicsRectItem(x, y, width, height, self.__detail_layers[self.__current_detail_layer])

        #add raster data to the rect tile
        self.__tiler.load_tile(tile_info)
        #no border
        self.__rect_tiles[key].setPen(QPen(Qt.NoPen))

        #remember the tiling data
        self.__rect_tiles[key].setData(0, tile_info)

        #attempt to add tile texture to rectangle:
        self.textureRect(self.__rect_tiles[key])

        return self.__rect_tiles[key]

    def addTilesToCurrentDetailLayer(self):
        tile_info_list = self.tilesInVisibleWorld()

        for next_tile_info in tile_info_list:
            next_rect = self.createRectFromTileInfo(next_tile_info)

            #add rect tile to appropriate detail layer
            self.__detail_layers[self.__current_detail_layer].addToGroup(next_rect)

    #returns True if texture successfully applied, False otherwise
    #depth applies to how many zoom levels (or detail layers) we have traveled
    #while attempting to get a lower resolution texture
    def textureRect(self, rect_tile):
        tile_info = rect_tile.data(0)

        if tile_info is None:
            return False

        pm = QPixmap(self.__tiler.tile_to_path(tile_info))  
        if pm.width() != 256:
            #print("Probably didn't get tile:", next_tile_info.x, next_tile_info.y, "\n")
            #TODO: Attempt to texture with a lower res tile
            #Bear in mind that you will have to take Mercator projection into
            #account on the lower res tile.
            
            #First Attempt: didn't work
            #if tile_info.zoom <= self.__tiler.get_min_zoom():
            #    return False
            #
            #find colocated lower res tile
            #(lat,lon) = tile_info.coord()
            #tile_info2 = self.__tiler.coord_to_tile(lat,lon, tile_info.zoom-1)
            #rect_tile.setData(0, tile_info2)
            #print("prev tile: ", tile_info.tile, tile_info.coord())
            #return self.textureRect(rect_tile, depth + 1)

            #until such time as we can pull lower res tiles and figure out
            #which area to render on a rectangle, skip:
            return False

        topLeft = rect_tile.boundingRect().topLeft()
        bottomRight = rect_tile.boundingRect().bottomRight()   
       
        width = bottomRight.x() - topLeft.x()
        height = bottomRight.y() - topLeft.y()

        brush_trans = QTransform()        
        brush_trans.translate(topLeft.x(), topLeft.y())
        brush_trans.scale(width/256.0, height/256.0)

        qb = QBrush(pm)
        qb.setTransform(brush_trans)
        rect_tile.setBrush(qb)
   
        return True

    def checkForNewTextures(self):
        #ONLY care about rects in the current view:
        tile_info_list = self.tilesInVisibleWorld()

        for next_tile_info in tile_info_list:
            key = self.rectKey(next_tile_info.x, next_tile_info.y)
            # make sure key exists in self.__rect_tiles
            if key not in self.__rect_tiles:
                self.createRectFromTileInfo(next_tile_info)
            
            if self.__rect_tiles[key].brush().texture().width() != 256:
                self.textureRect(self.__rect_tiles[key])
             
            #TODO: this code becomes applicable when lower res tiles become
            #available to higher zoom levels.
            #if self.__rect_tiles[key].data(0).zoom < self.__current_detail_layer:
                #lower res in there, try to get higher res 
                #(remove tile info of the lower res tile):
            #    del self.__rect_tiles[key]

    def clearFencePoints(self):
        children = self.__fence_layer.childItems()
        for child in children:
            self.__fence_layer.removeFromGroup(child)

    def clearWPs(self):
        children = self.__mission_layer.childItems()
        for child in children:
            self.__mission_layer.removeFromGroup(child)
        
        self.__prev_drawn_nav_wp = None

    def addWP(self, wp):
        if wp.command in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
                          mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM,
                          mavutil.mavlink.MAV_CMD_NAV_LAND]:
            

            #point
            rad = self.__wp_diameter * 0.5
            ellipse = QGraphicsEllipseItem(wp.y - rad, -wp.x - rad, 
                self.__wp_diameter, self.__wp_diameter, self.__mission_layer)
            ellipse.setBrush(QBrush(QColor(255, 255, 255)))
            e_pen = QPen(QColor(255, 255, 255))
            e_pen.setWidth(0)
            ellipse.setPen(e_pen)
            self.__mission_layer.addToGroup(ellipse)

            #label
            label = QGraphicsTextItem(str(wp.seq), self.__mission_layer)
            label.setZValue(2)
            label.setDefaultTextColor(Qt.white)
            label.setPos(wp.y + rad, -wp.x - rad)
            label.setScale(0.00002)  #bit hacky --  really should scale based on
                                 #current zoom, but I'm in a hurry.
            self.__mission_layer.addToGroup(label)
            label.show()

    #argument is a dictionary of waypoints (keys = ids)
    def drawNewMission(self, wps):
        self.clearWPs()

        self.drawMissionLines(wps)        
                
    def drawWPLine(self, wp1, wp2):
        if wp1 is None or wp2 is None:
            print("Error: Can't draw line for Null endpoint")
            return
    
        rad = self.__wp_diameter * 0.5
        mapped_wp1_x = wp1.y - rad
        mapped_wp1_y = -wp1.x
        #tangential approach?
        if (wp1.command == mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT
                and wp1.param1 == 1.0):
            l_rad = abs(self.__wp_loiter_radius)
            if l_rad is not None:
                dis = acs_math.gps_distance(wp1.x, wp1.y, wp2.x, wp2.y)
                theta = math.degrees(math.atan(l_rad / dis))

                #sign of self.__wp_loiter_radius indicates the direction of the
                #loiter (negative is counter-clockwise, postive is clockwise)
                #Also, the waypoint itself can override the default setting
                #via param2
                if ((wp1.param2 == 0 and self.__wp_loiter_radius > 0.0) or
                     wp1.param2 > 0.0):
                    theta = -theta

                tan_dis = math.sqrt( dis * dis - l_rad * l_rad)
                bearing = acs_math.gps_bearing(wp2.x, wp2.y, wp1.x, wp1.y)

                (tan_wp_x, tan_wp_y) = acs_math.gps_newpos(wp2.x, wp2.y,
                    bearing - theta, tan_dis)

                mapped_wp1_x = tan_wp_y - rad
                mapped_wp1_y = -tan_wp_x

        next_line = QGraphicsLineItem(mapped_wp1_x, mapped_wp1_y,
                            wp2.y - rad, -wp2.x, self.__mission_layer)
        l_pen = QPen(QColor(255, 255, 255))
        l_pen.setWidth(0.00002)
        next_line.setPen(l_pen)
        self.__mission_layer.addToGroup(next_line)

    def setWPLoiterRad(self, rad):
        self.__wp_loiter_radius = rad

    def drawWPCircle(self, wp):
        if self.__wp_loiter_radius is None:
            print("Can't draw WP loiter circles; wp_loiter_radius not set.")
            return

        rad_deg = acs_math.gps_meters_to_degrees_lat(abs(self.__wp_loiter_radius), wp.x, wp.y)
        diameter = rad_deg * 2.0
        ellipse = QGraphicsEllipseItem(wp.y - rad_deg, -wp.x - rad_deg, 
            diameter, diameter, self.__mission_layer)
        #ellipse.setBrush(QBrush(QColor(255, 255, 255)))
        e_pen = QPen(QColor(255, 255, 255))
        e_pen.setWidth(0.00002)
        ellipse.setPen(e_pen)
        self.__mission_layer.addToGroup(ellipse)

    def drawMissionLines(self, wps):
        for i in range(1, len(wps)):
            self.addWP(wps[i])

            if wps[i].command in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
                                  mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
                                  mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT,
                                  mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,
                                  mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,
                                  mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM]:

                if self.__prev_drawn_nav_wp is not None:
                    self.drawWPLine(self.__prev_drawn_nav_wp, wps[i])
            
                if wps[i].command in [mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM,
                                      mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,
                                      mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,
                                    mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT]:
                    self.drawWPCircle(wps[i])

                self.__prev_drawn_nav_wp = wps[i]

            elif wps[i].command == mavutil.mavlink.MAV_CMD_DO_JUMP:
                wp_id = wps[i].param1
                if self.__prev_drawn_nav_wp is not None:
                    self.drawWPLine(self.__prev_drawn_nav_wp, wps[wp_id])
                self.__prev_drawn_nav_wp = None
    
    def drawNewFence(self, fps):
        self.clearFencePoints()

        prev_fp = None
        for i in range(1, len(fps)):
            if prev_fp is not None:
                prev_x = prev_fp.lon
                prev_y = -prev_fp.lat
                mapped_x = fps[i].lon
                mapped_y = -fps[i].lat

                next_line = QGraphicsLineItem(prev_x, prev_y, 
                    mapped_x, mapped_y, self.__fence_layer)
                l_pen = QPen(QColor(0, 255, 0))
                l_pen.setWidth(0.1)
                next_line.setPen(l_pen)
                self.__fence_layer.addToGroup(next_line)

            prev_fp = fps[i]

    def updateIcon(self, id, uav_state, image_num=0):
        if uav_state.get_lon() == 0.0:
            #haven't received a Pose message yet
            return

        if id not in self.__plane_icons:
            #make the plane's label first
            label = QGraphicsTextItem(str(id), self.__plane_layer)
            label.setZValue(2)
            label.setDefaultTextColor(Qt.red)
            self.__plane_layer.addToGroup(label) 
            label.show()
            self.__plane_labels[id] = label

            self.__plane_icons[id] = MapGraphicsIcon(id, label,
                                                    self.__plane_layer)
            self.__plane_icons[id].centerIconAt(uav_state.get_lon(),
                                               -uav_state.get_lat())
            self.__plane_icons[id].textureIcon(self.__plane_icon_pixmaps[image_num])

            #plane icons need to be drawn on top of map tiles:
            self.__plane_icons[id].setZValue(1)
            self.__plane_layer.addToGroup(self.__plane_icons[id])

            #key 0 = last update time
            self.__plane_icons[id].setData(0, 0)

            #refresh:
            #HACK: don't know why zooming works to refresh. Couldn't
            #get scene.invalidate() nor scene.update() to work
            self.onZoom(self.__current_detail_layer)
        #end if

        now = time.time()

        #if we don't have new pose data, then we don't update the plane icon
        if (self.__plane_icons[id].data(0) is None 
         or self.__plane_icons[id].data(0) >= uav_state.get_last_pose_update()):
            return

        #place icon
        self.__plane_icons[id].centerIconAt(uav_state.get_lon(), -uav_state.get_lat())
        #give correct heading:
        quat = uav_state.get_quat()
        heading = acs_math.yaw_from_quat(quat[0], quat[1], quat[2], quat[3])
        self.__plane_icons[id].setHeading(heading)
          
        #set last update time
        self.__plane_icons[id].setData(0, now)
     
    def zoomTo(self, zoomLevel, lat = 0, lon = 0):
        self.__view.zoomTo(zoomLevel, lat, lon)

    def onZoom(self, zoom_level):
        self.setCurrentDetailLayer(zoom_level)
        self.__mapWidgetUi.zoom_sb.setValue(zoom_level)
        for id, nextPlaneIcon in self.__plane_icons.items():
            nextPlaneIcon.scaleByViewAndTexture(self.__view)

    def onZoomSBValueChanged(self, new_zoom):
        if (int(self.__view.getCurrentZoom()) != new_zoom):
            self.__view.zoomTo(new_zoom)

    def onPan(self, new_lat, new_lon):
        lat_lon_str = str(new_lat) + ", " + str(new_lon) 
        self.__mapWidgetUi.coords_lb.setText(lat_lon_str)

    def hideUAVIcon(self, id):
        if id in self.__plane_icons:
            self.__plane_icons[id].hide()
            self.__plane_labels[id].hide()

    def showUAVIcon(self, id):
        if id in self.__plane_icons:
            self.__plane_icons[id].show()
            self.__plane_labels[id].show()
Example #51
0
 def graphicsetup (self):
     lightbrush = QBrush(FlPalette.light)
     mainbrush = QBrush(self.maincolor)
     altbrush = QBrush(self.altcolor)
     nopen = QPen(0)
     viewport = self.view.viewport()
     
     self.graphgroup = QGraphicsItemGroup(self)
     self.fggroup = QGraphicsItemGroup(self)
     
     self.shadowbox = QGraphicsRectItem(self)
     self.shadowbox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
     self.shadowbox.setBrush(FlPalette.dark)
     self.shadowbox.setPen(nopen)
     self.shadowbox.setPos(*(self.style.shadowoffset,)*2)
     self.graphgroup.addToGroup(self.shadowbox)
     
     self.activebox = QGraphicsRectItem(self)
     self.activebox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
     activepen = QPen(self.maincolor, self.style.selectmargin, join=Qt.MiterJoin)
     self.activebox.setPen(activepen)
     self.activebox.hide()
     self.graphgroup.addToGroup(self.activebox)
     
     self.selectbox = QGraphicsRectItem(self)
     self.selectbox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
     selectpen = QPen(FlPalette.light, self.style.selectmargin, join=Qt.MiterJoin)
     self.selectbox.setPen(selectpen)
     self.selectbox.hide()
     self.graphgroup.addToGroup(self.selectbox)
     
     self.mainbox = QGraphicsRectItem(self)
     self.mainbox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
     self.mainbox.setBrush(mainbrush)
     self.mainbox.setPen(nopen)
     self.graphgroup.addToGroup(self.mainbox)
     
     self.nodelabel = QGraphicsSimpleTextItemCond(self, viewport)
     self.nodelabel.setBrush(lightbrush)
     self.nodelabel.setFont(self.style.boldfont)
     self.nodelabel.setText(self.label % self.realid())
     self.nodelabel.setPos(self.style.itemmargin, self.style.itemmargin)
     self.fggroup.addToGroup(self.nodelabel)
     
     self.icon = self.pixmap("images/blank.png")
     self.iwidth = self.icon.width()
     self.iconx = self.style.nodetextwidth
     
     self.condicon = QGraphicsPixmapItemCond(self.icon, self, viewport)
     self.condicon.setPos(self.iconx-self.iwidth, self.style.itemmargin)
     self.iconx = self.condicon.x()
     self.fggroup.addToGroup(self.condicon)
     
     self.randicon = QGraphicsPixmapItemCond(self.icon, self, viewport)
     self.randicon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
     self.iconx = self.randicon.x()
     self.fggroup.addToGroup(self.randicon)
     
     self.exiticon = QGraphicsPixmapItemCond(self.icon, self, viewport)
     self.exiticon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
     self.iconx = self.exiticon.x()
     self.fggroup.addToGroup(self.exiticon)
     
     self.entericon = QGraphicsPixmapItemCond(self.icon, self, viewport)
     self.entericon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
     self.iconx = self.entericon.x()
     self.fggroup.addToGroup(self.entericon)
     
     self.persisticon = QGraphicsPixmapItemCond(self.icon, self, viewport)
     self.persisticon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
     self.iconx = self.persisticon.x()
     self.fggroup.addToGroup(self.persisticon)
     
     self.comment = QGraphicsTextItemCond(self, viewport)
     self.comment.setTextWidth(self.style.nodetextwidth)
     self.comment.setDefaultTextColor(FlPalette.light)
     self.comment.setPos(0, self.nodelabel.y()+self.nodelabel.boundingRect().height()+self.style.itemmargin)
     self.fggroup.addToGroup(self.comment)
     
     self.graphgroup.addToGroup(self.fggroup)
     
     self.view.nodedocs[self.realid()]["comment"].contentsChanged.connect(self.updatecomment)
     self.updatecondition()
     self.updateenterscripts()
     self.updateexitscripts()
     self.updaterandweight()
     self.updatepersistence()
class Ui_MainWindow(QtWidgets.QMainWindow, Ui_MainWindowBase):

    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.setupUi(self)

        self.videoPlaybackInit()
        self.imgInit()
        self.menuInit()

        self.df = {}
        self.trackingPathGroup = None
        self.movableArrowGroup = None

        self.line_data_dict = {}
        self.line_item_dict = {}

        self.file_name_dict = {}

        self.currentFrameNo = 0

        self.colors = None

        self.overlayCheckBox.stateChanged.connect(self.overlayCheckBoxStateChanged)
        self.radiusSpinBox.valueChanged.connect(self.radiusSpinBoxValueChanged)
        self.frameNoSpinBox.valueChanged.connect(self.frameNoSpinBoxValueChanged)
        self.markDeltaSpinBox.valueChanged.connect(self.markDeltaSpinBoxValueChanged)

    def overlayCheckBoxStateChanged(self, s):
        if self.overlayCheckBox.isChecked():
            self.frameBufferItemGroup.show()
        else:
            self.frameBufferItemGroup.hide()

        self.updateInputGraphicsView()

    def markDeltaSpinBoxValueChanged(self, value):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setMarkDelta(self.markDeltaSpinBox.value())
            self.updateInputGraphicsView()

    def radiusSpinBoxValueChanged(self, value):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setRadius(self.radiusSpinBox.value())
            self.updateInputGraphicsView()

    def frameNoSpinBoxValueChanged(self, value):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setOverlayFrameNo(self.frameNoSpinBox.value())
            self.updateInputGraphicsView()

    def dragEnterEvent(self,event):
        event.acceptProposedAction()

    def dropEvent(self,event):
        # event.setDropAction(QtCore.Qt.MoveAction)
        mime = event.mimeData()
        if mime.hasUrls():
            urls = mime.urls()
            if len(urls) > 0:
                self.processDropedFile(urls[0].toLocalFile())

        event.acceptProposedAction()

    def processDropedFile(self,filePath):
        root,ext = os.path.splitext(filePath)
        if ext == ".filter":
            # Read Filter
            self.openFilterFile(filePath=filePath)
            return
        elif ext == ".csv":
            self.openCSVFile(filePath=filePath)
        elif ext == ".json":
            self.openJSONFile(filePath=filePath)
        elif ext == ".color":
            self.openColorFile(filePath=filePath)
        elif self.openImageFile(filePath=filePath):
            return
        elif self.openVideoFile(filePath=filePath):
            return

    def videoPlaybackInit(self):
        self.videoPlaybackWidget.hide()
        self.videoPlaybackWidget.frameChanged.connect(self.setFrame, Qt.QueuedConnection)

    def setFrame(self, frame, frameNo):
        if frame is not None:
            self.cv_img = frame
            self.currentFrameNo = frameNo
            self.updateInputGraphicsView()
            self.evaluate()

    def imgInit(self):
        self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png"))


        self.frameBuffer = Queue()
        self.frameBufferItemGroup = QGraphicsItemGroup()
        self.frameBufferItemGroup.hide()
        self.inputPixmapRenderScene = QGraphicsScene()
        self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup)

        self.inputScene = QGraphicsScene()
        self.inputGraphicsView.setScene(self.inputScene)
        self.inputGraphicsView.resizeEvent = self.graphicsViewResized
        # self.inputScene.addItem(self.frameBufferItemGroup)

        qimg = misc.cvMatToQImage(self.cv_img)
        self.inputPixmap = QPixmap.fromImage(qimg)
        self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
        self.inputScene.addItem(self.inputPixmapItem)

        self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self.inputGraphicsView)
        self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent
        self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent
        self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent

        self.inputGraphicsView.viewport().installEventFilter(self)

        self.inputGraphicsView.setMouseTracking(True)
        self.overlayScene = QGraphicsScene()
        self.inputGraphicsView.setOverlayScene(self.overlayScene)

        self.zoomedGraphicsView.setScene(self.inputScene)
        self.zoomedGraphicsView.setOverlayScene(self.overlayScene)

    def inputGraphicsViewMousePressEvent(self, event):
        self.origin = QPoint(event.pos())
        self.rubberBand.setGeometry(
            QtCore.QRect(self.origin, QtCore.QSize()))
        self.rubberBand.show()

        # Comment out to permit the view for sending the event to the child scene.
        # QGraphicsView.mousePressEvent(self.inputGraphicsView, event)

    def inputGraphicsViewMouseMoveEvent(self, event):
        if self.rubberBand.isVisible():
            self.rubberBand.setGeometry(
                QtCore.QRect(self.origin, event.pos()).normalized())
        # Comment out to permit the view for sending the event to the child scene.
        # QGraphicsView.mouseMoveEvent(self.inputGraphicsView, event)

    def inputGraphicsViewMouseReleaseEvent(self, event):
        if self.rubberBand.isVisible():
            self.rubberBand.hide()
            rect = self.rubberBand.geometry()
            sceneRect = self.inputGraphicsView.mapToScene(rect).boundingRect()
            self.zoomedGraphicsView.fitInView(QRectF(sceneRect))
            self.zoomedGraphicsView.viewport().update()
        # Comment out to permit the view for sending the event to the child scene.
        self.inputGraphicsView.viewport().update()
        # QGraphicsView.mouseReleaseEvent(self.inputGraphicsView, event)

    def menuInit(self):
        self.actionSaveDataFiles.triggered.connect(self.saveDataFiles)
        self.actionOpenCSVFile.triggered.connect(self.openCSVFile)
        self.actionOpenCSVFile.triggered.connect(self.openJSONFile)
        self.actionOpenCSVFile.triggered.connect(self.openJSONFile)

        self.actionPath.triggered.connect(self.actionPathTriggered)
        self.actionCircle.triggered.connect(self.actionCircleTriggered)
        self.actionIntervalMark.triggered.connect(self.actionIntervalMarkTriggered)
        self.actionShape.triggered.connect(self.actionShapeTriggered)
        self.actionSkeleton.triggered.connect(self.actionSkeletonTriggered)
        self.actionArrow.triggered.connect(self.actionArrowTriggered)

        self.actionChangeOrderOfNum.triggered.connect(self.actionChangeOrderOfNumTriggered)

        self.actionTrackingPathColor.triggered.connect(self.openTrackingPathColorSelectorDialog)

    def actionPathTriggered(self, checked):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setDrawLine(checked)
            if not checked or self.actionIntervalMark.isChecked():
                self.trackingPathGroup.setDrawMarkItem(checked)
            self.updateInputGraphicsView()

    def actionCircleTriggered(self, checked):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setDrawItem(checked)
            self.updateInputGraphicsView()

    def actionIntervalMarkTriggered(self, checked):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setDrawMarkItem(checked)
            self.updateInputGraphicsView()

    def actionShapeTriggered(self, checked):
        if 'shape' in self.line_item_dict.keys():
            line_item = self.line_item_dict['shape']
            if checked:
                line_item.show()
            else:
                line_item.hide()

    def actionSkeletonTriggered(self, checked):
        if 'skeleton' in self.line_item_dict.keys():
            line_item = self.line_item_dict['skeleton']
            if checked:
                line_item.show()
            else:
                line_item.hide()

    def actionArrowTriggered(self, checked):
        if self.movableArrowGroup is not None:
            if checked:
                self.movableArrowGroup.show()
            else:
                self.movableArrowGroup.hide()

    def actionChangeOrderOfNumTriggered(self, checked):
        if len(self.df.keys())!=0 or len(self.line_data_dict.keys())!=0:
            self.videoPlaybackWidget.stop()

            dialog = DataSwapDialog(self)
            dialog.setWindowModality(Qt.WindowModal)
            dialog.setData(self.df, self.line_data_dict)
            dialog.swapAccepted.connect(self.evaluate)

            res = dialog.exec()

    def openTrackingPathColorSelectorDialog(self, activated=False):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.openColorSelectorDialog(self)

    def openVideoFile(self, activated=False, filePath = None):
        if filePath is None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open Video File', userDir)

        if len(filePath) is not 0:
            self.filePath = filePath

            ret = self.videoPlaybackWidget.openVideo(filePath)
            if ret == False:
                return False

            self.videoPlaybackWidget.show()
            self.cv_img = self.videoPlaybackWidget.getCurrentFrame()

            self.initialize()

            return True
        else:
            return False

    def openImageFile(self, activated=False, filePath = None):
        if filePath == None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open Image File', userDir)

        if len(filePath) is not 0:
            self.filePath = filePath
            img = cv2.imread(filePath)
            if img is None:
                return False

            self.cv_img = img
            self.videoPlaybackWidget.hide()
            self.updateInputGraphicsView()

            self.evaluate()

            return True
        else:
            return False

    def openCSVFile(self, activated=False, filePath=None):
        if filePath is None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open CSV File', userDir, 'CSV files (*.csv)')

        if len(filePath) is not 0:
            df = pd.read_csv(filePath, index_col=0)
            name = df.index.name

            if name is None:
                name = 'position'

            self.df[name] = df
            self.file_name_dict[name] = filePath

            if name is None or name=='position':
                if self.trackingPathGroup is not None:
                    self.inputScene.removeItem(self.trackingPathGroup)

                self.trackingPathGroup = TrackingPathGroup()
                self.trackingPathGroup.setRect(self.inputScene.sceneRect())
                self.inputScene.addItem(self.trackingPathGroup)

                if not self.actionPath.isChecked():
                    self.trackingPathGroup.setDrawLine(False)
                if not self.actionCircle.isChecked():
                    self.trackingPathGroup.setDrawItem(False)
                if not self.actionIntervalMark.isChecked():
                    self.trackingPathGroup.setDrawMarkItem(False)

                self.trackingPathGroup.setDataFrame(self.df['position'])
            elif name=='arrow':
                if self.movableArrowGroup is not None:
                    self.inputScene.removeItem(self.movableArrowGroup)

                self.movableArrowGroup = MovableArrowGroup()
                self.inputScene.addItem(self.movableArrowGroup)
                self.movableArrowGroup.edited.connect(self.arrowEdited)

                if not self.actionArrow.isChecked():
                    self.movableArrowGroup.hide()

            if 'arrow' in self.df.keys() and 'position' in self.df.keys():
                self.movableArrowGroup.setDataFrame(self.df['arrow'], self.df['position'])

            self.initialize()

    def openColorFile(self, activated=False, filePath=None):
        if filePath is None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open Color File', userDir, 'Color files (*.color)')

        if len(filePath) is not 0:
            self.colors = pd.read_csv(filePath, index_col=0).as_matrix().tolist()
            self.colors = [QColor(*rgb) for rgb in self.colors]
            self.setColorsToGraphicsObjects()

    def openJSONFile(self, activated=False, filePath=None):
        if filePath is None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open JSON File', userDir, 'JSON files (*.json)')

        if len(filePath) is not 0:
            with open(filePath) as f_p:
                data = json.load(f_p)

            name = data['name']
            self.line_data_dict[name] = data
            self.file_name_dict[name] = filePath

            if name in self.line_item_dict.keys():
                self.inputScene.removeItem(self.line_item_dict[name])

            lines = MovableLineGroup()
            lines.setData(data)
            lines.setRect(self.inputScene.sceneRect())

            if name=='shape' and not self.actionShape.isChecked():
                lines.hide()

            if name=='skeleton' and not self.actionSkeleton.isChecked():
                lines.hide()

            self.line_item_dict[name] = lines
            self.inputScene.addItem(lines)

            self.initialize()

    def saveDataFiles(self, activated=False, filePath = None):
        if len(self.df.keys())!=0:
            for k, v in self.df.items():
                f_name, f_ext = os.path.splitext(self.file_name_dict[k])
                candidate_file_path = '{0}-fixed{1}'.format(f_name, f_ext)
                filePath, _ = QFileDialog.getSaveFileName(None, 'Save CSV File', candidate_file_path, "CSV files (*.csv)")

                if len(filePath) is not 0:
                    logger.debug("Saving CSV file: {0}".format(filePath))
                    df = v.copy()
                    col_n = df.as_matrix().shape[1]/2

                    col_names = np.array([('x{0}'.format(i), 'y{0}'.format(i)) for i in range(int(round(col_n)))]).flatten()
                    df.columns = pd.Index(col_names)
                    df.to_csv(filePath)

        for k, v in self.line_data_dict.items():
            f_name, f_ext = os.path.splitext(self.file_name_dict[k])
            candidate_file_path = '{0}-fixed{1}'.format(f_name, f_ext)
            filePath, _ = QFileDialog.getSaveFileName(None, 'Save JSON File', candidate_file_path, "JSON files (*.json)")

            if len(filePath) is not 0:
                logger.debug("Saving JSON file: {0}".format(filePath))
                with open(filePath, 'w') as f_p:
                    json.dump(v, f_p)

    def updateInputGraphicsView(self):
        self.inputScene.removeItem(self.inputPixmapItem)
        qimg = misc.cvMatToQImage(self.cv_img)
        self.inputPixmap = QPixmap.fromImage(qimg)

        p = QPainter(self.inputPixmap)
        sourceRect = self.inputPixmapRenderScene.sceneRect()
        self.inputPixmapRenderScene.render(p, QRectF(sourceRect), QRectF(sourceRect), QtCore.Qt.IgnoreAspectRatio)

        self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
        rect = QtCore.QRectF(self.inputPixmap.rect())
        self.inputScene.setSceneRect(rect)
        self.inputScene.addItem(self.inputPixmapItem)

        self.inputGraphicsView.viewport().update()
        self.graphicsViewResized()

    def eventFilter(self, obj, event):
        if obj is self.inputGraphicsView.viewport() and event.type()==QEvent.Wheel:
            return True

        if event.type() == QEvent.KeyPress:
            if Qt.Key_Home <= event.key() <= Qt.Key_PageDown:
                self.videoPlaybackWidget.playbackSlider.keyPressEvent(event)
                return True

        return False

    def graphicsViewResized(self, event=None):
        self.inputGraphicsView.fitInView(QtCore.QRectF(self.inputPixmap.rect()), QtCore.Qt.KeepAspectRatio)

    def setColorsToGraphicsObjects(self):
        # FIXME: データセットと色リストのサイズ整合性チェックが必要
        if self.colors is not None:
            if self.trackingPathGroup is not None:
                self.trackingPathGroup.setColors(self.colors)

            for k, v in self.line_item_dict.items():
                v.setColors(self.colors)

    def initialize(self):
        if  not self.videoPlaybackWidget.isOpened():
            return

        if self.trackingPathGroup is not None:
            r = self.trackingPathGroup.autoAdjustRadius(self.cv_img.shape)
            self.radiusSpinBox.setValue(r)
            self.trackingPathGroup.autoAdjustLineWidth(self.cv_img.shape)

            self.trackingPathGroup.setItemsAreMovable(True)

            if self.movableArrowGroup is not None:
                pass

        for k, v in self.line_item_dict.items():
            v.autoAdjustLineWidth(self.cv_img.shape)
            v.autoAdjustMarkSize(self.cv_img.shape)

        self.setColorsToGraphicsObjects()

        self.evaluate()

    def evaluate(self):
        if not self.videoPlaybackWidget.isOpened():
            return

        qimg = misc.cvMatToQImage(self.cv_img)
        pixmapItem = QGraphicsPixmapItem(QPixmap.fromImage(qimg))
        pixmapItem.setOpacity(0.2)

        self.frameBuffer.put(pixmapItem)
        self.frameBufferItemGroup.addToGroup(pixmapItem)
        if self.frameBuffer.qsize() > 10:
            item = self.frameBuffer.get()
            self.frameBufferItemGroup.removeFromGroup(item)

        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setPoints(self.currentFrameNo)

            if self.movableArrowGroup is not None:
                self.movableArrowGroup.setPositions(self.currentFrameNo)

        for k, v in self.line_item_dict.items():
            v.setPolyline(self.currentFrameNo)

    @pyqtSlot(object)
    def arrowEdited(self, name):
        # TODO: 方向の再推定機能の実装
        # quit_msg = "Arrow {} edited.\nRe-estimate the direction in following frames?".format(name)
        # reply = QtWidgets.QMessageBox.question(
        #         self,
        #         'Question',
        #         quit_msg,
        #         QtWidgets.QMessageBox.Yes,
        #         QtWidgets.QMessageBox.No
        #         )
        #
        # if reply == QtWidgets.QMessageBox.Yes:
        #     pass
        # else:
        #     pass
        pass
Example #53
0
class BoardGUI(QWidget):
    """cointain the graphical representation of the Board"""

    # ratio of bordersize compared to the size of one base square
    borderRatio = 0.8
    baseRectRatio = 14/15  # 12/13 for normal ratio but looks weird
    stoneScale = 0.46

    # siganl
    stoneClicked = pyqtSignal(tuple)

    def __init__(self, parent, game):
        super().__init__()

        self.initUI(game)

    def initUI(self, game):
        self.board = game.currentBoard
        self.game = game

        self.showCoords = True
        self.scene = QGraphicsScene()

        # grid containing coordinates for the scene
        self.grid = []
        self.drawGrid()

        # initialize and set layout + view
        self.view = QGraphicsView(self.scene)
        self.view.setMouseTracking(True)
        self.view.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.setMouseTracking(True)
        box = QHBoxLayout()
        box.addWidget(self.view)
        self.setLayout(box)

        # stones for all positions are created and listed in self.pos dict
        self.createPosition()
        self.makeCoords()  # has to be called after drawGrid!

    def resizeEvent(self, e):
        self.view.fitInView(self.view.scene().sceneRect(), Qt.KeepAspectRatio)

    def boardWidth(self):
        """returns the max width fitting into widget"""
        width = self.contentsRect().width()*0.95
        height = self.contentsRect().height()*0.95

        return min(width, height*self.baseRectRatio)

    def boardHeight(self):
        """returns the max width fitting into widget """
        return self.boardWidth()*(1/self.baseRectRatio)

    def makeGrid(self):
        """
        returns coords [[(x, y)]] for the Grid according
         to current window mesures
        """
        # set scenesize to window size
        self.scene.setSceneRect(0, 0, self.boardWidth(), self.boardHeight())
        denom = self.board.size + 2*self.borderRatio
        baseWidth = self.boardWidth() / denom
        baseHeight = self.boardHeight() / denom

        leftOffset = 0.5*baseWidth  # (self.contentsRect().width()-self.boardWidth())/2
        topOffset = 0  # (self.contentsRect().height()-self.boardHeight())/2

        partionWidth = [leftOffset+(self.borderRatio+x)*baseWidth
                        for x in range(self.board.size)]
        partionHeight = [topOffset+(self.borderRatio+x)*baseHeight
                         for x in range(self.board.size)]

        grid = [[(x, y) for x in partionWidth] for y in partionHeight]
        self.grid = grid
        self.baseWidth = baseWidth

    def drawGrid(self):
        """draws the background grid"""
        self.makeGrid()
        for line in self.grid:
            self.scene.addLine(*line[0], *line[-1])
        for (pointT, pointB) in zip(self.grid[0], self.grid[-1]):
            self.scene.addLine(*pointT, *pointB)
        self.drawHoshis()

    def makeCoords(self):
        """ draws Coordinates """
        xLabels = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
        yLabels = list(range(1, 26))
        botGrid = []
        leftGrid = []
        # generate pixel coordinates grids
        for n in range(self.board.size):
            (xBot, yBot) = self.grid[self.board.size-1][n]
            yBot += self.baseWidth*0.4/self.baseRectRatio
            xBot -= self.baseWidth*0.1
            botGrid.append((xBot, yBot))
            (xLeft, yLeft) = self.grid[n][0]
            xLeft -= self.baseWidth*1.2
            yLeft -= self.baseWidth*0.3/self.baseRectRatio
            leftGrid.append((xLeft, yLeft))
        # generate Text items and add them to group
        self.coordGroup = QGraphicsItemGroup()
        for n in range(self.board.size):
            leftText = QGraphicsSimpleTextItem(str(yLabels[n]))
            leftText.setPos(*leftGrid[n])
            self.coordGroup.addToGroup(leftText)
            bottomText = QGraphicsSimpleTextItem(xLabels[n])
            bottomText.setPos(*botGrid[n])
            self.coordGroup.addToGroup(bottomText)
        # draw coordinates and update visibility according to self.showCoords
        self.scene.addItem(self.coordGroup)
        self.updateCoords()

    def updateCoords(self):
        """ slot that updates the visibility os the coordiantes. """
        self.coordGroup.setVisible(self.showCoords)

    def setCoordVis(self, visibility):
        """ set the self.showCoords boolean """
        self.showCoords = visibility
        self.updateCoords()

    def drawHoshis(self):
        """ Draws Hoshi dots"""
        hoshis = []
        rad = self.baseWidth*0.15
        for (x, y) in self.board.getHoshis():
            hoshis.append(self.grid[x][y])
        for point in hoshis:
            (x, y) = point
            self.scene.addEllipse(x-rad, y-rad, rad*2.0, rad*2.0,
                                  QPen(), QBrush(Qt.SolidPattern))

    def updatePosition(self):
        """
        sets the colors for all stones in self.pos according
        to the status in self.board
        """
        for (x, y) in self.pos:
            color = self.game.currentBoard.getPosition(x, y)
            self.pos[(x, y)].setMark(None)
            self.pos[(x, y)].setColor(color)
        lastMove = self.game.currentBoard.lastMove
        if lastMove:
            self.pos[lastMove].setMark(GoMarks.circel)
        ko = self.game.currentBoard.ko
        if ko:
            self.pos[ko].setMark(GoMarks.square)

    def createPosition(self):
        """
        Creates the self.pos dictionary containing all possible stones on the
        board initialized as empty stones

        also connects a signal form each stone to ???
        """
        self.pos = {}
        radius = self.stoneScale*self.baseWidth
        for row in range(self.board.size):
            for col in range(self.board.size):
                (x, y) = self.grid[row][col]
                newStone = Stone(x, y, radius)
                self.pos[(row, col)] = newStone
                self.scene.addItem(newStone)
        self.updatePosition()
        self.connecting()

    def connecting(self):
        for key in self.pos:
            self.pos[key].clicked.connect(lambda key=key: self.resend(key))

    def resend(self, pos):
        """
        emits the captured signal again,
        with (int, in) parameter for stone clicked
        """
        self.stoneClicked.emit(pos)
Example #54
0
class AMANDisplay(QGraphicsView):
    def __init__(self):
        super(AMANDisplay, self).__init__()
        self.setGeometry(0, 0, 500, 600)
        self.setStyleSheet("background-color:#233370")
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scene = QGraphicsScene(0, 0, 500, 600)

        # Timeline boundaries
        pen = QPen(QColor("white"))
        brush = QBrush(QColor("#233370"))
        self.scene.addLine(220, 0, 220, 600, pen)
        self.scene.addLine(280, 0, 280, 600, pen)
        self.scene.addLine(0, 30, 500, 30, pen)

        timelinebox = self.scene.addRect(220, 30, 60, 540, pen, brush)
        timelinebox.setFlag(timelinebox.ItemClipsChildrenToShape, True)

        # Timeline scale
        self.timeline = QGraphicsItemGroup()
        self.timeline.setParentItem(timelinebox)
        self.timeticks = []
        for i in range(40):
            y = 15 * i
            w = 6
            if i % 5 == 0:
                w = 10
                self.timeticks.append(self.scene.addText("%02d" % (40 - i), QFont("Courier", 10)))
                self.timeticks[-1].setPos(240, y - 10)
                self.timeticks[-1].setDefaultTextColor(QColor("white"))
                self.timeline.addToGroup(self.timeticks[-1])
            self.timeline.addToGroup(self.scene.addLine(220, y, 220 + w, y, pen))
            self.timeline.addToGroup(self.scene.addLine(280 - w, y, 280, y, pen))

        self.lrwy = self.scene.addText("18R", QFont("Arial", 20, 50))
        self.lrwy.setPos(1, 1)
        self.lrwy.setDefaultTextColor(QColor("white"))
        # Finalize
        self.setScene(self.scene)
        self.show()

    def update(self, simt, data):
        # data has: ids, iafs, eats, etas, delays, rwys, spdratios

        # First delete old labels
        for (key,) in self.aircraft.keys:
            if key not in data.ids:
                # del label
                del self.aircraft[key]

        for i in len(data.ids):
            if data.ids[i] not in self.aircraft:
                # self.aircraft[data.ids[i]] = QLabel()
                pass

            # Generate the new label text and position
            newtext = "<font color=Red>bla</font>"  # veranderen
            lbl = self.aircraft[data.ids[i]]
            lbl.setText(newtext)
            lbl.move(posx, posy)  # move in pixels
Example #55
0
class NodeItem(QGraphicsItem):
    def __init__ (self, nodeobj, parent=None, view=None, state=1):
        super().__init__()
        self.edge = None
        self.linkIDs = None
        self.children = None
        self.childpos = None
        self.nodeobj = nodeobj
        self.style = FlGlob.mainwindow.style
        self.view = weakref.proxy(view)
        self.refID = parent.realid() if parent is not None else None
        self.state = state
        self.setrank(parent)
        self.setCursor(Qt.ArrowCursor)
        self.yoffset = 0
        self.graphicsetup()
        self.setstate(state)
    
    def id (self):
        return (self.refID, self.nodeobj.ID)
    
    def realid (self):
        return self.nodeobj.ID
    
    def childlist (self, generate=False):
        ID = self.nodeobj.ID
        itemtable = self.view.itemtable
        if self.state == 1 and ID in itemtable and not self.iscollapsed():
            if self.children and self.nodeobj.linkIDs == self.linkIDs and None not in [c() for c in self.children]:
                ret = self.children
            else:
                children = []
                for child in self.nodeobj.linkIDs:
                    if child in itemtable[ID]:
                        item = itemtable[ID][child]
                    else:
                        continue
                    children.append(weakref.ref(item))
                self.linkIDs = self.nodeobj.linkIDs.copy()
                self.children = children
                ret = children
        else:
            ret = []
        if generate:
            x = self.x()
            y = self.y()
            self.childpos = []
            for target in ret:
                t = target()
                self.childpos.append((t.x()+t.boundingRect().left()-self.style.activemargin-x, t.y()-y))
            if self.edge:
                if self.childpos != self.edge.childpos:
                    self.edge.prepareGeometryChange()
                    self.edge.sourceright = self.boundingRect().right()
                    self.edge.update(self.edge.boundingRect())
        return ret
    
    def setedge (self, edge):
        self.edge = edge
        edge.setX(self.x())
    
    def setactive (self, active):
        if active:
            self.activebox.show()
            self.mainbox.setBrush(QBrush(self.altcolor))
        else:
            self.activebox.hide()
            self.mainbox.setBrush(QBrush(self.maincolor))
    
    def setselected (self, selected):
        if selected:
            self.selectbox.show()
        else:
            self.selectbox.hide()
    
    def setstate (self, state):
        self.state = state
        if state == 1: # normal
            self.show()
            self.graphgroup.setOpacity(1)
            self.shadowbox.show()
        elif state == 0: # ghost
            self.show()
            self.graphgroup.setOpacity(0.7)
            self.shadowbox.hide()
        elif state == -1: # hidden
            self.hide()
    
    def setplaymode (self, playmode):
        if playmode:
            self.setOpacity(0.5)
        else:
            self.setOpacity(1)
    
    def setY (self, y):
        parent = self.view.itembyID(self.refID)
        y += self.getyoffset()
        if self.edge is not None:
            self.edge.setY(y)
        super().setY(y)
    
    def setrank (self, parent):
        if parent is None:
            return
        if self.issubnode():
            x = parent.x()
            self.setX(x)
        else:
            x = parent.x()+self.style.rankwidth
            self.setX(x)
            self.nudgechildren()
        if self.edge is not None:
            self.edge.setX(x)
    
    def nudgechildren (self):
        for child in self.childlist():
            child().setrank(self)
    
    def getyoffset (self):
        if self.nodeobj.nodebank == -1:
            return self.yoffset
        else:
            return self.view.itembyID(self.refID).getyoffset() + self.yoffset
    
    def hide (self):
        super().hide()
        if self.edge:
            self.edge.hide()
    
    def show (self):
        super().show()
        if self.edge:
            self.edge.show()
    
    def issubnode (self):
        return self.nodeobj.nodebank is not -1
    
    def isghost (self):
        return not self.state
    
    def realnode (self):
        return self.view.itembyID(self.nodeobj.ID)
    
    def isactive (self):
        return self.view.activenode is self
    
    def isselected (self):
        return self.view.selectednode is self
    
    def iscollapsed (self):
        return self.id() in self.view.collapsednodes
    
    def y_top (self):
        return self.y() - self.boundingRect().height()//2
    
    def y_bottom (self):
        return self.y() + self.boundingRect().height()//2
    
    def bulkshift (self, children, diff):
        self.setY(self.y() + diff)
        if children is None:
            children = [c() for c in self.childlist()]
        for child in children:
            child.bulkshift(None, diff)
    
    def treeposition (self, ranks=None):
        if ranks is None:
            ranks = dict()
        localranks = dict()
        children = [c() for c in self.childlist()]
        for child in children:
            localranks = child.treeposition(localranks)
        rank = self.x() // self.style.rankwidth
        if children:
            top = children[0].y_top()
            bottom = children[-1].y_bottom()
            self.setY((top+bottom)//2)
        localranks[rank] = [self.y_top, self.y_bottom]
        streeshift = None
        for r in localranks:
            if r in ranks:
                rankshift = ranks[r][1]() + self.style.rowgap - localranks[r][0]()
                if streeshift is None or rankshift > streeshift:
                    streeshift = rankshift
                ranks[r][1] = localranks[r][1]
            else:
                ranks[r] = localranks[r]
        if streeshift:
            self.bulkshift(children, streeshift)
        return ranks
    
    def siblings (self):
        if self.refID is None:
            return None
        parent = self.view.nodecontainer.nodes[self.refID]
        if self.issubnode():
            return parent.subnodes
        else:
            return parent.linkIDs
    
    def siblingabove (self):
        sibs = self.siblings()
        if sibs is None or self.nodeobj.ID not in sibs:
            return None
        myindex = sibs.index(self.nodeobj.ID)
        if myindex:
            sibID = (self.refID, sibs[myindex-1])
            return self.view.itembyfullID(sibID)
        else:
            return None
    
    def siblingbelow (self):
        sibs = self.siblings()
        if sibs is None or self.nodeobj.ID not in sibs:
            return None
        myindex = sibs.index(self.nodeobj.ID)
        if len(sibs) > myindex+1:
            sibID = (self.refID, sibs[myindex+1])
            return self.view.itembyfullID(sibID)
        else:
            return None
    
    def subtreesize (self, depth=-1):
        """Find vertical extents of a subtree.
        
        Returns min/max y coordinates up to given depth (negative depth means
        whole subtree)."""

        # calculate child positions for EgdeItem only once when calculating scenerect
        if depth<0:
            generate = True
        else:
            generate = False
        
        children = [c() for c in self.childlist(generate=generate)]
        maxdepth = abs(depth)
        if children and depth:
            nextdepth = depth-1
            ymin = self.y_top()
            ymax = self.y_bottom()
            for child in children:
                top, bottom, depth = child.subtreesize(nextdepth)
                ymin = min(ymin, top)
                ymax = max(ymax, bottom)
                maxdepth = max(maxdepth, depth)
        else:
            ymin = self.y_top()
            ymax = self.y_bottom()
        return ymin, ymax, maxdepth
        
    def boundingRect (self):
        return self.rect
    
    def paint (self, painter, style, widget):
        pass
    
    def pixmap (self, path):
        return QPixmap(path).scaledToWidth(self.style.boldheight, Qt.SmoothTransformation)
    
    def graphicsetup (self):
        lightbrush = QBrush(FlPalette.light)
        mainbrush = QBrush(self.maincolor)
        altbrush = QBrush(self.altcolor)
        nopen = QPen(0)
        viewport = self.view.viewport()
        
        self.graphgroup = QGraphicsItemGroup(self)
        self.fggroup = QGraphicsItemGroup(self)
        
        self.shadowbox = QGraphicsRectItem(self)
        self.shadowbox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
        self.shadowbox.setBrush(FlPalette.dark)
        self.shadowbox.setPen(nopen)
        self.shadowbox.setPos(*(self.style.shadowoffset,)*2)
        self.graphgroup.addToGroup(self.shadowbox)
        
        self.activebox = QGraphicsRectItem(self)
        self.activebox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
        activepen = QPen(self.maincolor, self.style.selectmargin, join=Qt.MiterJoin)
        self.activebox.setPen(activepen)
        self.activebox.hide()
        self.graphgroup.addToGroup(self.activebox)
        
        self.selectbox = QGraphicsRectItem(self)
        self.selectbox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
        selectpen = QPen(FlPalette.light, self.style.selectmargin, join=Qt.MiterJoin)
        self.selectbox.setPen(selectpen)
        self.selectbox.hide()
        self.graphgroup.addToGroup(self.selectbox)
        
        self.mainbox = QGraphicsRectItem(self)
        self.mainbox.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
        self.mainbox.setBrush(mainbrush)
        self.mainbox.setPen(nopen)
        self.graphgroup.addToGroup(self.mainbox)
        
        self.nodelabel = QGraphicsSimpleTextItemCond(self, viewport)
        self.nodelabel.setBrush(lightbrush)
        self.nodelabel.setFont(self.style.boldfont)
        self.nodelabel.setText(self.label % self.realid())
        self.nodelabel.setPos(self.style.itemmargin, self.style.itemmargin)
        self.fggroup.addToGroup(self.nodelabel)
        
        self.icon = self.pixmap("images/blank.png")
        self.iwidth = self.icon.width()
        self.iconx = self.style.nodetextwidth
        
        self.condicon = QGraphicsPixmapItemCond(self.icon, self, viewport)
        self.condicon.setPos(self.iconx-self.iwidth, self.style.itemmargin)
        self.iconx = self.condicon.x()
        self.fggroup.addToGroup(self.condicon)
        
        self.randicon = QGraphicsPixmapItemCond(self.icon, self, viewport)
        self.randicon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
        self.iconx = self.randicon.x()
        self.fggroup.addToGroup(self.randicon)
        
        self.exiticon = QGraphicsPixmapItemCond(self.icon, self, viewport)
        self.exiticon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
        self.iconx = self.exiticon.x()
        self.fggroup.addToGroup(self.exiticon)
        
        self.entericon = QGraphicsPixmapItemCond(self.icon, self, viewport)
        self.entericon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
        self.iconx = self.entericon.x()
        self.fggroup.addToGroup(self.entericon)
        
        self.persisticon = QGraphicsPixmapItemCond(self.icon, self, viewport)
        self.persisticon.setPos(self.iconx-self.style.itemmargin-self.iwidth, self.style.itemmargin)
        self.iconx = self.persisticon.x()
        self.fggroup.addToGroup(self.persisticon)
        
        self.comment = QGraphicsTextItemCond(self, viewport)
        self.comment.setTextWidth(self.style.nodetextwidth)
        self.comment.setDefaultTextColor(FlPalette.light)
        self.comment.setPos(0, self.nodelabel.y()+self.nodelabel.boundingRect().height()+self.style.itemmargin)
        self.fggroup.addToGroup(self.comment)
        
        self.graphgroup.addToGroup(self.fggroup)
        
        self.view.nodedocs[self.realid()]["comment"].contentsChanged.connect(self.updatecomment)
        self.updatecondition()
        self.updateenterscripts()
        self.updateexitscripts()
        self.updaterandweight()
        self.updatepersistence()
        
        # Never call updatelayout() from here (or any inheritable reimplementation)!
    
    def collapse (self, collapse):
        for item in self.fggroup.childItems():
            if item is not self.nodelabel:
                if collapse:
                    item.hide()
                else:
                    item.show()
        self.updatelayout()
    
    def updatecondition (self):
        icons = {True: "key", False: "blank"}
        pixmap = self.pixmap("images/%s.png" % icons[self.nodeobj.hascond()])
        self.condicon.setPixmap(pixmap)
        if self.nodeobj.hascond():
            self.condicon.setToolTip("Condition")
        else:
            self.condicon.setToolTip("")
    
    def updateenterscripts (self):
        icons = {True: "script-enter", False: "blank"}
        pixmap = self.pixmap("images/%s.png" % icons[self.nodeobj.hasenterscripts()])
        self.entericon.setPixmap(pixmap)
        if self.nodeobj.hasenterscripts():
            self.entericon.setToolTip("Enter Scripts")
        else:
            self.entericon.setToolTip("")
    
    def updateexitscripts (self):
        icons = {True: "script-exit", False: "blank"}
        pixmap = self.pixmap("images/%s.png" % icons[self.nodeobj.hasexitscripts()])
        self.exiticon.setPixmap(pixmap)
        if self.nodeobj.hasexitscripts():
            self.exiticon.setToolTip("Exit Scripts")
        else:
            self.exiticon.setToolTip("")
    
    def updaterandweight (self):
        icons = {True: "dice", False: "blank"}
        pixmap = self.pixmap("images/%s.png" % icons[bool(self.nodeobj.randweight)])
        self.randicon.setPixmap(pixmap)
        if self.nodeobj.randweight:
            self.randicon.setToolTip("Random Weight: %s" % self.nodeobj.randweight)
        else:
            self.randicon.setToolTip("")
    
    def updatepersistence (self):
        icons = {"Mark": "mark", "OncePerConv": "once", "OnceEver": "onceever", "": "blank"}
        pixmap = self.pixmap("images/%s.png" % icons[self.nodeobj.persistence])
        self.persisticon.setPixmap(pixmap)
        if self.nodeobj.persistence:
            self.persisticon.setToolTip("Persistence: %s" % self.nodeobj.persistence)
        else:
            self.persisticon.setToolTip("")
    
    def updatecomment (self):
        self.fggroup.removeFromGroup(self.comment)
        contents = self.view.nodedocs[self.realid()]["comment"].toPlainText()
        if not contents:
            self.comment.hide()
        else:
            self.comment.show()
            self.comment.setPlainText(contents)
            self.fggroup.addToGroup(self.comment)
        self.updatelayout()
    
    def updatelayout (self):
        if self.iscollapsed():
            rect = self.nodelabel.mapRectToParent(self.nodelabel.boundingRect())
        else:
            rect = self.fggroup.childrenBoundingRect()
        mainrect = rect.marginsAdded(self.style.nodemargins)
        self.mainbox.setRect(mainrect)
        self.shadowbox.setRect(mainrect)
        self.selectbox.setRect(mainrect.marginsAdded(self.style.selectmargins))
        activerect = mainrect.marginsAdded(self.style.activemargins)
        self.activebox.setRect(activerect)
        self.graphgroup.setPos(-activerect.width()//2-activerect.x(), -activerect.height()//2-activerect.y())
        self.prepareGeometryChange()
        self.rect = self.graphgroup.mapRectToParent(mainrect)
        self.view.updatelayout()
    
    def mouseDoubleClickEvent (self, event):
        super().mouseDoubleClickEvent(event)
        event.accept()
        if event.button() == Qt.LeftButton:
            self.view.setactivenode(self)
    
    def mousePressEvent (self, event):
        super().mousePressEvent(event)
        if event.button() & (Qt.LeftButton | Qt.RightButton) :
            self.view.setselectednode(self)
            event.accept()
    
    def __repr__ (self):
        return "<%s %s>" % (type(self).__name__, self.id())
Example #56
0
class Ui_MainWindow(QtWidgets.QMainWindow, Ui_MainWindowBase):
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.setupUi(self)

        self.videoPlaybackInit()
        self.imgInit()
        self.menuInit()

        self.df = None
        self.trackingPathGroup = None
        self.drawingFlag = False
        self.handInputSystem = None
        self.handInputSystem = HandInputSystem()
        self.handInputSystem.setRect(self.inputScene.sceneRect())
        self.inputScene.addItem(self.handInputSystem)
        self.handInputSystem.addNewDataFrame()
        self.currentFrameNo = 0
            
        self.colors = []

        self.circleCheckBox.stateChanged.connect(self.polyLineCheckBoxStateChanged)
        self.lineCheckBox.stateChanged.connect(self.polyLineCheckBoxStateChanged)
        self.overlayCheckBox.stateChanged.connect(self.overlayCheckBoxStateChanged)
        self.radiusSpinBox.valueChanged.connect(self.radiusSpinBoxValueChanged)

        self.frameNoSpinBox.valueChanged.connect(self.frameNoSpinBoxValueChanged)
        self.groupBox_2.hide()
        

        self.inputGraphicsView.viewport().setCursor(QtCore.Qt.ArrowCursor)
        #
        self.optionViewButton.pressed.connect(self.optionViewButtonPressed)
        self.zoomedGraphicsView.hide()

        self.dataFrameWidget.dataFrameChanged.connect(self.dataFrameChanged)
        self.dataFrameWidget.hide()
        self.handInputSystem.setColor(self.dataFrameWidget.getColor())
        
        #self.processDropedFile("/Users/ymnk/temp/Dast/2016/01/hoge.avi")
        #self.processDropedFile("./a.csv")        
    def dataFrameChanged(self,addedFrameFlag,editingNo,color):
        if addedFrameFlag:
            self.handInputSystem.addNewDataFrame()
        self.handInputSystem.setEditingNo(editingNo)
        self.handInputSystem.setColor(color)
        print(addedFrameFlag,color,editingNo)

    def optionViewButtonPressed(self):
        if self.groupBox_2.isVisible():
            self.optionViewButton.setText("<")
            self.groupBox_2.hide()
        else:
            self.optionViewButton.setText(">")
            self.groupBox_2.show()

    def overlayCheckBoxStateChanged(self, s):
        if self.overlayCheckBox.isChecked():
            self.frameBufferItemGroup.show()
        else:
            self.frameBufferItemGroup.hide()

        self.updateInputGraphicsView()

    def polyLineCheckBoxStateChanged(self, s):
        overlayFrameNo = self.frameNoSpinBox.value()

        min_value = max(self.currentFrameNo-overlayFrameNo,0)
        current_pos = self.currentFrameNo - min_value

        if self.handInputSystem is not None:
            self.handInputSystem.setDrawItem(current_pos, self.circleCheckBox.isChecked())
            self.handInputSystem.setDrawLine(self.lineCheckBox.isChecked())
            self.updateInputGraphicsView()

    def radiusSpinBoxValueChanged(self, value):
        if self.handInputSystem is not None:
            self.handInputSystem.setRadius(self.radiusSpinBox.value())
            self.updateInputGraphicsView()

    def frameNoSpinBoxValueChanged(self, value):
        if self.handInputSystem is not None:
            self.handInputSystem.setOverlayFrameNo(self.frameNoSpinBox.value())
            self.updateInputGraphicsView()
    def dragEnterEvent(self,event):
        event.acceptProposedAction()

    def dropEvent(self,event):
        # event.setDropAction(QtCore.Qt.MoveAction)
        mime = event.mimeData()
        if mime.hasUrls():
            urls = mime.urls()
            if len(urls) > 0:
                self.processDropedFile(urls[0].toLocalFile())

        event.acceptProposedAction()

    def processDropedFile(self,filePath):
        root,ext = os.path.splitext(filePath)
        if ext == ".filter":
            # Read Filter
            self.openFilterFile(filePath=filePath)
            return
        elif ext == ".csv":
            self.openCSVFile(filePath=filePath)
        elif self.openImageFile(filePath=filePath):
            return
        elif self.openVideoFile(filePath=filePath):
            return

    def videoPlaybackInit(self):
        self.videoPlaybackWidget.hide()
        self.videoPlaybackWidget.frameChanged.connect(self.setFrame, Qt.QueuedConnection)

    def setFrame(self, frame, frameNo):
        if frame is not None:
            self.cv_img = frame
            self.currentFrameNo = frameNo
            self.updateInputGraphicsView()
            if self.videoInitialFlag == True:
                 self.graphicsViewResized()
                 self.videoInitialFlag = False
            self.evaluate()

    def imgInit(self):
        self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png"))


        self.frameBuffer = Queue()
        self.frameBufferItemGroup = QGraphicsItemGroup()
        self.frameBufferItemGroup.hide()
        self.inputPixmapRenderScene = QGraphicsScene()
        self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup)

        self.inputScene = QGraphicsScene()
        self.inputGraphicsView.setScene(self.inputScene)
        self.inputGraphicsView.resizeEvent = self.graphicsViewResized
        # self.inputScene.addItem(self.frameBufferItemGroup)

        qimg = misc.cvMatToQImage(self.cv_img)
        self.inputPixmap = QPixmap.fromImage(qimg)
        self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
        self.inputScene.addItem(self.inputPixmapItem)

        self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent
        self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent
        self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent
        self.inputGraphicsView.keyPressEvent = self.inputGraphicsViewKeyPressEvent
        self.inputGraphicsView.keyReleaseEvent = self.inputGraphicsViewKeyReleaseEvent
        self.inputGraphicsView.wheelEvent = self.inputGraphicsViewwheelEvent
        #self.inputGraphicsView.focusInEvent = self.inputGraphicsViewfocusInEvent
        self.inputGraphicsView.viewport().installEventFilter(self)

        self.inputGraphicsView.setMouseTracking(True)
        self.overlayScene = QGraphicsScene()
        self.inputGraphicsView.setOverlayScene(self.overlayScene)
    def inputGraphicsViewfocusInEvent(self,event):
        #
        QGraphicsView.focusInEvent(self.inputGraphicsView, event)
    def inputGraphicsViewMousePressEvent(self, event):
        if event.modifiers() == QtCore.Qt.ShiftModifier:
            # Comment out to permit the view for sending the event to the child scene.
            QGraphicsView.mousePressEvent(self.inputGraphicsView, event)
        else:
            self.drawingFlag = True
            if not self.videoPlaybackWidget.isPlaying():
                self.videoPlaybackWidget.playButtonClicked()
            
    def inputGraphicsViewMouseMoveEvent(self, event):
        if event.modifiers() == QtCore.Qt.ShiftModifier:
            # Comment out to permit the view for sending the event to the child scene.
            QGraphicsView.mouseMoveEvent(self.inputGraphicsView, event)
        elif self.drawingFlag == True:
            pass
            #self.videoPlaybackWidget.moveNextButtonClicked()
        #self.handInputSystem.inputMouseMoveEvent(mousePosition,self.currentFrameNo)
        #print(self.currentFrameNo)
        #self.positionStack.append(mousePosition)
        #self.handInputSystem.inputMouseMoveEvent(mousePosition)
        
    def inputGraphicsViewMouseReleaseEvent(self, event):
        if self.drawingFlag == True:
            self.drawingFlag = False
            self.videoPlaybackWidget.playButtonClicked()
        self.handInputSystem.inputMouseReleaseEvent()
        self.handInputSystem.setPoints()
        # Comment out to permit the view for sending the event to the child scene.
        QGraphicsView.mouseReleaseEvent(self.inputGraphicsView, event)
        self.inputGraphicsView.viewport().setCursor(QtCore.Qt.ArrowCursor)
        
    def inputGraphicsViewKeyPressEvent(self,event):
        mousePosition = QCursor().pos()
        mousePosition = self.inputGraphicsView.mapFromGlobal(mousePosition)
        if event.type() == QtCore.QEvent.KeyPress:
            key = event.key()
            if key == QtCore.Qt.Key_Space:
                self.videoPlaybackWidget.playButtonClicked()
            elif key == QtCore.Qt.Key_A:
                self.videoPlaybackWidget.movePrevButtonClicked()
            elif key == QtCore.Qt.Key_D:
                self.videoPlaybackWidget.moveNextButtonClicked()
            elif key == QtCore.Qt.Key_Down:
                self.inputGraphicsViewScaleDown()
            elif key == QtCore.Qt.Key_Up:
                self.inputGraphicsViewScaleUp()
                pass
            elif key == QtCore.Qt.Key_R:
                self.graphicsViewResized()
            elif key == QtCore.Qt.Key_P:
                pass
                #self.handInputSystem.nextDataFrame()
            elif key == QtCore.Qt.Key_O:
                pass
                #self.handInputSystem.previousDataFrame()
            elif key == QtCore.Qt.Key_J:
                frameNo = self.handInputSystem.getLastInputedFrameIndex()
                self.videoPlaybackWidget.moveToFrame(frameNo)
            elif key == QtCore.Qt.Key_S:
                self.handInputSystem.saveCSV("./a.csv")
        QGraphicsView.keyPressEvent(self.inputGraphicsView, event)
        
    def inputGraphicsViewKeyReleaseEvent(self,event):
        
        QGraphicsView.keyReleaseEvent(self.inputGraphicsView, event)
        
    def inputGraphicsViewwheelEvent(self,event):
        scaleFactor = 1.15
        if event.delta() > 0:
            # Zoom in
            self.inputGraphicsView.scale(scaleFactor, scaleFactor)
        else:
            # Zooming out
            self.inputGraphicsView.scale(1.0 / scaleFactor, 1.0 / scaleFactor)
        QGraphicsView.wheelEvent(self.inputGraphicsView, event)

    def inputGraphicsViewScaleDown(self):
        scaleFactor = 1.15
        self.inputGraphicsView.scale(1.0 / scaleFactor, 1.0 / scaleFactor)
    def inputGraphicsViewScaleUp(self):
        scaleFactor = 1.15
        self.inputGraphicsView.scale(scaleFactor, scaleFactor)
        
    def menuInit(self):
        self.actionSaveCSVFile.triggered.connect(self.saveCSVFile)
        self.actionOpenCSVFile.triggered.connect(self.openCSVFile)

    def openVideoFile(self, activated=False, filePath = None):
        if filePath is None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open Video File', userDir)

        if len(filePath) is not 0:
            self.filePath = filePath

            ret = self.videoPlaybackWidget.openVideo(filePath)
            if ret == False:
                return False
            self.videoInitialFlag = True
            self.videoPlaybackWidget.show()
            self.dataFrameWidget.show()
            # self.evaluate()

            return True
        else:
            return False

    def openImageFile(self, activated=False, filePath = None):
        if filePath == None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open Image File', userDir)

        if len(filePath) is not 0:
            self.filePath = filePath
            img = cv2.imread(filePath)
            if img is None:
                return False

            self.cv_img = img
            self.videoPlaybackWidget.hide()
            self.updateInputGraphicsView()

            self.evaluate()

            return True
        else:
            return False

    def openCSVFile(self, activated=False, filePath=None):
        if filePath is None:
            filePath, _ = QFileDialog.getOpenFileName(None, 'Open CSV File', userDir, 'CSV files (*.csv)')

        if len(filePath) is not 0:
            self.df = pd.read_csv(filePath, index_col=0)
            if self.handInputSystem is not None:
                self.inputScene.removeItem(self.handInputSystem)
            self.handInputSystem = HandInputSystem()
            self.handInputSystem.setRect(self.inputScene.sceneRect())
            self.inputScene.addItem(self.handInputSystem)
            self.handInputSystem.setDataFrame(self.df)
            self.handInputSystem.setPoints()

            self.dataFrameWidget.clear()
            self.dataFrameWidget.dataFrameNo = self.handInputSystem.dataFrameNo
            self.dataFrameWidget.editingNo = 0
            for item in range(self.handInputSystem.dataFrameNo+1):
                color = self.handInputSystem.itemList[item].getColor()
                print(item,color)
                self.dataFrameWidget.colorList.append(color)
            self.dataFrameWidget.setUniqueIDLabel()

            self.evaluate()

    def saveCSVFile(self, activated=False, filePath = None):
        #if self.df is not None:
        if self.handInputSystem.isDataFrame():
            filePath, _ = QFileDialog.getSaveFileName(None, 'Save CSV File', userDir, "CSV files (*.csv)")

            if len(filePath) is not 0:
                logger.debug("Saving CSV file: {0}".format(filePath))
                self.handInputSystem.saveCSV(filePath)

    def updateInputGraphicsView(self):
        # print("update")
        # self.inputScene.clear()
        self.inputScene.removeItem(self.inputPixmapItem)
        qimg = misc.cvMatToQImage(self.cv_img)
        self.inputPixmap = QPixmap.fromImage(qimg)

        p = QPainter(self.inputPixmap)
        sourceRect = self.inputPixmapRenderScene.sceneRect()
        self.inputPixmapRenderScene.render(p, QRectF(sourceRect), QRectF(sourceRect), QtCore.Qt.IgnoreAspectRatio)

        self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
        rect = QtCore.QRectF(self.inputPixmap.rect())
        self.inputScene.setSceneRect(rect)
        self.inputScene.addItem(self.inputPixmapItem)

        self.inputGraphicsView.viewport().update()
        # self.graphicsViewResized()

    def eventFilter(self, obj, event):
        if obj is self.inputGraphicsView.viewport() and event.type()==QEvent.Wheel:
            return True
        else:
            return False

    def graphicsViewResized(self, event=None):
        # print("resize")
        # print(self.inputScene)
        self.inputGraphicsView.fitInView(QtCore.QRectF(self.inputPixmap.rect()), QtCore.Qt.KeepAspectRatio)

    def evaluate(self):
        if not self.videoPlaybackWidget.isOpened():
            return

        qimg = misc.cvMatToQImage(self.cv_img)
        pixmapItem = QGraphicsPixmapItem(QPixmap.fromImage(qimg))
        pixmapItem.setOpacity(0.2)

        self.frameBuffer.put(pixmapItem)
        self.frameBufferItemGroup.addToGroup(pixmapItem)
        if self.frameBuffer.qsize() > 10:
            item = self.frameBuffer.get()
            self.frameBufferItemGroup.removeFromGroup(item)
        """
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setPoints(self.currentFrameNo)
        """

        if self.handInputSystem is not None:
            self.handInputSystem.setPoints(self.currentFrameNo)
            if self.drawingFlag is True:
                mousePosition = QCursor().pos()
                mousePosition = self.inputGraphicsView.mapFromGlobal(mousePosition)
                mousePosition = self.inputGraphicsView.mapToScene(mousePosition)
                pos = [mousePosition.x(),mousePosition.y()]
                self.handInputSystem.appendPosition(pos,self.currentFrameNo)