canvas.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. SELECT, EDIT = range(2)
  10. epsilon = 9.0 # TODO: Tune value
  11. def __init__(self, *args, **kwargs):
  12. super(Canvas, self).__init__(*args, **kwargs)
  13. # Initialise local state.
  14. self.mode = self.SELECT
  15. self.shapes = []
  16. self.current = None
  17. self.selectedShape=None # save the selected shape here
  18. self.selectedShapeCopy=None
  19. self.lineColor = QColor(0, 0, 255)
  20. self.line = Shape(line_color=self.lineColor)
  21. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  22. self.prevPoint = QPointF()
  23. self.offsets = QPointF(), QPointF()
  24. self.scale = 1.0
  25. self.pixmap = None
  26. self.hideShapesWhenNew=False
  27. # Set widget options.
  28. self.setMouseTracking(True)
  29. self.setFocusPolicy(Qt.WheelFocus)
  30. def editing(self):
  31. return self.mode == self.EDIT
  32. def setEditing(self, value=True):
  33. self.mode = self.EDIT if value else self.SELECT
  34. def mouseMoveEvent(self, ev):
  35. """Update line with last point and current coordinates."""
  36. pos = self.transformPos(ev.posF())
  37. # Polygon copy moving.
  38. if ev.button() == Qt.RightButton:
  39. if self.selectedShapeCopy:
  40. if self.prevPoint:
  41. self.selectedShapeCopy.moveBy(pos - self.prevPoint)
  42. self.repaint()
  43. self.prevPoint = pos
  44. elif self.selectedShape:
  45. self.selectedShapeCopy = self.selectedShape.copy()
  46. self.repaint()
  47. return
  48. # Polygon drawing.
  49. if self.current and self.editing():
  50. color = self.lineColor
  51. if self.outOfPixmap(pos):
  52. # Don't allow the user to draw outside the pixmap.
  53. # Project the point to the pixmap's edges.
  54. pos = self.intersectionPoint(self.current[-1], pos)
  55. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  56. # Attract line to starting point and colorise to alert the user:
  57. # TODO: I would also like to highlight the pixel somehow.
  58. pos = self.current[0]
  59. color = self.current.line_color
  60. self.line[1] = pos
  61. self.line.line_color = color
  62. self.repaint()
  63. # Polygon moving.
  64. elif self.selectedShape and self.prevPoint:
  65. self.boundedMoveShape(pos)
  66. self.repaint()
  67. def mousePressEvent(self, ev):
  68. pos = self.transformPos(ev.posF())
  69. if ev.button() == Qt.LeftButton:
  70. if self.editing():
  71. if self.current:
  72. self.current.addPoint(self.line[1])
  73. self.line[0] = self.current[-1]
  74. if self.current.isClosed():
  75. self.finalise(ev)
  76. else:
  77. if self.outOfPixmap(pos):
  78. return
  79. self.current = Shape()
  80. self.setMouseTracking(True)
  81. self.line.points = [pos, pos]
  82. self.current.addPoint(pos)
  83. else:
  84. self.selectShape(pos)
  85. self.prevPoint = pos
  86. self.repaint()
  87. #elif ev.button() == Qt.RightButton and not self.editing():
  88. # self.selectShape(pos)
  89. # self.prevPoint = pos
  90. def mouseDoubleClickEvent(self, ev):
  91. # FIXME: Don't create shape with 2 vertices only.
  92. if self.current and self.editing():
  93. # Add first point in the list so that it is consistent
  94. # with shapes created the normal way.
  95. self.current.addPoint(self.current[0])
  96. self.finalise(ev)
  97. def selectShape(self, point):
  98. """Select the first shape created which contains this point."""
  99. self.deSelectShape()
  100. for shape in reversed(self.shapes):
  101. if shape.containsPoint(point):
  102. shape.selected = True
  103. self.selectedShape = shape
  104. self.calculateOffsets(shape, point)
  105. self.repaint()
  106. return
  107. def calculateOffsets(self, shape, point):
  108. rect = shape.boundingRect()
  109. x1 = rect.x() - point.x()
  110. y1 = rect.y() - point.y()
  111. x2 = (rect.x() + rect.width()) - point.x()
  112. y2 = (rect.y() + rect.height()) - point.y()
  113. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  114. def boundedMoveShape(self, pos):
  115. if self.outOfPixmap(pos):
  116. return # No need to move
  117. o1 = pos + self.offsets[0]
  118. if self.outOfPixmap(o1):
  119. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  120. o2 = pos + self.offsets[1]
  121. if self.outOfPixmap(o2):
  122. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  123. min(0, self.pixmap.height()- o2.y()))
  124. # The next line tracks the new position of the cursor
  125. # relative to the shape, but also results in making it
  126. # a bit "shaky" when nearing the border and allows it to
  127. # go outside of the shape's area for some reason. XXX
  128. #self.calculateOffsets(self.selectedShape, pos)
  129. self.selectedShape.moveBy(pos - self.prevPoint)
  130. self.prevPoint = pos
  131. def deSelectShape(self):
  132. if self.selectedShape:
  133. self.selectedShape.selected = False
  134. self.selectedShape = None
  135. def deleteSelected(self):
  136. if self.selectedShape:
  137. self.shapes.remove(self.selectedShape)
  138. self.selectedShape = None
  139. self.repaint()
  140. def copySelectedShape(self):
  141. if self.selectedShape:
  142. shape = self.selectedShape.copy()
  143. self.shapes.append(shape)
  144. self.selectedShape = shape
  145. self.deSelectShape()
  146. self.repaint()
  147. return shape
  148. def paintEvent(self, event):
  149. if not self.pixmap:
  150. return super(Canvas, self).paintEvent(event)
  151. p = QPainter()
  152. p.begin(self)
  153. p.setRenderHint(QPainter.Antialiasing)
  154. p.scale(self.scale, self.scale)
  155. p.translate(self.offsetToCenter())
  156. p.drawPixmap(0, 0, self.pixmap)
  157. Shape.scale = self.scale
  158. if not self.hideShapesWhenNew:
  159. for shape in self.shapes:
  160. shape.paint(p)
  161. if self.current:
  162. self.current.paint(p)
  163. self.line.paint(p)
  164. if self.selectedShapeCopy:
  165. self.selectedShapeCopy.paint(p)
  166. p.end()
  167. def transformPos(self, point):
  168. """Convert from widget-logical coordinates to painter-logical coordinates."""
  169. return point / self.scale - self.offsetToCenter()
  170. def offsetToCenter(self):
  171. s = self.scale
  172. area = super(Canvas, self).size()
  173. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  174. aw, ah = area.width(), area.height()
  175. x = (aw-w)/(2*s) if aw > w else 0
  176. y = (ah-h)/(2*s) if ah > h else 0
  177. return QPointF(x, y)
  178. def outOfPixmap(self, p):
  179. w, h = self.pixmap.width(), self.pixmap.height()
  180. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  181. def finalise(self, ev):
  182. assert self.current
  183. self.current.fill = True
  184. self.shapes.append(self.current)
  185. self.current = None
  186. self.setEditing(False)
  187. self.repaint()
  188. self.hideShapesWhenNew=False
  189. self.newShape.emit(self.mapToGlobal(ev.pos()))
  190. self.setMouseTracking(False)
  191. def closeEnough(self, p1, p2):
  192. #d = distance(p1 - p2)
  193. #m = (p1-p2).manhattanLength()
  194. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  195. return distance(p1 - p2) < self.epsilon
  196. def intersectionPoint(self, p1, p2):
  197. # Cycle through each image edge in clockwise fashion,
  198. # and find the one intersecting the current line segment.
  199. # http://paulbourke.net/geometry/lineline2d/
  200. size = self.pixmap.size()
  201. points = [(0,0),
  202. (size.width(), 0),
  203. (size.width(), size.height()),
  204. (0, size.height())]
  205. x1, y1 = p1.x(), p1.y()
  206. x2, y2 = p2.x(), p2.y()
  207. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  208. x3, y3 = points[i]
  209. x4, y4 = points[(i+1)%4]
  210. if (x, y) == (x1, y1):
  211. # Handle cases where previous point is on one of the edges.
  212. if x3 == x4:
  213. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  214. else: # y3 == y4
  215. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  216. return QPointF(x, y)
  217. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  218. """For each edge formed by `points', yield the intersection
  219. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  220. Also return the distance of `(x2,y2)' to the middle of the
  221. edge along with its index, so that the one closest can be chosen."""
  222. for i in xrange(4):
  223. x3, y3 = points[i]
  224. x4, y4 = points[(i+1) % 4]
  225. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  226. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  227. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  228. if denom == 0:
  229. # This covers two cases:
  230. # nua == nub == 0: Coincident
  231. # otherwise: Parallel
  232. continue
  233. ua, ub = nua / denom, nub / denom
  234. if 0 <= ua <= 1 and 0 <= ub <= 1:
  235. x = x1 + ua * (x2 - x1)
  236. y = y1 + ua * (y2 - y1)
  237. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  238. d = distance(m - QPointF(x2, y2))
  239. yield d, i, (x, y)
  240. # These two, along with a call to adjustSize are required for the
  241. # scroll area.
  242. def sizeHint(self):
  243. return self.minimumSizeHint()
  244. def minimumSizeHint(self):
  245. if self.pixmap:
  246. return self.scale * self.pixmap.size()
  247. return super(Canvas, self).minimumSizeHint()
  248. def wheelEvent(self, ev):
  249. if ev.orientation() == Qt.Vertical:
  250. mods = ev.modifiers()
  251. if Qt.ControlModifier == int(mods):
  252. self.zoomRequest.emit(ev.delta())
  253. else:
  254. self.scrollRequest.emit(ev.delta(),
  255. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  256. else Qt.Vertical)
  257. else:
  258. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  259. ev.accept()
  260. def keyPressEvent(self, ev):
  261. if ev.key() == Qt.Key_Escape and self.current:
  262. self.current = None
  263. self.repaint()
  264. def setLastLabel(self, text):
  265. assert text
  266. print "shape <- '%s'" % text
  267. self.shapes[-1].label = text
  268. return self.shapes[-1]
  269. def undoLastLine(self):
  270. assert self.shapes
  271. self.current = self.shapes.pop()
  272. self.current.fill = False
  273. pos = self.current.popPoint()
  274. self.line.points = [self.current[-1], pos]
  275. self.setEditing()
  276. def deleteLastShape(self):
  277. assert self.shapes
  278. self.shapes.pop()
  279. def pp(p):
  280. return '%.2f, %.2f' % (p.x(), p.y())
  281. def distance(p):
  282. return sqrt(p.x() * p.x() + p.y() * p.y())