canvas.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. from qtpy import QtCore
  2. from qtpy import QtGui
  3. from qtpy import QtWidgets
  4. from labelme import QT5
  5. from labelme.shape import Shape
  6. import labelme.utils
  7. # TODO(unknown):
  8. # - [maybe] Find optimal epsilon value.
  9. CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
  10. CURSOR_POINT = QtCore.Qt.PointingHandCursor
  11. CURSOR_DRAW = QtCore.Qt.CrossCursor
  12. CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
  13. CURSOR_GRAB = QtCore.Qt.OpenHandCursor
  14. class Canvas(QtWidgets.QWidget):
  15. zoomRequest = QtCore.Signal(int, QtCore.QPoint)
  16. scrollRequest = QtCore.Signal(int, int)
  17. newShape = QtCore.Signal()
  18. selectionChanged = QtCore.Signal(list)
  19. shapeMoved = QtCore.Signal()
  20. drawingPolygon = QtCore.Signal(bool)
  21. edgeSelected = QtCore.Signal(bool)
  22. CREATE, EDIT = 0, 1
  23. # polygon, rectangle, line, or point
  24. _createMode = 'polygon'
  25. _fill_drawing = False
  26. def __init__(self, *args, **kwargs):
  27. self.epsilon = kwargs.pop('epsilon', 10.0)
  28. super(Canvas, self).__init__(*args, **kwargs)
  29. # Initialise local state.
  30. self.mode = self.EDIT
  31. self.shapes = []
  32. self.shapesBackups = []
  33. self.current = None
  34. self.selectedShapes = [] # save the selected shapes here
  35. self.selectedShapesCopy = []
  36. self.lineColor = QtGui.QColor(0, 0, 255)
  37. # self.line represents:
  38. # - createMode == 'polygon': edge from last point to current
  39. # - createMode == 'rectangle': diagonal line of the rectangle
  40. # - createMode == 'line': the line
  41. # - createMode == 'point': the point
  42. self.line = Shape(line_color=self.lineColor)
  43. self.prevPoint = QtCore.QPoint()
  44. self.prevMovePoint = QtCore.QPoint()
  45. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  46. self.scale = 1.0
  47. self.pixmap = QtGui.QPixmap()
  48. self.visible = {}
  49. self._hideBackround = False
  50. self.hideBackround = False
  51. self.hShape = None
  52. self.hVertex = None
  53. self.hEdge = None
  54. self.movingShape = False
  55. self._painter = QtGui.QPainter()
  56. self._cursor = CURSOR_DEFAULT
  57. # Menus:
  58. # 0: right-click, 1: ctrl+right-click
  59. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  60. # Set widget options.
  61. self.setMouseTracking(True)
  62. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  63. def fillDrawing(self):
  64. return self._fill_drawing
  65. def setFillDrawing(self, value):
  66. self._fill_drawing = value
  67. @property
  68. def createMode(self):
  69. return self._createMode
  70. @createMode.setter
  71. def createMode(self, value):
  72. if value not in ['polygon', 'rectangle', 'circle',
  73. 'line', 'point', 'linestrip']:
  74. raise ValueError('Unsupported createMode: %s' % value)
  75. self._createMode = value
  76. def storeShapes(self):
  77. shapesBackup = []
  78. for shape in self.shapes:
  79. shapesBackup.append(shape.copy())
  80. if len(self.shapesBackups) >= 10:
  81. self.shapesBackups = self.shapesBackups[-9:]
  82. self.shapesBackups.append(shapesBackup)
  83. @property
  84. def isShapeRestorable(self):
  85. if len(self.shapesBackups) < 2:
  86. return False
  87. return True
  88. def restoreShape(self):
  89. if not self.isShapeRestorable:
  90. return
  91. self.shapesBackups.pop() # latest
  92. shapesBackup = self.shapesBackups.pop()
  93. self.shapes = shapesBackup
  94. self.selectedShapes = []
  95. for shape in self.shapes:
  96. shape.selected = False
  97. self.repaint()
  98. def enterEvent(self, ev):
  99. self.overrideCursor(self._cursor)
  100. def leaveEvent(self, ev):
  101. self.restoreCursor()
  102. def focusOutEvent(self, ev):
  103. self.restoreCursor()
  104. def isVisible(self, shape):
  105. return self.visible.get(shape, True)
  106. def drawing(self):
  107. return self.mode == self.CREATE
  108. def editing(self):
  109. return self.mode == self.EDIT
  110. def setEditing(self, value=True):
  111. self.mode = self.EDIT if value else self.CREATE
  112. if not value: # Create
  113. self.unHighlight()
  114. self.deSelectShape()
  115. def unHighlight(self):
  116. if self.hShape:
  117. self.hShape.highlightClear()
  118. self.hVertex = self.hShape = None
  119. def selectedVertex(self):
  120. return self.hVertex is not None
  121. def mouseMoveEvent(self, ev):
  122. """Update line with last point and current coordinates."""
  123. try:
  124. if QT5:
  125. pos = self.transformPos(ev.localPos())
  126. else:
  127. pos = self.transformPos(ev.posF())
  128. except AttributeError:
  129. return
  130. self.prevMovePoint = pos
  131. self.restoreCursor()
  132. # Polygon drawing.
  133. if self.drawing():
  134. self.line.shape_type = self.createMode
  135. self.overrideCursor(CURSOR_DRAW)
  136. if not self.current:
  137. return
  138. color = self.lineColor
  139. if self.outOfPixmap(pos):
  140. # Don't allow the user to draw outside the pixmap.
  141. # Project the point to the pixmap's edges.
  142. pos = self.intersectionPoint(self.current[-1], pos)
  143. elif len(self.current) > 1 and self.createMode == 'polygon' and\
  144. self.closeEnough(pos, self.current[0]):
  145. # Attract line to starting point and
  146. # colorise to alert the user.
  147. pos = self.current[0]
  148. color = self.current.line_color
  149. self.overrideCursor(CURSOR_POINT)
  150. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  151. if self.createMode in ['polygon', 'linestrip']:
  152. self.line[0] = self.current[-1]
  153. self.line[1] = pos
  154. elif self.createMode == 'rectangle':
  155. self.line.points = [self.current[0], pos]
  156. self.line.close()
  157. elif self.createMode == 'circle':
  158. self.line.points = [self.current[0], pos]
  159. self.line.shape_type = "circle"
  160. elif self.createMode == 'line':
  161. self.line.points = [self.current[0], pos]
  162. self.line.close()
  163. elif self.createMode == 'point':
  164. self.line.points = [self.current[0]]
  165. self.line.close()
  166. self.line.line_color = color
  167. self.repaint()
  168. self.current.highlightClear()
  169. return
  170. # Polygon copy moving.
  171. if QtCore.Qt.RightButton & ev.buttons():
  172. if self.selectedShapesCopy and self.prevPoint:
  173. self.overrideCursor(CURSOR_MOVE)
  174. self.boundedMoveShapes(self.selectedShapesCopy, pos)
  175. self.repaint()
  176. elif self.selectedShapes:
  177. self.selectedShapesCopy = \
  178. [s.copy() for s in self.selectedShapes]
  179. self.repaint()
  180. return
  181. # Polygon/Vertex moving.
  182. self.movingShape = False
  183. if QtCore.Qt.LeftButton & ev.buttons():
  184. if self.selectedVertex():
  185. self.boundedMoveVertex(pos)
  186. self.repaint()
  187. self.movingShape = True
  188. elif self.selectedShapes and self.prevPoint:
  189. self.overrideCursor(CURSOR_MOVE)
  190. self.boundedMoveShapes(self.selectedShapes, pos)
  191. self.repaint()
  192. self.movingShape = True
  193. return
  194. # Just hovering over the canvas, 2 posibilities:
  195. # - Highlight shapes
  196. # - Highlight vertex
  197. # Update shape/vertex fill and tooltip value accordingly.
  198. self.setToolTip("Image")
  199. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  200. # Look for a nearby vertex to highlight. If that fails,
  201. # check if we happen to be inside a shape.
  202. index = shape.nearestVertex(pos, self.epsilon / self.scale)
  203. index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
  204. if index is not None:
  205. if self.selectedVertex():
  206. self.hShape.highlightClear()
  207. self.hVertex = index
  208. self.hShape = shape
  209. self.hEdge = index_edge
  210. shape.highlightVertex(index, shape.MOVE_VERTEX)
  211. self.overrideCursor(CURSOR_POINT)
  212. self.setToolTip("Click & drag to move point")
  213. self.setStatusTip(self.toolTip())
  214. self.update()
  215. break
  216. elif shape.containsPoint(pos):
  217. if self.selectedVertex():
  218. self.hShape.highlightClear()
  219. self.hVertex = None
  220. self.hShape = shape
  221. self.hEdge = index_edge
  222. self.setToolTip(
  223. "Click & drag to move shape '%s'" % shape.label)
  224. self.setStatusTip(self.toolTip())
  225. self.overrideCursor(CURSOR_GRAB)
  226. self.update()
  227. break
  228. else: # Nothing found, clear highlights, reset state.
  229. if self.hShape:
  230. self.hShape.highlightClear()
  231. self.update()
  232. self.hVertex, self.hShape, self.hEdge = None, None, None
  233. self.edgeSelected.emit(self.hEdge is not None)
  234. def addPointToEdge(self):
  235. if (self.hShape is None and
  236. self.hEdge is None and
  237. self.prevMovePoint is None):
  238. return
  239. shape = self.hShape
  240. index = self.hEdge
  241. point = self.prevMovePoint
  242. shape.insertPoint(index, point)
  243. shape.highlightVertex(index, shape.MOVE_VERTEX)
  244. self.hShape = shape
  245. self.hVertex = index
  246. self.hEdge = None
  247. def mousePressEvent(self, ev):
  248. if QT5:
  249. pos = self.transformPos(ev.localPos())
  250. else:
  251. pos = self.transformPos(ev.posF())
  252. if ev.button() == QtCore.Qt.LeftButton:
  253. if self.drawing():
  254. if self.current:
  255. # Add point to existing shape.
  256. if self.createMode == 'polygon':
  257. self.current.addPoint(self.line[1])
  258. self.line[0] = self.current[-1]
  259. if self.current.isClosed():
  260. self.finalise()
  261. elif self.createMode in ['rectangle', 'circle', 'line']:
  262. assert len(self.current.points) == 1
  263. self.current.points = self.line.points
  264. self.finalise()
  265. elif self.createMode == 'linestrip':
  266. self.current.addPoint(self.line[1])
  267. self.line[0] = self.current[-1]
  268. if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
  269. self.finalise()
  270. elif not self.outOfPixmap(pos):
  271. # Create new shape.
  272. self.current = Shape(shape_type=self.createMode)
  273. self.current.addPoint(pos)
  274. if self.createMode == 'point':
  275. self.finalise()
  276. else:
  277. if self.createMode == 'circle':
  278. self.current.shape_type = 'circle'
  279. self.line.points = [pos, pos]
  280. self.setHiding()
  281. self.drawingPolygon.emit(True)
  282. self.update()
  283. else:
  284. group_mode = (int(ev.modifiers()) == QtCore.Qt.ControlModifier)
  285. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  286. self.prevPoint = pos
  287. self.repaint()
  288. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  289. group_mode = (int(ev.modifiers()) == QtCore.Qt.ControlModifier)
  290. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  291. self.prevPoint = pos
  292. self.repaint()
  293. def mouseReleaseEvent(self, ev):
  294. if ev.button() == QtCore.Qt.RightButton:
  295. menu = self.menus[len(self.selectedShapesCopy) > 0]
  296. self.restoreCursor()
  297. if not menu.exec_(self.mapToGlobal(ev.pos())) \
  298. and self.selectedShapesCopy:
  299. # Cancel the move by deleting the shadow copy.
  300. self.selectedShapesCopy = []
  301. self.repaint()
  302. elif ev.button() == QtCore.Qt.LeftButton and self.selectedShapes:
  303. self.overrideCursor(CURSOR_GRAB)
  304. if self.movingShape:
  305. self.storeShapes()
  306. self.shapeMoved.emit()
  307. def endMove(self, copy):
  308. assert self.selectedShapes and self.selectedShapesCopy
  309. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  310. # del shape.fill_color
  311. # del shape.line_color
  312. if copy:
  313. for i, shape in enumerate(self.selectedShapesCopy):
  314. self.shapes.append(shape)
  315. self.selectedShapes[i].selected = False
  316. self.selectedShapes[i] = shape
  317. else:
  318. for i, shape in enumerate(self.selectedShapesCopy):
  319. self.selectedShapes[i].points = shape.points
  320. self.selectedShapesCopy = []
  321. self.repaint()
  322. self.storeShapes()
  323. return True
  324. def hideBackroundShapes(self, value):
  325. self.hideBackround = value
  326. if self.selectedShapes:
  327. # Only hide other shapes if there is a current selection.
  328. # Otherwise the user will not be able to select a shape.
  329. self.setHiding(True)
  330. self.repaint()
  331. def setHiding(self, enable=True):
  332. self._hideBackround = self.hideBackround if enable else False
  333. def canCloseShape(self):
  334. return self.drawing() and self.current and len(self.current) > 2
  335. def mouseDoubleClickEvent(self, ev):
  336. # We need at least 4 points here, since the mousePress handler
  337. # adds an extra one before this handler is called.
  338. if self.canCloseShape() and len(self.current) > 3:
  339. self.current.popPoint()
  340. self.finalise()
  341. def selectShapes(self, shapes):
  342. self.setHiding()
  343. self.selectionChanged.emit(shapes)
  344. self.update()
  345. def selectShapePoint(self, point, multiple_selection_mode):
  346. """Select the first shape created which contains this point."""
  347. if self.selectedVertex(): # A vertex is marked for selection.
  348. index, shape = self.hVertex, self.hShape
  349. shape.highlightVertex(index, shape.MOVE_VERTEX)
  350. else:
  351. for shape in reversed(self.shapes):
  352. if self.isVisible(shape) and shape.containsPoint(point):
  353. self.calculateOffsets(shape, point)
  354. self.setHiding()
  355. if multiple_selection_mode:
  356. if shape not in self.selectedShapes:
  357. self.selectionChanged.emit(
  358. self.selectedShapes + [shape])
  359. else:
  360. self.selectionChanged.emit([shape])
  361. return
  362. self.deSelectShape()
  363. def calculateOffsets(self, shape, point):
  364. rect = shape.boundingRect()
  365. x1 = rect.x() - point.x()
  366. y1 = rect.y() - point.y()
  367. x2 = (rect.x() + rect.width() - 1) - point.x()
  368. y2 = (rect.y() + rect.height() - 1) - point.y()
  369. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  370. def boundedMoveVertex(self, pos):
  371. index, shape = self.hVertex, self.hShape
  372. point = shape[index]
  373. if self.outOfPixmap(pos):
  374. pos = self.intersectionPoint(point, pos)
  375. shape.moveVertexBy(index, pos - point)
  376. def boundedMoveShapes(self, shapes, pos):
  377. if self.outOfPixmap(pos):
  378. return False # No need to move
  379. o1 = pos + self.offsets[0]
  380. if self.outOfPixmap(o1):
  381. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  382. o2 = pos + self.offsets[1]
  383. if self.outOfPixmap(o2):
  384. pos += QtCore.QPoint(min(0, self.pixmap.width() - o2.x()),
  385. min(0, self.pixmap.height() - o2.y()))
  386. # XXX: The next line tracks the new position of the cursor
  387. # relative to the shape, but also results in making it
  388. # a bit "shaky" when nearing the border and allows it to
  389. # go outside of the shape's area for some reason.
  390. # self.calculateOffsets(self.selectedShapes, pos)
  391. dp = pos - self.prevPoint
  392. if dp:
  393. for shape in shapes:
  394. shape.moveBy(dp)
  395. self.prevPoint = pos
  396. return True
  397. return False
  398. def deSelectShape(self):
  399. if self.selectedShapes:
  400. self.setHiding(False)
  401. self.selectionChanged.emit([])
  402. self.update()
  403. def deleteSelected(self):
  404. deleted_shapes = []
  405. if self.selectedShapes:
  406. for shape in self.selectedShapes:
  407. self.shapes.remove(shape)
  408. deleted_shapes.append(shape)
  409. self.storeShapes()
  410. self.selectedShapes = []
  411. self.update()
  412. return deleted_shapes
  413. def copySelectedShapes(self):
  414. if self.selectedShapes:
  415. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  416. self.boundedShiftShapes(self.selectedShapesCopy)
  417. self.endMove(copy=True)
  418. return self.selectedShapes
  419. def boundedShiftShapes(self, shapes):
  420. # Try to move in one direction, and if it fails in another.
  421. # Give up if both fail.
  422. point = shapes[0][0]
  423. offset = QtCore.QPoint(2.0, 2.0)
  424. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  425. self.prevPoint = point
  426. if not self.boundedMoveShapes(shapes, point - offset):
  427. self.boundedMoveShapes(shapes, point + offset)
  428. def paintEvent(self, event):
  429. if not self.pixmap:
  430. return super(Canvas, self).paintEvent(event)
  431. p = self._painter
  432. p.begin(self)
  433. p.setRenderHint(QtGui.QPainter.Antialiasing)
  434. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  435. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  436. p.scale(self.scale, self.scale)
  437. p.translate(self.offsetToCenter())
  438. p.drawPixmap(0, 0, self.pixmap)
  439. Shape.scale = self.scale
  440. for shape in self.shapes:
  441. if (shape.selected or not self._hideBackround) and \
  442. self.isVisible(shape):
  443. shape.fill = shape.selected or shape == self.hShape
  444. shape.paint(p)
  445. if self.current:
  446. self.current.paint(p)
  447. self.line.paint(p)
  448. if self.selectedShapesCopy:
  449. for s in self.selectedShapesCopy:
  450. s.paint(p)
  451. if (self.fillDrawing() and self.createMode == 'polygon' and
  452. self.current is not None and len(self.current.points) >= 2):
  453. drawing_shape = self.current.copy()
  454. drawing_shape.addPoint(self.line[1])
  455. drawing_shape.fill = True
  456. drawing_shape.fill_color.setAlpha(64)
  457. drawing_shape.paint(p)
  458. p.end()
  459. def transformPos(self, point):
  460. """Convert from widget-logical coordinates to painter-logical ones."""
  461. return point / self.scale - self.offsetToCenter()
  462. def offsetToCenter(self):
  463. s = self.scale
  464. area = super(Canvas, self).size()
  465. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  466. aw, ah = area.width(), area.height()
  467. x = (aw - w) / (2 * s) if aw > w else 0
  468. y = (ah - h) / (2 * s) if ah > h else 0
  469. return QtCore.QPoint(x, y)
  470. def outOfPixmap(self, p):
  471. w, h = self.pixmap.width(), self.pixmap.height()
  472. return not (0 <= p.x() < w and 0 <= p.y() < h)
  473. def finalise(self):
  474. assert self.current
  475. self.current.close()
  476. self.shapes.append(self.current)
  477. self.storeShapes()
  478. self.current = None
  479. self.setHiding(False)
  480. self.newShape.emit()
  481. self.update()
  482. def closeEnough(self, p1, p2):
  483. # d = distance(p1 - p2)
  484. # m = (p1-p2).manhattanLength()
  485. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  486. # divide by scale to allow more precision when zoomed in
  487. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  488. def intersectionPoint(self, p1, p2):
  489. # Cycle through each image edge in clockwise fashion,
  490. # and find the one intersecting the current line segment.
  491. # http://paulbourke.net/geometry/lineline2d/
  492. size = self.pixmap.size()
  493. points = [(0, 0),
  494. (size.width() - 1, 0),
  495. (size.width() - 1, size.height() - 1),
  496. (0, size.height() - 1)]
  497. x1, y1 = p1.x(), p1.y()
  498. x2, y2 = p2.x(), p2.y()
  499. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  500. x3, y3 = points[i]
  501. x4, y4 = points[(i + 1) % 4]
  502. if (x, y) == (x1, y1):
  503. # Handle cases where previous point is on one of the edges.
  504. if x3 == x4:
  505. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  506. else: # y3 == y4
  507. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  508. return QtCore.QPoint(x, y)
  509. def intersectingEdges(self, point1, point2, points):
  510. """Find intersecting edges.
  511. For each edge formed by `points', yield the intersection
  512. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  513. Also return the distance of `(x2,y2)' to the middle of the
  514. edge along with its index, so that the one closest can be chosen.
  515. """
  516. (x1, y1) = point1
  517. (x2, y2) = point2
  518. for i in range(4):
  519. x3, y3 = points[i]
  520. x4, y4 = points[(i + 1) % 4]
  521. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  522. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  523. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  524. if denom == 0:
  525. # This covers two cases:
  526. # nua == nub == 0: Coincident
  527. # otherwise: Parallel
  528. continue
  529. ua, ub = nua / denom, nub / denom
  530. if 0 <= ua <= 1 and 0 <= ub <= 1:
  531. x = x1 + ua * (x2 - x1)
  532. y = y1 + ua * (y2 - y1)
  533. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  534. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  535. yield d, i, (x, y)
  536. # These two, along with a call to adjustSize are required for the
  537. # scroll area.
  538. def sizeHint(self):
  539. return self.minimumSizeHint()
  540. def minimumSizeHint(self):
  541. if self.pixmap:
  542. return self.scale * self.pixmap.size()
  543. return super(Canvas, self).minimumSizeHint()
  544. def wheelEvent(self, ev):
  545. if QT5:
  546. mods = ev.modifiers()
  547. delta = ev.angleDelta()
  548. if QtCore.Qt.ControlModifier == int(mods):
  549. # with Ctrl/Command key
  550. # zoom
  551. self.zoomRequest.emit(delta.y(), ev.pos())
  552. else:
  553. # scroll
  554. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  555. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  556. else:
  557. if ev.orientation() == QtCore.Qt.Vertical:
  558. mods = ev.modifiers()
  559. if QtCore.Qt.ControlModifier == int(mods):
  560. # with Ctrl/Command key
  561. self.zoomRequest.emit(ev.delta(), ev.pos())
  562. else:
  563. self.scrollRequest.emit(
  564. ev.delta(),
  565. QtCore.Qt.Horizontal
  566. if (QtCore.Qt.ShiftModifier == int(mods))
  567. else QtCore.Qt.Vertical)
  568. else:
  569. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  570. ev.accept()
  571. def keyPressEvent(self, ev):
  572. key = ev.key()
  573. if key == QtCore.Qt.Key_Escape and self.current:
  574. self.current = None
  575. self.drawingPolygon.emit(False)
  576. self.update()
  577. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  578. self.finalise()
  579. def setLastLabel(self, text, flags):
  580. assert text
  581. self.shapes[-1].label = text
  582. self.shapes[-1].flags = flags
  583. self.shapesBackups.pop()
  584. self.storeShapes()
  585. return self.shapes[-1]
  586. def undoLastLine(self):
  587. assert self.shapes
  588. self.current = self.shapes.pop()
  589. self.current.setOpen()
  590. if self.createMode in ['polygon', 'linestrip']:
  591. self.line.points = [self.current[-1], self.current[0]]
  592. elif self.createMode in ['rectangle', 'line', 'circle']:
  593. self.current.points = self.current.points[0:1]
  594. elif self.createMode == 'point':
  595. self.current = None
  596. self.drawingPolygon.emit(True)
  597. def undoLastPoint(self):
  598. if not self.current or self.current.isClosed():
  599. return
  600. self.current.popPoint()
  601. if len(self.current) > 0:
  602. self.line[0] = self.current[-1]
  603. else:
  604. self.current = None
  605. self.drawingPolygon.emit(False)
  606. self.repaint()
  607. def loadPixmap(self, pixmap):
  608. self.pixmap = pixmap
  609. self.shapes = []
  610. self.repaint()
  611. def loadShapes(self, shapes, replace=True):
  612. if replace:
  613. self.shapes = list(shapes)
  614. else:
  615. self.shapes.extend(shapes)
  616. self.storeShapes()
  617. self.current = None
  618. self.repaint()
  619. def setShapeVisible(self, shape, value):
  620. self.visible[shape] = value
  621. self.repaint()
  622. def overrideCursor(self, cursor):
  623. self.restoreCursor()
  624. self._cursor = cursor
  625. QtWidgets.QApplication.setOverrideCursor(cursor)
  626. def restoreCursor(self):
  627. QtWidgets.QApplication.restoreOverrideCursor()
  628. def resetState(self):
  629. self.restoreCursor()
  630. self.pixmap = None
  631. self.shapesBackups = []
  632. self.update()