canvas.py 36.2 KB
Newer Older
qq_25193841's avatar
qq_25193841 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
# Copyright (c) <2015-Present> Tzutalin
# Copyright (C) 2013  MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
# William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction, including without
# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

try:
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
except ImportError:
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *

#from PyQt4.QtOpenGL import *

from libs.shape import Shape
from libs.utils import distance

CURSOR_DEFAULT = Qt.ArrowCursor
CURSOR_POINT = Qt.PointingHandCursor
CURSOR_DRAW = Qt.CrossCursor
CURSOR_MOVE = Qt.ClosedHandCursor
CURSOR_GRAB = Qt.OpenHandCursor

# class Canvas(QGLWidget):


class Canvas(QWidget):
    zoomRequest = pyqtSignal(int)
    scrollRequest = pyqtSignal(int, int)
    newShape = pyqtSignal()
40 41
    # selectionChanged = pyqtSignal(bool)
    selectionChanged = pyqtSignal(list)
qq_25193841's avatar
qq_25193841 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
    shapeMoved = pyqtSignal()
    drawingPolygon = pyqtSignal(bool)

    CREATE, EDIT = list(range(2))
    _fill_drawing = False # draw shadows

    epsilon = 11.0

    def __init__(self, *args, **kwargs):
        super(Canvas, self).__init__(*args, **kwargs)
        # Initialise local state.
        self.mode = self.EDIT
        self.shapes = []
55
        self.shapesBackups = []
qq_25193841's avatar
qq_25193841 已提交
56
        self.current = None
57
        self.selectedShapes = []
qq_25193841's avatar
qq_25193841 已提交
58
        self.selectedShape = None  # save the selected shape here
59
        self.selectedShapesCopy = []
qq_25193841's avatar
qq_25193841 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        self.drawingLineColor = QColor(0, 0, 255)
        self.drawingRectColor = QColor(0, 0, 255)
        self.line = Shape(line_color=self.drawingLineColor)
        self.prevPoint = QPointF()
        self.offsets = QPointF(), QPointF()
        self.scale = 1.0
        self.pixmap = QPixmap()
        self.visible = {}
        self._hideBackround = False
        self.hideBackround = False
        self.hShape = None
        self.hVertex = None
        self._painter = QPainter()
        self._cursor = CURSOR_DEFAULT
        # Menus:
        self.menus = (QMenu(), QMenu())
        # Set widget options.
        self.setMouseTracking(True)
        self.setFocusPolicy(Qt.WheelFocus)
        self.verified = False
        self.drawSquare = False
        self.fourpoint = True # ADD
        self.pointnum = 0
83
        self.movingShape = False
qq_25193841's avatar
qq_25193841 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

        #initialisation for panning
        self.pan_initial_pos = QPoint()

    def setDrawingColor(self, qColor):
        self.drawingLineColor = qColor
        self.drawingRectColor = qColor

    def enterEvent(self, ev):
        self.overrideCursor(self._cursor)

    def leaveEvent(self, ev):
        self.restoreCursor()

    def focusOutEvent(self, ev):
        self.restoreCursor()

    def isVisible(self, shape):
        return self.visible.get(shape, True)

    def drawing(self):
        return self.mode == self.CREATE

    def editing(self):
        return self.mode == self.EDIT

    def setEditing(self, value=True):
        self.mode = self.EDIT if value else self.CREATE
        if not value:  # Create
            self.unHighlight()
            self.deSelectShape()
        self.prevPoint = QPointF()
        self.repaint()

    def unHighlight(self):
        if self.hShape:
            self.hShape.highlightClear()
        self.hVertex = self.hShape = None

    def selectedVertex(self):
        return self.hVertex is not None


    def mouseMoveEvent(self, ev):
        """Update line with last point and current coordinates."""
        pos = self.transformPos(ev.pos())

        # Update coordinates in status bar if image is opened
        window = self.parent().window()
        if window.filePath is not None:
            self.parent().window().labelCoordinates.setText(
                'X: %d; Y: %d' % (pos.x(), pos.y()))

        # Polygon drawing.
        if self.drawing():
            self.overrideCursor(CURSOR_DRAW) # ?
            if self.current:
                # Display annotation width and height while drawing
                currentWidth = abs(self.current[0].x() - pos.x())
                currentHeight = abs(self.current[0].y() - pos.y())
                self.parent().window().labelCoordinates.setText(
                        'Width: %d, Height: %d / X: %d; Y: %d' % (currentWidth, currentHeight, pos.x(), pos.y()))

                color = self.drawingLineColor
                if self.outOfPixmap(pos):
                    # Don't allow the user to draw outside the pixmap.
                    # Clip the coordinates to 0 or max,
                    # if they are outside the range [0, max]
                    size = self.pixmap.size()
                    clipped_x = min(max(0, pos.x()), size.width())
                    clipped_y = min(max(0, pos.y()), size.height())
                    pos = QPointF(clipped_x, clipped_y)
