canvas.py 14 KB

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