canvas.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. from math import sqrt
  2. from PyQt4.QtGui import *
  3. from PyQt4.QtCore import *
  4. from PyQt4.QtOpenGL import *
  5. from shape import Shape
  6. # TODO:
  7. # - [maybe] Find optimal epsilon value.
  8. CURSOR_DEFAULT = Qt.ArrowCursor
  9. CURSOR_POINT = Qt.PointingHandCursor
  10. CURSOR_DRAW = Qt.CrossCursor
  11. CURSOR_MOVE = Qt.ClosedHandCursor
  12. CURSOR_GRAB = Qt.OpenHandCursor
  13. #class Canvas(QGLWidget):
  14. class Canvas(QWidget):
  15. zoomRequest = pyqtSignal(int)
  16. scrollRequest = pyqtSignal(int, int)
  17. newShape = pyqtSignal(QPoint)
  18. selectionChanged = pyqtSignal(bool)
  19. shapeMoved = pyqtSignal()
  20. SELECT, EDIT = range(2)
  21. epsilon = 11.0
  22. def __init__(self, *args, **kwargs):
  23. super(Canvas, self).__init__(*args, **kwargs)
  24. # Initialise local state.
  25. self.mode = self.SELECT
  26. self.shapes = []
  27. self.current = None
  28. self.selectedShape=None # save the selected shape here
  29. self.selectedShapeCopy=None
  30. self.lineColor = QColor(0, 0, 255)
  31. self.line = Shape(line_color=self.lineColor)
  32. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  33. self.prevPoint = QPointF()
  34. self.offsets = QPointF(), QPointF()
  35. self.scale = 1.0
  36. self.pixmap = QPixmap()
  37. self.visible = {}
  38. self._hideBackround = False
  39. self.hideBackround = False
  40. self.highlightedShape = None
  41. self._painter = QPainter()
  42. # Menus:
  43. self.menus = (QMenu(), QMenu())
  44. # Set widget options.
  45. self.setMouseTracking(True)
  46. self.setFocusPolicy(Qt.WheelFocus)
  47. def focusOutEvent(self, ev):
  48. self.restoreCursor()
  49. def isVisible(self, shape):
  50. return self.visible.get(shape, True)
  51. def editing(self):
  52. return self.mode == self.EDIT
  53. def setEditing(self, value=True):
  54. self.mode = self.EDIT if value else self.SELECT
  55. def mouseMoveEvent(self, ev):
  56. """Update line with last point and current coordinates."""
  57. pos = self.transformPos(ev.posF())
  58. self.restoreCursor()
  59. # Polygon copy moving.
  60. if Qt.RightButton & ev.buttons():
  61. if self.selectedShapeCopy and self.prevPoint:
  62. self.overrideCursor(CURSOR_MOVE)
  63. self.boundedMoveShape(self.selectedShapeCopy, pos)
  64. self.repaint()
  65. elif self.selectedShape:
  66. self.selectedShapeCopy = self.selectedShape.copy()
  67. self.repaint()
  68. return
  69. # Polygon drawing.
  70. if self.editing():
  71. self.overrideCursor(CURSOR_DRAW)
  72. if self.current and self.editing():
  73. color = self.lineColor
  74. if self.outOfPixmap(pos):
  75. # Don't allow the user to draw outside the pixmap.
  76. # Project the point to the pixmap's edges.
  77. pos = self.intersectionPoint(self.current[-1], pos)
  78. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  79. # Attract line to starting point and colorise to alert the user:
  80. pos = self.current[0]
  81. color = self.current.line_color
  82. self.current.highlightStart = True
  83. self.overrideCursor(CURSOR_POINT)
  84. self.line[1] = pos
  85. self.line.line_color = color
  86. self.repaint()
  87. self.current.highlightStart = False
  88. return
  89. # Polygon moving.
  90. if Qt.LeftButton & ev.buttons() and self.selectedShape and self.prevPoint:
  91. self.overrideCursor(CURSOR_MOVE)
  92. self.boundedMoveShape(self.selectedShape, pos)
  93. self.shapeMoved.emit()
  94. self.repaint()
  95. return
  96. # Just hovering over the canvas:
  97. # Update tooltip value and fill topmost shape.
  98. self.setToolTip("Image")
  99. previous = self.highlightedShape
  100. for shape in reversed(self.shapes):
  101. if shape.containsPoint(pos) and self.isVisible(shape):
  102. self.setToolTip("Object '%s'" % shape.label)
  103. self.highlightedShape = shape
  104. self.overrideCursor(CURSOR_GRAB)
  105. break
  106. else:
  107. self.highlightedShape = None
  108. if previous != self.highlightedShape:
  109. # Try to minimise repaints.
  110. self.repaint()
  111. def mousePressEvent(self, ev):
  112. pos = self.transformPos(ev.posF())
  113. if ev.button() == Qt.LeftButton:
  114. if self.editing():
  115. if self.current:
  116. self.current.addPoint(self.line[1])
  117. self.line[0] = self.current[-1]
  118. if self.current.isClosed():
  119. self.finalise(ev)
  120. elif not self.outOfPixmap(pos):
  121. self.current = Shape()
  122. self.current.addPoint(pos)
  123. self.line.points = [pos, pos]
  124. self.setHiding()
  125. self.repaint()
  126. else:
  127. self.selectShapePoint(pos)
  128. self.prevPoint = pos
  129. self.repaint()
  130. elif ev.button() == Qt.RightButton and not self.editing():
  131. self.selectShapePoint(pos)
  132. self.prevPoint = pos
  133. self.repaint()
  134. def mouseReleaseEvent(self, ev):
  135. pos = self.transformPos(ev.posF())
  136. if ev.button() == Qt.RightButton:
  137. menu = self.menus[bool(self.selectedShapeCopy)]
  138. self.restoreCursor()
  139. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  140. and self.selectedShapeCopy:
  141. # Cancel the move by deleting the shadow copy.
  142. self.selectedShapeCopy = None
  143. self.repaint()
  144. elif ev.button() == Qt.LeftButton and self.selectedShape:
  145. self.overrideCursor(CURSOR_GRAB)
  146. def endMove(self, copy=False):
  147. assert self.selectedShape and self.selectedShapeCopy
  148. shape = self.selectedShapeCopy
  149. #del shape.fill_color
  150. #del shape.line_color
  151. if copy:
  152. self.shapes.append(shape)
  153. self.selectedShape.selected = False
  154. self.selectedShape = shape
  155. self.repaint()
  156. else:
  157. shape.label = self.selectedShape.label
  158. self.deleteSelected()
  159. self.shapes.append(shape)
  160. self.selectedShapeCopy = None
  161. def hideBackroundShapes(self, value):
  162. self.hideBackround = value
  163. if self.selectedShape:
  164. # Only hide other shapes if there is a current selection.
  165. # Otherwise the user will not be able to select a shape.
  166. self.setHiding(True)
  167. self.repaint()
  168. def setHiding(self, enable=True):
  169. self._hideBackround = self.hideBackround if enable else False
  170. def mouseDoubleClickEvent(self, ev):
  171. if self.current and self.editing():
  172. # Shapes need to have at least 3 vertices.
  173. if len(self.current) < 4:
  174. return
  175. # Replace the last point with the starting point.
  176. # We have to do this because the mousePressEvent handler
  177. # adds that point before this handler is called!
  178. self.current[-1] = self.current[0]
  179. self.finalise(ev)
  180. def selectShape(self, shape):
  181. self.deSelectShape()
  182. shape.selected = True
  183. self.selectedShape = shape
  184. self.setHiding()
  185. self.selectionChanged.emit(True)
  186. self.update()
  187. def selectShapePoint(self, point):
  188. """Select the first shape created which contains this point."""
  189. self.deSelectShape()
  190. for shape in reversed(self.shapes):
  191. if self.isVisible(shape) and shape.containsPoint(point):
  192. shape.selected = True
  193. self.selectedShape = shape
  194. self.calculateOffsets(shape, point)
  195. self.setHiding()
  196. self.selectionChanged.emit(True)
  197. return
  198. def calculateOffsets(self, shape, point):
  199. rect = shape.boundingRect()
  200. x1 = rect.x() - point.x()
  201. y1 = rect.y() - point.y()
  202. x2 = (rect.x() + rect.width()) - point.x()
  203. y2 = (rect.y() + rect.height()) - point.y()
  204. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  205. def boundedMoveShape(self, shape, pos):
  206. if self.outOfPixmap(pos):
  207. return # No need to move
  208. o1 = pos + self.offsets[0]
  209. if self.outOfPixmap(o1):
  210. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  211. o2 = pos + self.offsets[1]
  212. if self.outOfPixmap(o2):
  213. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  214. min(0, self.pixmap.height()- o2.y()))
  215. # The next line tracks the new position of the cursor
  216. # relative to the shape, but also results in making it
  217. # a bit "shaky" when nearing the border and allows it to
  218. # go outside of the shape's area for some reason. XXX
  219. #self.calculateOffsets(self.selectedShape, pos)
  220. shape.moveBy(pos - self.prevPoint)
  221. self.prevPoint = pos
  222. def deSelectShape(self):
  223. if self.selectedShape:
  224. self.selectedShape.selected = False
  225. self.selectedShape = None
  226. self.setHiding(False)
  227. self.selectionChanged.emit(False)
  228. self.update()
  229. def deleteSelected(self):
  230. if self.selectedShape:
  231. shape = self.selectedShape
  232. self.shapes.remove(self.selectedShape)
  233. self.selectedShape = None
  234. self.update()
  235. return shape
  236. def copySelectedShape(self):
  237. if self.selectedShape:
  238. shape = self.selectedShape.copy()
  239. self.shapes.append(shape)
  240. self.selectedShape = shape
  241. self.deSelectShape()
  242. return shape
  243. def paintEvent(self, event):
  244. if not self.pixmap:
  245. return super(Canvas, self).paintEvent(event)
  246. p = self._painter
  247. p.begin(self)
  248. p.setRenderHint(QPainter.Antialiasing)
  249. p.setRenderHint(QPainter.HighQualityAntialiasing)
  250. p.setRenderHint(QPainter.SmoothPixmapTransform)
  251. p.scale(self.scale, self.scale)
  252. p.translate(self.offsetToCenter())
  253. p.drawPixmap(0, 0, self.pixmap)
  254. Shape.scale = self.scale
  255. for shape in self.shapes:
  256. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  257. shape.fill = shape.selected or self.highlightedShape == shape
  258. shape.paint(p)
  259. if self.current:
  260. self.current.paint(p)
  261. self.line.paint(p)
  262. if self.selectedShapeCopy:
  263. self.selectedShapeCopy.paint(p)
  264. p.end()
  265. def transformPos(self, point):
  266. """Convert from widget-logical coordinates to painter-logical coordinates."""
  267. return point / self.scale - self.offsetToCenter()
  268. def offsetToCenter(self):
  269. s = self.scale
  270. area = super(Canvas, self).size()
  271. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  272. aw, ah = area.width(), area.height()
  273. x = (aw-w)/(2*s) if aw > w else 0
  274. y = (ah-h)/(2*s) if ah > h else 0
  275. return QPointF(x, y)
  276. def outOfPixmap(self, p):
  277. w, h = self.pixmap.width(), self.pixmap.height()
  278. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  279. def finalise(self, ev):
  280. assert self.current
  281. self.shapes.append(self.current)
  282. self.current = None
  283. self.setEditing(False)
  284. self.setHiding(False)
  285. self.repaint()
  286. self.newShape.emit(self.mapToGlobal(ev.pos()))
  287. def closeEnough(self, p1, p2):
  288. #d = distance(p1 - p2)
  289. #m = (p1-p2).manhattanLength()
  290. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  291. return distance(p1 - p2) < self.epsilon
  292. def intersectionPoint(self, p1, p2):
  293. # Cycle through each image edge in clockwise fashion,
  294. # and find the one intersecting the current line segment.
  295. # http://paulbourke.net/geometry/lineline2d/
  296. size = self.pixmap.size()
  297. points = [(0,0),
  298. (size.width(), 0),
  299. (size.width(), size.height()),
  300. (0, size.height())]
  301. x1, y1 = p1.x(), p1.y()
  302. x2, y2 = p2.x(), p2.y()
  303. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  304. x3, y3 = points[i]
  305. x4, y4 = points[(i+1)%4]
  306. if (x, y) == (x1, y1):
  307. # Handle cases where previous point is on one of the edges.
  308. if x3 == x4:
  309. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  310. else: # y3 == y4
  311. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  312. return QPointF(x, y)
  313. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  314. """For each edge formed by `points', yield the intersection
  315. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  316. Also return the distance of `(x2,y2)' to the middle of the
  317. edge along with its index, so that the one closest can be chosen."""
  318. for i in xrange(4):
  319. x3, y3 = points[i]
  320. x4, y4 = points[(i+1) % 4]
  321. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  322. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  323. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  324. if denom == 0:
  325. # This covers two cases:
  326. # nua == nub == 0: Coincident
  327. # otherwise: Parallel
  328. continue
  329. ua, ub = nua / denom, nub / denom
  330. if 0 <= ua <= 1 and 0 <= ub <= 1:
  331. x = x1 + ua * (x2 - x1)
  332. y = y1 + ua * (y2 - y1)
  333. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  334. d = distance(m - QPointF(x2, y2))
  335. yield d, i, (x, y)
  336. # These two, along with a call to adjustSize are required for the
  337. # scroll area.
  338. def sizeHint(self):
  339. return self.minimumSizeHint()
  340. def minimumSizeHint(self):
  341. if self.pixmap:
  342. return self.scale * self.pixmap.size()
  343. return super(Canvas, self).minimumSizeHint()
  344. def wheelEvent(self, ev):
  345. if ev.orientation() == Qt.Vertical:
  346. mods = ev.modifiers()
  347. if Qt.ControlModifier == int(mods):
  348. self.zoomRequest.emit(ev.delta())
  349. else:
  350. self.scrollRequest.emit(ev.delta(),
  351. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  352. else Qt.Vertical)
  353. else:
  354. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  355. ev.accept()
  356. def keyPressEvent(self, ev):
  357. if ev.key() == Qt.Key_Escape and self.current:
  358. self.current = None
  359. self.repaint()
  360. def setLastLabel(self, text):
  361. assert text
  362. print "shape <- '%s'" % text
  363. self.shapes[-1].label = text
  364. return self.shapes[-1]
  365. def undoLastLine(self):
  366. assert self.shapes
  367. self.current = self.shapes.pop()
  368. pos = self.current.popPoint()
  369. self.line.points = [self.current[-1], pos]
  370. self.setEditing()
  371. def deleteLastShape(self):
  372. assert self.shapes
  373. self.shapes.pop()
  374. def loadPixmap(self, pixmap):
  375. self.pixmap = pixmap
  376. self.shapes = []
  377. self.repaint()
  378. def loadShapes(self, shapes):
  379. self.shapes = list(shapes)
  380. self.current = None
  381. self.repaint()
  382. def copySelectedShape(self):
  383. if self.selectedShape:
  384. newShape=self.selectedShape.copy()
  385. self.shapes.append(newShape)
  386. self.deSelectShape()
  387. self.shapes[-1].selected=True
  388. self.selectedShape=self.shapes[-1]
  389. self.repaint()
  390. return self.selectedShape
  391. def setShapeVisible(self, shape, value):
  392. self.visible[shape] = value
  393. self.repaint()
  394. def overrideCursor(self, cursor):
  395. QApplication.setOverrideCursor(cursor)
  396. def restoreCursor(self):
  397. QApplication.restoreOverrideCursor()
  398. def resetState(self):
  399. self.restoreCursor()
  400. self.pixmap = None
  401. self.update()
  402. def pp(p):
  403. return '%.2f, %.2f' % (p.x(), p.y())
  404. def distance(p):
  405. return sqrt(p.x() * p.x() + p.y() * p.y())