156 157

                elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):# and not self.fourpoint:
qq_25193841's avatar
qq_25193841 已提交
158 159 160 161 162 163
                    # Attract line to starting point and colorise to alert the
                    # user:
                    pos = self.current[0]
                    color = self.current.line_color
                    self.overrideCursor(CURSOR_POINT)
                    self.current.highlightVertex(0, Shape.NEAR_VERTEX)
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
                # elif ( # ADD # 合并上下代码 内容一样
                #         len(self.current) > 1
                #         and self.fourpoint
                #         and self.closeEnough(pos, self.current[0])
                # ):
                #     # Attract line to starting point and
                #     # colorise to alert the user.
                #     pos = self.current[0]
                #     self.overrideCursor(CURSOR_POINT)
                #     self.current.highlightVertex(0, Shape.NEAR_VERTEX)


                if self.drawSquare: # 这部分不同
                    # initPos = self.current[0] # 原先代码
                    # minX = initPos.x()
                    # minY = initPos.y()
                    # min_size = min(abs(pos.x() - minX), abs(pos.y() - minY))
                    # directionX = -1 if pos.x() - minX < 0 else 1
                    # directionY = -1 if pos.y() - minY < 0 else 1
                    # self.line[1] = QPointF(minX + directionX * min_size, minY + directionY * min_size)

                    self.line.points = [self.current[0], pos] # Labelme代码
                    self.line.close()
qq_25193841's avatar
qq_25193841 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

                elif self.fourpoint:
                    # self.line[self.pointnum] = pos # OLD
                    self.line[0] = self.current[-1]
                    self.line[1] = pos

                else:
                    self.line[1] = pos # pos is the mouse's current position

                self.line.line_color = color
                self.prevPoint = QPointF() # ?
                self.current.highlightClear()
            else:
                self.prevPoint = pos
            self.repaint()
            return
203
        # 一下都相同
qq_25193841's avatar
qq_25193841 已提交
204 205
        # Polygon copy moving.
        if Qt.RightButton & ev.buttons():
206
            if self.selectedShapesCopy and self.prevPoint:
qq_25193841's avatar
qq_25193841 已提交
207
                self.overrideCursor(CURSOR_MOVE)
208
                self.boundedMoveShape(self.selectedShapesCopy, pos)
qq_25193841's avatar
qq_25193841 已提交
209
                self.repaint()
210 211 212 213
            elif self.selectedShapes:
                self.selectedShapesCopy = [
                    s.copy() for s in self.selectedShapes
                ]
qq_25193841's avatar
qq_25193841 已提交
214 215 216 217 218 219 220
                self.repaint()
            return

        # Polygon/Vertex moving.
        if Qt.LeftButton & ev.buttons():
            if self.selectedVertex():
                self.boundedMoveVertex(pos)
221
                self.shapeMoved.emit() # 同时选中时的移动
qq_25193841's avatar
qq_25193841 已提交
222
                self.repaint()
223 224
                self.movingShape = True
            elif self.selectedShapes and self.prevPoint:
qq_25193841's avatar
qq_25193841 已提交
225
                self.overrideCursor(CURSOR_MOVE)
226
                self.boundedMoveShape(self.selectedShapes, pos)
qq_25193841's avatar
qq_25193841 已提交
227 228
                self.shapeMoved.emit()
                self.repaint()
229 230
                self.movingShape = True
            else: # TODO 这部分是多的
qq_25193841's avatar
qq_25193841 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                #pan
                delta_x = pos.x() - self.pan_initial_pos.x()
                delta_y = pos.y() - self.pan_initial_pos.y()
                self.scrollRequest.emit(delta_x, Qt.Horizontal)
                self.scrollRequest.emit(delta_y, Qt.Vertical)
                self.update()
            return

        # Just hovering over the canvas, 2 posibilities:
        # - Highlight shapes
        # - Highlight vertex
        # Update shape/vertex fill and tooltip value accordingly.
        self.setToolTip("Image")
        for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
            # Look for a nearby vertex to highlight. If that fails,
            # check if we happen to be inside a shape.
            index = shape.nearestVertex(pos, self.epsilon)
            if index is not None:
                if self.selectedVertex():
                    self.hShape.highlightClear()
251 252
                # TODO: Pre部分的变量都没有
                self.hVertex, self.hShape = index, shape # 倒着来的原因是要更新hShape的值?
