PlotCanvas.py 9.7 KB

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