canvas.py 14 KB

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