PlotCanvas.py 16 KB

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