PlotCanvas.py 9.6 KB

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