qq_25193841's avatar
qq_25193841 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                shape.highlightVertex(index, shape.MOVE_VERTEX)
                self.overrideCursor(CURSOR_POINT)
                self.setToolTip("Click & drag to move point")
                self.setStatusTip(self.toolTip())
                self.update()
                break
            elif shape.containsPoint(pos):
                if self.selectedVertex():
                    self.hShape.highlightClear()
                self.hVertex, self.hShape = None, shape
                self.setToolTip(
                    "Click & drag to move shape '%s'" % shape.label)
                self.setStatusTip(self.toolTip())
                self.overrideCursor(CURSOR_GRAB)
                self.update()
                break
        else:  # Nothing found, clear highlights, reset state.
            if self.hShape:
                self.hShape.highlightClear()
                self.update()
            self.hVertex, self.hShape = None, None
            self.overrideCursor(CURSOR_DEFAULT)

    def mousePressEvent(self, ev):
        pos = self.transformPos(ev.pos())
        if ev.button() == Qt.LeftButton:
            if self.drawing():
                # self.handleDrawing(pos) # OLD
281 282 283 284 285 286 287 288 289 290 291 292
                if self.current:
                    if self.fourpoint: # ADD IF
                        # Add point to existing shape.
                        # print('Adding points in mousePressEvent is ', self.line[1])
                        self.current.addPoint(self.line[1])
                        self.line[0] = self.current[-1]
                        if self.current.isClosed():
                            # print('1111')
                            self.finalise()
                    elif self.drawSquare: # 增加
                        assert len(self.current.points) == 1
                        self.current.points = self.line.points
qq_25193841's avatar
qq_25193841 已提交
293 294 295
                        self.finalise()
                elif not self.outOfPixmap(pos):
                    # Create new shape.
296
                    self.current = Shape()# self.current = Shape(shape_type=self.createMode) # TODO: 有可能需要制定类型?
qq_25193841's avatar
qq_25193841 已提交
297 298 299 300 301 302 303 304 305 306 307
                    self.current.addPoint(pos)
                    # if self.createMode == "point":
                    #     self.finalise()
                    # else:
                    #     if self.createMode == "circle":
                    #         self.current.shape_type = "circle"
                    self.line.points = [pos, pos]
                    self.setHiding()
                    self.drawingPolygon.emit(True)
                    self.update()

308 309 310 311 312 313 314 315 316 317
            else: # 改动后可以增加多选框,选点方式从单点变成list
                # selection = self.selectShapePoint(pos)
                # self.prevPoint = pos
                #
                # if selection is None:
                #     #pan
                #     QApplication.setOverrideCursor(QCursor(Qt.OpenHandCursor))
                #     self.pan_initial_pos = pos
                group_mode = int(ev.modifiers()) == Qt.ControlModifier
                self.selectShapePoint(pos, multiple_selection_mode=group_mode)
qq_25193841's avatar
qq_25193841 已提交
318
                self.prevPoint = pos
319 320
                self.pan_initial_pos = pos
                # self.repaint()
qq_25193841's avatar
qq_25193841 已提交
321 322

        elif ev.button() == Qt.RightButton and self.editing():
323 324 325 326
            # self.selectShapePoint(pos)
            # self.prevPoint = pos
            group_mode = int(ev.modifiers()) == Qt.ControlModifier
            self.selectShapePoint(pos, multiple_selection_mode=group_mode)
qq_25193841's avatar
qq_25193841 已提交
327
            self.prevPoint = pos
328
            # self.repaint() # 只用update?
qq_25193841's avatar
qq_25193841 已提交
329 330 331 332
        self.update()

    def mouseReleaseEvent(self, ev):
        if ev.button() == Qt.RightButton:
333
            menu = self.menus[bool(self.selectedShapesCopy)]
qq_25193841's avatar
qq_25193841 已提交
334 335
            self.restoreCursor()
            if not menu.exec_(self.mapToGlobal(ev.pos()))\
336
               and self.selectedShapesCopy:
qq_25193841's avatar
qq_25193841 已提交
337
                # Cancel the move by deleting the shadow copy.
338 339
                # self.selectedShapeCopy = None
                self.selectedShapesCopy = []
qq_25193841's avatar
qq_25193841 已提交
340
                self.repaint()
341 342
        # elif ev.button() == Qt.LeftButton and self.selectedShape: # OLD
        elif ev.button() == Qt.LeftButton and self.selectedShapes:
qq_25193841's avatar
qq_25193841 已提交
343 344 345 346 347
            if self.selectedVertex():
                self.overrideCursor(CURSOR_POINT)
            else:
                self.overrideCursor(CURSOR_GRAB)

348
        elif ev.button() == Qt.LeftButton and not self.fourpoint: # 暂时去除四点部分的代码
qq_25193841's avatar
qq_25193841 已提交
349 350
            pos = self.transformPos(ev.pos())
            if self.drawing():
