PlotCanvas.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from PyQt4 import QtGui, QtCore
  9. from matplotlib.figure import Figure
  10. from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
  11. import FlatCAMApp
  12. class PlotCanvas:
  13. """
  14. Class handling the plotting area in the application.
  15. """
  16. def __init__(self, container):
  17. """
  18. The constructor configures the Matplotlib figure that
  19. will contain all plots, creates the base axes and connects
  20. events to the plotting area.
  21. :param container: The parent container in which to draw plots.
  22. :rtype: PlotCanvas
  23. """
  24. # Options
  25. self.x_margin = 15 # pixels
  26. self.y_margin = 25 # Pixels
  27. # Parent container
  28. self.container = container
  29. # Plots go onto a single matplotlib.figure
  30. self.figure = Figure(dpi=50) # TODO: dpi needed?
  31. self.figure.patch.set_visible(False)
  32. # These axes show the ticks and grid. No plotting done here.
  33. # New axes must have a label, otherwise mpl returns an existing one.
  34. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  35. self.axes.set_aspect(1)
  36. self.axes.grid(True)
  37. # The canvas is the top level container (Gtk.DrawingArea)
  38. self.canvas = FigureCanvas(self.figure)
  39. # self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
  40. # self.canvas.setFocus()
  41. #self.canvas.set_hexpand(1)
  42. #self.canvas.set_vexpand(1)
  43. #self.canvas.set_can_focus(True) # For key press
  44. # Attach to parent
  45. #self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  46. self.container.addWidget(self.canvas) # Qt
  47. # Copy a bitmap of the canvas for quick animation.
  48. # Update every time the canvas is re-drawn.
  49. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  50. # Events
  51. self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
  52. #self.canvas.connect('configure-event', self.auto_adjust_axes)
  53. self.canvas.mpl_connect('resize_event', self.auto_adjust_axes)
  54. #self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  55. #self.canvas.connect("scroll-event", self.on_scroll)
  56. self.canvas.mpl_connect('scroll_event', self.on_scroll)
  57. self.canvas.mpl_connect('key_press_event', self.on_key_down)
  58. self.canvas.mpl_connect('key_release_event', self.on_key_up)
  59. self.mouse = [0, 0]
  60. self.key = None
  61. def on_key_down(self, event):
  62. """
  63. :param event:
  64. :return:
  65. """
  66. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  67. self.key = event.key
  68. def on_key_up(self, event):
  69. """
  70. :param event:
  71. :return:
  72. """
  73. self.key = None
  74. def mpl_connect(self, event_name, callback):
  75. """
  76. Attach an event handler to the canvas through the Matplotlib interface.
  77. :param event_name: Name of the event
  78. :type event_name: str
  79. :param callback: Function to call
  80. :type callback: func
  81. :return: Connection id
  82. :rtype: int
  83. """
  84. return self.canvas.mpl_connect(event_name, callback)
  85. def mpl_disconnect(self, cid):
  86. """
  87. Disconnect callback with the give id.
  88. :param cid: Callback id.
  89. :return: None
  90. """
  91. self.canvas.mpl_disconnect(cid)
  92. def connect(self, event_name, callback):
  93. """
  94. Attach an event handler to the canvas through the native GTK interface.
  95. :param event_name: Name of the event
  96. :type event_name: str
  97. :param callback: Function to call
  98. :type callback: function
  99. :return: Nothing
  100. """
  101. self.canvas.connect(event_name, callback)
  102. def clear(self):
  103. """
  104. Clears axes and figure.
  105. :return: None
  106. """
  107. # Clear
  108. self.axes.cla()
  109. try:
  110. self.figure.clf()
  111. except KeyError:
  112. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  113. # Re-build
  114. self.figure.add_axes(self.axes)
  115. self.axes.set_aspect(1)
  116. self.axes.grid(True)
  117. # Re-draw
  118. self.canvas.draw()
  119. def adjust_axes(self, xmin, ymin, xmax, ymax):
  120. """
  121. Adjusts all axes while maintaining the use of the whole canvas
  122. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  123. request that will be modified to fit these restrictions.
  124. :param xmin: Requested minimum value for the X axis.
  125. :type xmin: float
  126. :param ymin: Requested minimum value for the Y axis.
  127. :type ymin: float
  128. :param xmax: Requested maximum value for the X axis.
  129. :type xmax: float
  130. :param ymax: Requested maximum value for the Y axis.
  131. :type ymax: float
  132. :return: None
  133. """
  134. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  135. width = xmax - xmin
  136. height = ymax - ymin
  137. try:
  138. r = width / height
  139. except ZeroDivisionError:
  140. FlatCAMApp.App.log.error("Height is %f" % height)
  141. return
  142. canvas_w, canvas_h = self.canvas.get_width_height()
  143. canvas_r = float(canvas_w) / canvas_h
  144. x_ratio = float(self.x_margin) / canvas_w
  145. y_ratio = float(self.y_margin) / canvas_h
  146. if r > canvas_r:
  147. ycenter = (ymin + ymax) / 2.0
  148. newheight = height * r / canvas_r
  149. ymin = ycenter - newheight / 2.0
  150. ymax = ycenter + newheight / 2.0
  151. else:
  152. xcenter = (xmax + xmin) / 2.0
  153. newwidth = width * canvas_r / r
  154. xmin = xcenter - newwidth / 2.0
  155. xmax = xcenter + newwidth / 2.0
  156. # Adjust axes
  157. for ax in self.figure.get_axes():
  158. if ax._label != 'base':
  159. ax.set_frame_on(False) # No frame
  160. ax.set_xticks([]) # No tick
  161. ax.set_yticks([]) # No ticks
  162. ax.patch.set_visible(False) # No background
  163. ax.set_aspect(1)
  164. ax.set_xlim((xmin, xmax))
  165. ax.set_ylim((ymin, ymax))
  166. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  167. # Re-draw
  168. self.canvas.draw()
  169. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  170. def auto_adjust_axes(self, *args):
  171. """
  172. Calls ``adjust_axes()`` using the extents of the base axes.
  173. :rtype : None
  174. :return: None
  175. """
  176. xmin, xmax = self.axes.get_xlim()
  177. ymin, ymax = self.axes.get_ylim()
  178. self.adjust_axes(xmin, ymin, xmax, ymax)
  179. def zoom(self, factor, center=None):
  180. """
  181. Zooms the plot by factor around a given
  182. center point. Takes care of re-drawing.
  183. :param factor: Number by which to scale the plot.
  184. :type factor: float
  185. :param center: Coordinates [x, y] of the point around which to scale the plot.
  186. :type center: list
  187. :return: None
  188. """
  189. xmin, xmax = self.axes.get_xlim()
  190. ymin, ymax = self.axes.get_ylim()
  191. width = xmax - xmin
  192. height = ymax - ymin
  193. if center is None or center == [None, None]:
  194. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  195. # For keeping the point at the pointer location
  196. relx = (xmax - center[0]) / width
  197. rely = (ymax - center[1]) / height
  198. new_width = width / factor
  199. new_height = height / factor
  200. xmin = center[0] - new_width * (1 - relx)
  201. xmax = center[0] + new_width * relx
  202. ymin = center[1] - new_height * (1 - rely)
  203. ymax = center[1] + new_height * rely
  204. # Adjust axes
  205. for ax in self.figure.get_axes():
  206. ax.set_xlim((xmin, xmax))
  207. ax.set_ylim((ymin, ymax))
  208. # Re-draw
  209. self.canvas.draw()
  210. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  211. def pan(self, x, y):
  212. xmin, xmax = self.axes.get_xlim()
  213. ymin, ymax = self.axes.get_ylim()
  214. width = xmax - xmin
  215. height = ymax - ymin
  216. # Adjust axes
  217. for ax in self.figure.get_axes():
  218. ax.set_xlim((xmin + x*width, xmax + x*width))
  219. ax.set_ylim((ymin + y*height, ymax + y*height))
  220. # Re-draw
  221. self.canvas.draw()
  222. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  223. def new_axes(self, name):
  224. """
  225. Creates and returns an Axes object attached to this object's Figure.
  226. :param name: Unique label for the axes.
  227. :return: Axes attached to the figure.
  228. :rtype: Axes
  229. """
  230. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  231. def on_scroll(self, event):
  232. """
  233. Scroll event handler.
  234. :param event: Event object containing the event information.
  235. :return: None
  236. """
  237. # So it can receive key presses
  238. # self.canvas.grab_focus()
  239. self.canvas.setFocus()
  240. # Event info
  241. # z, direction = event.get_scroll_direction()
  242. if self.key is None:
  243. if event.button == 'up':
  244. self.zoom(1.5, self.mouse)
  245. else:
  246. self.zoom(1/1.5, self.mouse)
  247. return
  248. if self.key == 'shift':
  249. if event.button == 'up':
  250. self.pan(0.3, 0)
  251. else:
  252. self.pan(-0.3, 0)
  253. return
  254. if self.key == 'control':
  255. if event.button == 'up':
  256. self.pan(0, 0.3)
  257. else:
  258. self.pan(0, -0.3)
  259. return
  260. def on_mouse_move(self, event):
  261. """
  262. Mouse movement event hadler. Stores the coordinates.
  263. :param event: Contains information about the event.
  264. :return: None
  265. """
  266. self.mouse = [event.xdata, event.ydata]