PlotCanvas.py 12 KB

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