351
                self.handleDrawing(pos) # 关键函数
qq_25193841's avatar
qq_25193841 已提交
352 353 354 355
            else:
                #pan
                QApplication.restoreOverrideCursor() # ?

356 357 358 359 360 361 362 363 364 365 366
        if self.movingShape and self.hShape: # 加上之后会移动点会崩 用于撤回
             index = self.shapes.index(self.hShape)
             if (
                 self.shapesBackups[-1][index].points # 如果新建的框位置变化
                 != self.shapes[index].points
             ):
                 self.storeShapes() # 重新backup一下
                 self.shapeMoved.emit() # 连接updateBoxlist

             self.movingShape = False

qq_25193841's avatar
qq_25193841 已提交
367 368

    def endMove(self, copy=False):
369 370
        # assert self.selectedShape and self.selectedShapeCopy
        # shape = self.selectedShapeCopy
qq_25193841's avatar
qq_25193841 已提交
371 372
        #del shape.fill_color
        #del shape.line_color
373 374 375 376 377 378 379 380 381 382
        # if copy:
        #     self.shapes.append(shape)
        #     self.selectedShape.selected = False
        #     self.selectedShape = shape
        #     self.repaint()
        # else:
        #     self.selectedShape.points = [p for p in shape.points]
        # self.selectedShapeCopy = None
        assert self.selectedShapes and self.selectedShapesCopy
        assert len(self.selectedShapesCopy) == len(self.selectedShapes)
qq_25193841's avatar
qq_25193841 已提交
383
        if copy:
384 385 386 387
            for i, shape in enumerate(self.selectedShapesCopy):
                self.shapes.append(shape)
                self.selectedShapes[i].selected = False
                self.selectedShapes[i] = shape
qq_25193841's avatar
qq_25193841 已提交
388
        else:
389 390 391 392 393 394
            for i, shape in enumerate(self.selectedShapesCopy):
                self.selectedShapes[i].points = shape.points
        self.selectedShapesCopy = []
        self.repaint()
        self.storeShapes()
        return True
qq_25193841's avatar
qq_25193841 已提交
395 396 397

    def hideBackroundShapes(self, value):
        self.hideBackround = value
398
        if self.selectedShapes:
qq_25193841's avatar
qq_25193841 已提交
399 400 401 402 403
            # Only hide other shapes if there is a current selection.
            # Otherwise the user will not be able to select a shape.
            self.setHiding(True)
            self.repaint()

404
    def handleDrawing(self, pos): # 没有此函数
qq_25193841's avatar
qq_25193841 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        if self.current and self.current.reachMaxPoints() is False:
            if self.fourpoint:
                targetPos = self.line[self.pointnum]
                self.current.addPoint(targetPos)
                print('current points in handleDrawing is ', self.line[self.pointnum])
                self.update()
                if self.pointnum == 3:
                    self.finalise()

            else: # 按住送掉后跳到这里
                initPos = self.current[0]
                print('initPos', self.current[0])
                minX = initPos.x()
                minY = initPos.y()
                targetPos = self.line[1]
                maxX = targetPos.x()
                maxY = targetPos.y()
                self.current.addPoint(QPointF(maxX, minY))
                self.current.addPoint(targetPos)
                self.current.addPoint(QPointF(minX, maxY))
                self.finalise()

        elif not self.outOfPixmap(pos):
            print('release')
            self.current = Shape()
            self.current.addPoint(pos)
            self.line.points = [pos, pos]
            self.setHiding()
            self.drawingPolygon.emit(True)
            self.update()

    def setHiding(self, enable=True):
        self._hideBackround = self.hideBackround if enable else False

    def canCloseShape(self):
        return self.drawing() and self.current and len(self.current) > 2

    def mouseDoubleClickEvent(self, ev):
        # We need at least 4 points here, since the mousePress handler
        # adds an extra one before this handler is called.
        if self.canCloseShape() and len(self.current) > 3:
            if not self.fourpoint:
                self.current.popPoint()
            self.finalise()

450 451 452 453 454 455 456 457
    def selectShapes(self, shapes):
        # self.deSelectShape()
        # shape.selected = True
        # self.selectedShape = shape
        # self.setHiding()
        # self.selectionChanged.emit(True)
        # self.update()
        for s in shapes: s.seleted = True
qq_25193841's avatar
qq_25193841 已提交
458
        self.setHiding()
459
        self.selectionChanged.emit(shapes)
