canvas.py 14 KB

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