PlotCanvas.py 16 KB

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