qq_25193841's avatar
qq_25193841 已提交
460 461
        self.update()

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    # def selectShapePoint(self, point):
    #     """Select the first shape created which contains this point."""
    #     self.deSelectShape()
    #     if self.selectedVertex():  # A vertex is marked for selection.
    #         index, shape = self.hVertex, self.hShape
    #         shape.highlightVertex(index, shape.MOVE_VERTEX)
    #         self.selectShape(shape)
    #         return self.hVertex
    #     for shape in reversed(self.shapes):
    #         if self.isVisible(shape) and shape.containsPoint(point):
    #             self.selectShape(shape) # 函数
    #             self.calculateOffsets(shape, point)
    #             return self.selectedShape
    #     return None

    def selectShapePoint(self, point, multiple_selection_mode):
qq_25193841's avatar
qq_25193841 已提交
478 479 480
        """Select the first shape created which contains this point."""
        if self.selectedVertex():  # A vertex is marked for selection.
            index, shape = self.hVertex, self.hShape
481 482
            shape.highlightVertex(index, shape.MOVE_VERTEX) # 突出显示

qq_25193841's avatar
qq_25193841 已提交
483
            return self.hVertex
484 485 486 487 488 489 490 491 492 493 494 495 496 497
        else:
            for shape in reversed(self.shapes):
                if self.isVisible(shape) and shape.containsPoint(point):
                    self.calculateOffsets(shape, point)
                    self.setHiding()
                    if multiple_selection_mode:
                        if shape not in self.selectedShapes: # list TODO:为什么是2个,刚开始应该是1个
                            self.selectionChanged.emit(
                                self.selectedShapes + [shape] # 选择+未选择
                            )
                    else:
                        self.selectionChanged.emit([shape])
                    return
        self.deSelectShape()
qq_25193841's avatar
qq_25193841 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

    def calculateOffsets(self, shape, point):
        rect = shape.boundingRect()
        x1 = rect.x() - point.x()
        y1 = rect.y() - point.y()
        x2 = (rect.x() + rect.width()) - point.x()
        y2 = (rect.y() + rect.height()) - point.y()
        self.offsets = QPointF(x1, y1), QPointF(x2, y2)

    def snapPointToCanvas(self, x, y):
        """
        Moves a point x,y to within the boundaries of the canvas.
        :return: (x,y,snapped) where snapped is True if x or y were changed, False if not.
        """
        if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height():
            x = max(x, 0)
            y = max(y, 0)
            x = min(x, self.pixmap.width())
            y = min(y, self.pixmap.height())
            return x, y, True

        return x, y, False

    def boundedMoveVertex(self, pos):
        index, shape = self.hVertex, self.hShape
        point = shape[index]
        if self.outOfPixmap(pos):
            size = self.pixmap.size()
            clipped_x = min(max(0, pos.x()), size.width())
            clipped_y = min(max(0, pos.y()), size.height())
            pos = QPointF(clipped_x, clipped_y)

        if self.drawSquare:
            opposite_point_index = (index + 2) % 4
            opposite_point = shape[opposite_point_index]

            min_size = min(abs(pos.x() - opposite_point.x()), abs(pos.y() - opposite_point.y()))
            directionX = -1 if pos.x() - opposite_point.x() < 0 else 1
            directionY = -1 if pos.y() - opposite_point.y() < 0 else 1
            shiftPos = QPointF(opposite_point.x() + directionX * min_size - point.x(),
                               opposite_point.y() + directionY * min_size - point.y())
        else:
            shiftPos = pos - point

542 543 544 545 546 547 548 549 550 551 552 553 554 555
        if shape[0].x()==shape[3].x() and shape[1].x()==shape[2].x() and shape[0].y()==shape[1].y():
            shape.moveVertexBy(index, shiftPos)
            lindex = (index + 1) % 4
            rindex = (index + 3) % 4
            lshift = None
            rshift = None
            if index % 2 == 0:
                rshift = QPointF(shiftPos.x(), 0)
                lshift = QPointF(0, shiftPos.y())
            else:
                lshift = QPointF(shiftPos.x(), 0)
                rshift = QPointF(0, shiftPos.y())
            shape.moveVertexBy(rindex, rshift)
            shape.moveVertexBy(lindex, lshift)
qq_25193841's avatar
qq_25193841 已提交
556 557

        else:
558 559
            shape.moveVertexBy(index, shiftPos)

qq_25193841's avatar
qq_25193841 已提交
560

561
    def boundedMoveShape(self, shapes, pos):
qq_25193841's avatar
qq_25193841 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
        if self.outOfPixmap(pos):
            return False  # No need to move
        o1 = pos + self.offsets[0]
        if self.outOfPixmap(o1):
            pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
        o2 = pos + self.offsets[1]
        if self.outOfPixmap(o2):
            pos += QPointF(min(0, self.pixmap.width() - o2.x()),
                           min(0, self.pixmap.height() - o2.y()))
        # The next line tracks the new position of the cursor
        # relative to the shape, but also results in making it
        # a bit "shaky" when nearing the border and allows it to
        # go outside of the shape's area for some reason. XXX
        #self.calculateOffsets(self.selectedShape, pos)
        dp = pos - self.prevPoint
        if dp:
