canvas.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. self.repaint()
  122. else:
  123. shape.label = self.selectedShape.label
  124. self.deleteSelected()
  125. self.shapes.append(shape)
  126. self.selectedShapeCopy = None
  127. def hideBackroundShapes(self, value):
  128. self.hideBackround = value
  129. if self.selectedShape:
  130. # Only hide other shapes if there is a current selection.
  131. # Otherwise the user will not be able to select a shape.
  132. self.setHiding(True)
  133. self.repaint()
  134. def setHiding(self, enable=True):
  135. self._hideBackround = self.hideBackround if enable else False
  136. def mouseDoubleClickEvent(self, ev):
  137. if self.current and self.editing():
  138. # Shapes need to have at least 3 vertices.
  139. if len(self.current) < 4:
  140. return
  141. # Replace the last point with the starting point.
  142. # We have to do this because the mousePressEvent handler
  143. # adds that point before this handler is called!
  144. self.current[-1] = self.current[0]
  145. self.finalise(ev)
  146. def selectShape(self, point):
  147. """Select the first shape created which contains this point."""
  148. self.deSelectShape()
  149. for shape in reversed(self.shapes):
  150. if self.isVisible(shape) and shape.containsPoint(point):
  151. shape.selected = True
  152. self.selectedShape = shape
  153. self.calculateOffsets(shape, point)
  154. self.setHiding()
  155. self.selectionChanged.emit(True)
  156. return
  157. def calculateOffsets(self, shape, point):
  158. rect = shape.boundingRect()
  159. x1 = rect.x() - point.x()
  160. y1 = rect.y() - point.y()
  161. x2 = (rect.x() + rect.width()) - point.x()
  162. y2 = (rect.y() + rect.height()) - point.y()
  163. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  164. def boundedMoveShape(self, shape, pos):
  165. if self.outOfPixmap(pos):
  166. return # No need to move
  167. o1 = pos + self.offsets[0]
  168. if self.outOfPixmap(o1):
  169. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  170. o2 = pos + self.offsets[1]
  171. if self.outOfPixmap(o2):
  172. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  173. min(0, self.pixmap.height()- o2.y()))
  174. # The next line tracks the new position of the cursor
  175. # relative to the shape, but also results in making it
  176. # a bit "shaky" when nearing the border and allows it to
  177. # go outside of the shape's area for some reason. XXX
  178. #self.calculateOffsets(self.selectedShape, pos)
  179. shape.moveBy(pos - self.prevPoint)
  180. self.prevPoint = pos
  181. def deSelectShape(self):
  182. if self.selectedShape:
  183. self.selectedShape.selected = False
  184. self.selectedShape = None
  185. self.setHiding(False)
  186. self.repaint()
  187. self.selectionChanged.emit(False)
  188. def deleteSelected(self):
  189. if self.selectedShape:
  190. shape = self.selectedShape
  191. self.shapes.remove(self.selectedShape)
  192. self.selectedShape = None
  193. self.repaint()
  194. return shape
  195. def copySelectedShape(self):
  196. if self.selectedShape:
  197. shape = self.selectedShape.copy()
  198. self.shapes.append(shape)
  199. self.selectedShape = shape
  200. self.deSelectShape()
  201. self.repaint()
  202. return shape
  203. def paintEvent(self, event):
  204. if not self.pixmap:
  205. return super(Canvas, self).paintEvent(event)
  206. p = QPainter()
  207. p.begin(self)
  208. p.setRenderHint(QPainter.Antialiasing)
  209. p.scale(self.scale, self.scale)
  210. p.translate(self.offsetToCenter())
  211. p.drawPixmap(0, 0, self.pixmap)
  212. Shape.scale = self.scale
  213. for shape in self.shapes:
  214. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  215. shape.paint(p)
  216. if self.current:
  217. self.current.paint(p)
  218. self.line.paint(p)
  219. if self.selectedShapeCopy:
  220. self.selectedShapeCopy.paint(p)
  221. p.end()
  222. def transformPos(self, point):
  223. """Convert from widget-logical coordinates to painter-logical coordinates."""
  224. return point / self.scale - self.offsetToCenter()
  225. def offsetToCenter(self):
  226. s = self.scale
  227. area = super(Canvas, self).size()
  228. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  229. aw, ah = area.width(), area.height()
  230. x = (aw-w)/(2*s) if aw > w else 0
  231. y = (ah-h)/(2*s) if ah > h else 0
  232. return QPointF(x, y)
  233. def outOfPixmap(self, p):
  234. w, h = self.pixmap.width(), self.pixmap.height()
  235. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  236. def finalise(self, ev):
  237. assert self.current
  238. self.current.fill = True
  239. self.shapes.append(self.current)
  240. self.current = None
  241. self.setEditing(False)
  242. self.setHiding(False)
  243. self.repaint()
  244. self.newShape.emit(self.mapToGlobal(ev.pos()))
  245. def closeEnough(self, p1, p2):
  246. #d = distance(p1 - p2)
  247. #m = (p1-p2).manhattanLength()
  248. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  249. return distance(p1 - p2) < self.epsilon
  250. def intersectionPoint(self, p1, p2):
  251. # Cycle through each image edge in clockwise fashion,
  252. # and find the one intersecting the current line segment.
  253. # http://paulbourke.net/geometry/lineline2d/
  254. size = self.pixmap.size()
  255. points = [(0,0),
  256. (size.width(), 0),
  257. (size.width(), size.height()),
  258. (0, size.height())]
  259. x1, y1 = p1.x(), p1.y()
  260. x2, y2 = p2.x(), p2.y()
  261. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  262. x3, y3 = points[i]
  263. x4, y4 = points[(i+1)%4]
  264. if (x, y) == (x1, y1):
  265. # Handle cases where previous point is on one of the edges.
  266. if x3 == x4:
  267. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  268. else: # y3 == y4
  269. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  270. return QPointF(x, y)
  271. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  272. """For each edge formed by `points', yield the intersection
  273. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  274. Also return the distance of `(x2,y2)' to the middle of the
  275. edge along with its index, so that the one closest can be chosen."""
  276. for i in xrange(4):
  277. x3, y3 = points[i]
  278. x4, y4 = points[(i+1) % 4]
  279. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  280. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  281. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  282. if denom == 0:
  283. # This covers two cases:
  284. # nua == nub == 0: Coincident
  285. # otherwise: Parallel
  286. continue
  287. ua, ub = nua / denom, nub / denom
  288. if 0 <= ua <= 1 and 0 <= ub <= 1:
  289. x = x1 + ua * (x2 - x1)
  290. y = y1 + ua * (y2 - y1)
  291. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  292. d = distance(m - QPointF(x2, y2))
  293. yield d, i, (x, y)
  294. # These two, along with a call to adjustSize are required for the
  295. # scroll area.
  296. def sizeHint(self):
  297. return self.minimumSizeHint()
  298. def minimumSizeHint(self):
  299. if self.pixmap:
  300. return self.scale * self.pixmap.size()
  301. return super(Canvas, self).minimumSizeHint()
  302. def wheelEvent(self, ev):
  303. if ev.orientation() == Qt.Vertical:
  304. mods = ev.modifiers()
  305. if Qt.ControlModifier == int(mods):
  306. self.zoomRequest.emit(ev.delta())
  307. else:
  308. self.scrollRequest.emit(ev.delta(),
  309. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  310. else Qt.Vertical)
  311. else:
  312. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  313. ev.accept()
  314. def keyPressEvent(self, ev):
  315. if ev.key() == Qt.Key_Escape and self.current:
  316. self.current = None
  317. self.repaint()
  318. def setLastLabel(self, text):
  319. assert text
  320. print "shape <- '%s'" % text
  321. self.shapes[-1].label = text
  322. return self.shapes[-1]
  323. def undoLastLine(self):
  324. assert self.shapes
  325. self.current = self.shapes.pop()
  326. self.current.fill = False
  327. pos = self.current.popPoint()
  328. self.line.points = [self.current[-1], pos]
  329. self.setEditing()
  330. def deleteLastShape(self):
  331. assert self.shapes
  332. self.shapes.pop()
  333. def loadPixmap(self, pixmap):
  334. self.pixmap = pixmap
  335. self.shapes = []
  336. self.repaint()
  337. def loadShapes(self, shapes):
  338. self.shapes = list(shapes)
  339. self.current = None
  340. self.repaint()
  341. def copySelectedShape(self):
  342. if self.selectedShape:
  343. newShape=self.selectedShape.copy()
  344. self.shapes.append(newShape)
  345. self.deSelectShape()
  346. self.shapes[-1].selected=True
  347. self.selectedShape=self.shapes[-1]
  348. self.repaint()
  349. return self.selectedShape
  350. def setShapeVisible(self, shape, value):
  351. self.visible[shape] = value
  352. self.repaint()
  353. def pp(p):
  354. return '%.2f, %.2f' % (p.x(), p.y())
  355. def distance(p):
  356. return sqrt(p.x() * p.x() + p.y() * p.y())