canvas.py 11 KB

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