578 579
            for shape in shapes:
                shape.moveBy(dp)
qq_25193841's avatar
qq_25193841 已提交
580 581 582 583 584
            self.prevPoint = pos
            return True
        return False

    def deSelectShape(self):
585 586 587 588 589 590 591 592 593
        # if self.selectedShape:
        #     self.selectedShape.selected = False
        #     self.selectedShape = None
        #     self.setHiding(False)
        #     self.selectionChanged.emit(False)
        #     self.update()
        if self.selectedShapes:
            # TODO:少了两个清空?
            for shape in self.selectedShapes: shape.selected=False
qq_25193841's avatar
qq_25193841 已提交
594
            self.setHiding(False)
595
            self.selectionChanged.emit([])
qq_25193841's avatar
qq_25193841 已提交
596 597
            self.update()

598 599 600 601 602 603 604 605
    # def deleteSelected(self):
    #     if self.selectedShape:
    #         shape = self.selectedShape
    #         self.shapes.remove(self.selectedShape)
    #         self.selectedShape = None
    #         self.update()
    #         return shape

qq_25193841's avatar
qq_25193841 已提交
606
    def deleteSelected(self):
607 608 609 610 611 612 613 614 615
        deleted_shapes = []
        if self.selectedShapes:
            #self.storeShapes()
            for shape in self.selectedShapes:
                self.shapes.remove(shape)
                #self.shapesBackups.append(shape)
                deleted_shapes.append(shape)
            self.storeShapes() # 这里应该是先储存
            self.selectedShapes = []
qq_25193841's avatar
qq_25193841 已提交
616
            self.update()
617 618 619 620 621 622 623 624 625
        return deleted_shapes

    def storeShapes(self):
        shapesBackup = []
        for shape in self.shapes:
            shapesBackup.append(shape.copy())
        if len(self.shapesBackups) >= 10:
            self.shapesBackups = self.shapesBackups[-9:]
        self.shapesBackups.append(shapesBackup) # 每删除或保存一次都会backup一次
qq_25193841's avatar
qq_25193841 已提交
626 627

    def copySelectedShape(self):
628 629 630 631 632 633 634 635 636 637 638 639 640
        # if self.selectedShape:
        #     shape = self.selectedShape.copy()
        #     self.deSelectShape()
        #     self.shapes.append(shape)
        #     shape.selected = True
        #     self.selectedShape = shape
        #     self.boundedShiftShape(shape)
        #     return shape
        if self.selectedShapes:
            self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
            self.boundedShiftShapes(self.selectedShapesCopy)
            self.endMove(copy=True)
        return self.selectedShapes
qq_25193841's avatar
qq_25193841 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673

    def boundedShiftShape(self, shape):
        # Try to move in one direction, and if it fails in another.
        # Give up if both fail.
        point = shape[0]
        offset = QPointF(2.0, 2.0)
        self.calculateOffsets(shape, point)
        self.prevPoint = point
        if not self.boundedMoveShape(shape, point - offset):
            self.boundedMoveShape(shape, point + offset)

    def paintEvent(self, event):
        if not self.pixmap:
            return super(Canvas, self).paintEvent(event)

        p = self._painter
        p.begin(self)
        p.setRenderHint(QPainter.Antialiasing)
        p.setRenderHint(QPainter.HighQualityAntialiasing)
        p.setRenderHint(QPainter.SmoothPixmapTransform)

        p.scale(self.scale, self.scale)
        p.translate(self.offsetToCenter())

        p.drawPixmap(0, 0, self.pixmap)
        Shape.scale = self.scale
        for shape in self.shapes:
            if (shape.selected or not self._hideBackround) and self.isVisible(shape):
                shape.fill = shape.selected or shape == self.hShape
                shape.paint(p)
        if self.current:
            self.current.paint(p)
            self.line.paint(p)
674 675 676
        if self.selectedShapesCopy:
            for s in self.selectedShapesCopy:
                s.paint(p)
