canvas.py 15 KB

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