PlotCanvas.py 13 KB

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