canvas.py 15 KB

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