PlotCanvas.py 10 KB

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