canvas.py 26 KB

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