qq_25193841's avatar
qq_25193841 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803

        # Paint rect
        if self.current is not None and len(self.line) == 2 and not self.fourpoint:
            # print('Drawing rect')
            leftTop = self.line[0]
            rightBottom = self.line[1]
            rectWidth = rightBottom.x() - leftTop.x()
            rectHeight = rightBottom.y() - leftTop.y()
            p.setPen(self.drawingRectColor)
            brush = QBrush(Qt.BDiagPattern)
            p.setBrush(brush)
            p.drawRect(leftTop.x(), leftTop.y(), rectWidth, rectHeight)


        # ADD:
        if (
                self.fillDrawing()
                and self.fourpoint
                and self.current is not None
                and len(self.current.points) >= 2
        ):
            print('paint event')
            drawing_shape = self.current.copy()
            drawing_shape.addPoint(self.line[1])
            drawing_shape.fill = True
            drawing_shape.paint(p)

        if self.drawing() and not self.prevPoint.isNull() and not self.outOfPixmap(self.prevPoint):
            p.setPen(QColor(0, 0, 0))
            p.drawLine(self.prevPoint.x(), 0, self.prevPoint.x(), self.pixmap.height())
            p.drawLine(0, self.prevPoint.y(), self.pixmap.width(), self.prevPoint.y())

        self.setAutoFillBackground(True)
        if self.verified:
            pal = self.palette()
            pal.setColor(self.backgroundRole(), QColor(184, 239, 38, 128))
            self.setPalette(pal)
        else:
            pal = self.palette()
            pal.setColor(self.backgroundRole(), QColor(232, 232, 232, 255))
            self.setPalette(pal)

        p.end()

    def fillDrawing(self):
        return self._fill_drawing

    def transformPos(self, point):
        """Convert from widget-logical coordinates to painter-logical coordinates."""
        return point / self.scale - self.offsetToCenter()

    def offsetToCenter(self):
        s = self.scale
        area = super(Canvas, self).size()
        w, h = self.pixmap.width() * s, self.pixmap.height() * s
        aw, ah = area.width(), area.height()
        x = (aw - w) / (2 * s) if aw > w else 0
        y = (ah - h) / (2 * s) if ah > h else 0
        return QPointF(x, y)

    def outOfPixmap(self, p):
        w, h = self.pixmap.width(), self.pixmap.height()
        return not (0 <= p.x() <= w and 0 <= p.y() <= h)

    def finalise(self):
        assert self.current
        if self.current.points[0] == self.current.points[-1]:
            # print('finalse')
            self.current = None
            self.drawingPolygon.emit(False)
            self.update()
            return

        self.current.close()
        self.shapes.append(self.current)
        self.current = None
        self.setHiding(False)
        self.newShape.emit()
        self.update()

    def closeEnough(self, p1, p2):
        #d = distance(p1 - p2)
        #m = (p1-p2).manhattanLength()
        # print "d %.2f, m %d, %.2f" % (d, m, d - m)
        return distance(p1 - p2) < self.epsilon

    # These two, along with a call to adjustSize are required for the
    # scroll area.
    def sizeHint(self):
        return self.minimumSizeHint()

    def minimumSizeHint(self):
        if self.pixmap:
            return self.scale * self.pixmap.size()
        return super(Canvas, self).minimumSizeHint()

    def wheelEvent(self, ev):
        qt_version = 4 if hasattr(ev, "delta") else 5
        if qt_version == 4:
            if ev.orientation() == Qt.Vertical:
                v_delta = ev.delta()
                h_delta = 0
            else:
                h_delta = ev.delta()
                v_delta = 0
        else:
            delta = ev.angleDelta()
            h_delta = delta.x()
            v_delta = delta.y()

        mods = ev.modifiers()
        if Qt.ControlModifier == int(mods) and v_delta:
            self.zoomRequest.emit(v_delta)
        else:
            v_delta and self.scrollRequest.emit(v_delta, Qt.Vertical)
            h_delta and self.scrollRequest.emit(h_delta, Qt.Horizontal)
        ev.accept()

    def keyPressEvent(self, ev):
        key = ev.key()
        if key == Qt.Key_Escape and self.current:
            print('ESC press')
            self.current = None
            self.drawingPolygon.emit(False)
            self.update()
        elif key == Qt.Key_Return and self.canCloseShape():
            self.finalise()
804 805 806 807 808 809 810 811
        # elif key == Qt.Key_Left and self.selectedShape:
        #     self.moveOnePixel('Left')
        # elif key == Qt.Key_Right and self.selectedShape:
        #     self.moveOnePixel('Right')
        # elif key == Qt.Key_Up and self.selectedShape:
        #     self.moveOnePixel('Up')
        # elif key == Qt.Key_Down and self.selectedShape:
        #     self.moveOnePixel('Down')
qq_25193841's avatar
qq_25193841 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853

    def moveOnePixel(self, direction):
        # print(self.selectedShape.points)
        if direction == 'Left' and not self.moveOutOfBound(QPointF(-1.0, 0)):
            # print("move Left one pixel")
            self.selectedShape.points[0] += QPointF(-1.0, 0)
            self.selectedShape.points[1] += QPointF(-1.0, 0)
            self.selectedShape.points[2] += QPointF(-1.0, 0)
            self.selectedShape.points[3] += QPointF(-1.0, 0)
        elif direction == 'Right' and not self.moveOutOfBound(QPointF(1.0, 0)):
            # print("move Right one pixel")
            self.selectedShape.points[0] += QPointF(1.0, 0)
            self.selectedShape.points[1] += QPointF(1.0, 0)
            self.selectedShape.points[2] += QPointF(1.0, 0)
            self.selectedShape.points[3] += QPointF(1.0, 0)
        elif direction == 'Up' and not self.moveOutOfBound(QPointF(0, -1.0)):
            # print("move Up one pixel")
            self.selectedShape.points[0] += QPointF(0, -1.0)
            self.selectedShape.points[1] += QPointF(0, -1.0)
            self.selectedShape.points[2] += QPointF(0, -1.0)
            self.selectedShape.points[3] += QPointF(0, -1.0)
        elif direction == 'Down' and not self.moveOutOfBound(QPointF(0, 1.0)):
            # print("move Down one pixel")
            self.selectedShape.points[0] += QPointF(0, 1.0)
            self.selectedShape.points[1] += QPointF(0, 1.0)
            self.selectedShape.points[2] += QPointF(0, 1.0)
            self.selectedShape.points[3] += QPointF(0, 1.0)
        self.shapeMoved.emit()
        self.repaint()

    def moveOutOfBound(self, step):
        points = [p1+p2 for p1, p2 in zip(self.selectedShape.points, [step]*4)]
        return True in map(self.outOfPixmap, points)

    def setLastLabel(self, text, line_color  = None, fill_color = None):
        assert text
        self.shapes[-1].label = text
        if line_color:
            self.shapes[-1].line_color = line_color

        if fill_color:
            self.shapes[-1].fill_color = fill_color
854 855
        #self.shapesBackups.pop() # 新建shape后要pop?
        self.storeShapes()
qq_25193841's avatar
qq_25193841 已提交
856 857 858 859 860 861 862 863 864 865

        return self.shapes[-1]

    def undoLastLine(self):
        assert self.shapes
        self.current = self.shapes.pop()
        self.current.setOpen()
        self.line.points = [self.current[-1], self.current[0]]
        self.drawingPolygon.emit(True)

866 867 868 869 870 871 872 873 874 875 876
    def undoLastPoint(self):
        if not self.current or self.current.isClosed():
            return
        self.current.popPoint()
        if len(self.current) > 0:
            self.line[0] = self.current[-1]
        else:
            self.current = None
            self.drawingPolygon.emit(False)
        self.repaint()

qq_25193841's avatar
qq_25193841 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889
    def resetAllLines(self):
        assert self.shapes
        self.current = self.shapes.pop()
        self.current.setOpen()
        self.line.points = [self.current[-1], self.current[0]]
        self.drawingPolygon.emit(True)
        self.current = None
        self.drawingPolygon.emit(False)
        self.update()

    def loadPixmap(self, pixmap):
        self.pixmap = pixmap
        self.shapes = []
890
        self.repaint()
qq_25193841's avatar
qq_25193841 已提交
891

892 893 894 895 896
    def loadShapes(self, shapes, replace=True):
        if replace:
            self.shapes = list(shapes)
        else:
            self.shapes.extend(shapes)
qq_25193841's avatar
qq_25193841 已提交
897
        self.current = None
898 899 900 901
        self.hShape = None
        self.hVertex = None
        # self.hEdge = None
        self.storeShapes()
qq_25193841's avatar
qq_25193841 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
        self.repaint()

    def setShapeVisible(self, shape, value):
        self.visible[shape] = value
        self.repaint()

    def currentCursor(self):
        cursor = QApplication.overrideCursor()
        if cursor is not None:
            cursor = cursor.shape()
        return cursor

    def overrideCursor(self, cursor):
        self._cursor = cursor
        if self.currentCursor() is None:
            QApplication.setOverrideCursor(cursor)
        else:
            QApplication.changeOverrideCursor(cursor)

    def restoreCursor(self):
        QApplication.restoreOverrideCursor()

    def resetState(self):
        self.restoreCursor()
        self.pixmap = None
        self.update()
928
        self.shapesBackups = []
qq_25193841's avatar
qq_25193841 已提交
929 930 931

    def setDrawingShapeToSquare(self, status):
        self.drawSquare = status
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949

    def restoreShape(self): # 用于撤销
        if not self.isShapeRestorable:
            return
        self.shapesBackups.pop()  # latest
        shapesBackup = self.shapesBackups.pop()
        self.shapes = shapesBackup
        #self.shapes.append(self.shapesBackups.pop()) # 为何这里之前是只将back赋值呢
        self.selectedShapes = []
        for shape in self.shapes:
            shape.selected = False
        self.repaint()

    @property
    def isShapeRestorable(self):
        if len(self.shapesBackups) < 2:
            return False
        return True