PlotCanvasLegacy.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 PyQt5 import QtGui, QtCore, QtWidgets
  9. # Prevent conflict with Qt5 and above.
  10. from matplotlib import use as mpl_use
  11. from matplotlib.figure import Figure
  12. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  13. from matplotlib.backends.backend_agg import FigureCanvasAgg
  14. from matplotlib.widgets import Cursor
  15. import FlatCAMApp
  16. import logging
  17. mpl_use("Qt5Agg")
  18. log = logging.getLogger('base')
  19. class CanvasCache(QtCore.QObject):
  20. """
  21. Case story #1:
  22. 1) No objects in the project.
  23. 2) Object is created (new_object() emits object_created(obj)).
  24. on_object_created() adds (i) object to collection and emits
  25. (ii) new_object_available() then calls (iii) object.plot()
  26. 3) object.plot() creates axes if necessary on
  27. app.collection.figure. Then plots on it.
  28. 4) Plots on a cache-size canvas (in background).
  29. 5) Plot completes. Bitmap is generated.
  30. 6) Visible canvas is painted.
  31. """
  32. # Signals:
  33. # A bitmap is ready to be displayed.
  34. new_screen = QtCore.pyqtSignal()
  35. def __init__(self, plotcanvas, app, dpi=50):
  36. super(CanvasCache, self).__init__()
  37. self.app = app
  38. self.plotcanvas = plotcanvas
  39. self.dpi = dpi
  40. self.figure = Figure(dpi=dpi)
  41. self.axes = self.figure.add_axes([0.0, 0.0, 1.0, 1.0], alpha=1.0)
  42. self.axes.set_frame_on(False)
  43. self.axes.set_xticks([])
  44. self.axes.set_yticks([])
  45. self.canvas = FigureCanvasAgg(self.figure)
  46. self.cache = None
  47. def run(self):
  48. log.debug("CanvasCache Thread Started!")
  49. self.plotcanvas.update_screen_request.connect(self.on_update_req)
  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. #
  68. # log.debug("A new object is available. Should plot it!")
  69. class PlotCanvasLegacy(QtCore.QObject):
  70. """
  71. Class handling the plotting area in the application.
  72. """
  73. # Signals:
  74. # Request for new bitmap to display. The parameter
  75. # is a list with [xmin, xmax, ymin, ymax, zoom(optional)]
  76. update_screen_request = QtCore.pyqtSignal(list)
  77. double_click = QtCore.pyqtSignal(object)
  78. def __init__(self, container, app):
  79. """
  80. The constructor configures the Matplotlib figure that
  81. will contain all plots, creates the base axes and connects
  82. events to the plotting area.
  83. :param container: The parent container in which to draw plots.
  84. :rtype: PlotCanvas
  85. """
  86. super(PlotCanvasLegacy, self).__init__()
  87. self.app = app
  88. # Options
  89. self.x_margin = 15 # pixels
  90. self.y_margin = 25 # Pixels
  91. # Parent container
  92. self.container = container
  93. # Plots go onto a single matplotlib.figure
  94. self.figure = Figure(dpi=50) # TODO: dpi needed?
  95. self.figure.patch.set_visible(False)
  96. # These axes show the ticks and grid. No plotting done here.
  97. # New axes must have a label, otherwise mpl returns an existing one.
  98. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  99. self.axes.set_aspect(1)
  100. self.axes.grid(True)
  101. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  102. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  103. # The canvas is the top level container (FigureCanvasQTAgg)
  104. self.canvas = FigureCanvas(self.figure)
  105. self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
  106. self.canvas.setFocus()
  107. self.native = self.canvas
  108. # self.canvas.set_hexpand(1)
  109. # self.canvas.set_vexpand(1)
  110. # self.canvas.set_can_focus(True) # For key press
  111. # Attach to parent
  112. # self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  113. self.container.addWidget(self.canvas) # Qt
  114. # Copy a bitmap of the canvas for quick animation.
  115. # Update every time the canvas is re-drawn.
  116. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  117. # ## Bitmap Cache
  118. self.cache = CanvasCache(self, self.app)
  119. self.cache_thread = QtCore.QThread()
  120. self.cache.moveToThread(self.cache_thread)
  121. # super(PlotCanvas, self).connect(self.cache_thread, QtCore.SIGNAL("started()"), self.cache.run)
  122. self.cache_thread.started.connect(self.cache.run)
  123. self.cache_thread.start()
  124. self.cache.new_screen.connect(self.on_new_screen)
  125. # Events
  126. self.graph_event_connect('button_press_event', self.on_mouse_press)
  127. self.graph_event_connect('button_release_event', self.on_mouse_release)
  128. self.graph_event_connect('motion_notify_event', self.on_mouse_move)
  129. # self.canvas.connect('configure-event', self.auto_adjust_axes)
  130. self.graph_event_connect('resize_event', self.auto_adjust_axes)
  131. # self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  132. # self.canvas.connect("scroll-event", self.on_scroll)
  133. self.graph_event_connect('scroll_event', self.on_scroll)
  134. # self.graph_event_connect('key_press_event', self.on_key_down)
  135. # self.graph_event_connect('key_release_event', self.on_key_up)
  136. self.graph_event_connect('draw_event', self.on_draw)
  137. self.mouse = [0, 0]
  138. self.key = None
  139. self.pan_axes = []
  140. self.panning = False
  141. # signal is the mouse is dragging
  142. self.is_dragging = False
  143. # signal if there is a doubleclick
  144. self.is_dblclk = False
  145. def graph_event_connect(self, event_name, callback):
  146. """
  147. Attach an event handler to the canvas through the Matplotlib interface.
  148. :param event_name: Name of the event
  149. :type event_name: str
  150. :param callback: Function to call
  151. :type callback: func
  152. :return: Connection id
  153. :rtype: int
  154. """
  155. if event_name == 'mouse_move':
  156. event_name = 'motion_notify_event'
  157. if event_name == 'mouse_press':
  158. event_name = 'button_press_event'
  159. if event_name == 'mouse_release':
  160. event_name = 'button_release_event'
  161. if event_name == 'mouse_double_click':
  162. return self.double_click.connect(callback)
  163. if event_name == 'key_press':
  164. event_name = 'key_press_event'
  165. return self.canvas.mpl_connect(event_name, callback)
  166. def graph_event_disconnect(self, cid):
  167. """
  168. Disconnect callback with the give id.
  169. :param cid: Callback id.
  170. :return: None
  171. """
  172. if cid == 'mouse_move':
  173. cid = 'motion_notify_event'
  174. if cid == 'mouse_press':
  175. cid = 'button_press_event'
  176. if cid == 'mouse_release':
  177. cid = 'button_release_event'
  178. if cid == 'mouse_double_click':
  179. self.double_click.disconnect(cid)
  180. return
  181. if cid == 'key_press':
  182. cid = 'key_press_event'
  183. self.canvas.mpl_disconnect(cid)
  184. def on_new_screen(self):
  185. pass
  186. # log.debug("Cache updated the screen!")
  187. def new_cursor(self):
  188. c = MplCursor(axes=self.axes, color='black', linewidth=1)
  189. return c
  190. def on_key_down(self, event):
  191. """
  192. :param event:
  193. :return:
  194. """
  195. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  196. self.key = event.key
  197. def on_key_up(self, event):
  198. """
  199. :param event:
  200. :return:
  201. """
  202. self.key = None
  203. def connect(self, event_name, callback):
  204. """
  205. Attach an event handler to the canvas through the native Qt interface.
  206. :param event_name: Name of the event
  207. :type event_name: str
  208. :param callback: Function to call
  209. :type callback: function
  210. :return: Nothing
  211. """
  212. self.canvas.connect(event_name, callback)
  213. def clear(self):
  214. """
  215. Clears axes and figure.
  216. :return: None
  217. """
  218. # Clear
  219. self.axes.cla()
  220. try:
  221. self.figure.clf()
  222. except KeyError:
  223. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  224. # Re-build
  225. self.figure.add_axes(self.axes)
  226. self.axes.set_aspect(1)
  227. self.axes.grid(True)
  228. # Re-draw
  229. self.canvas.draw_idle()
  230. def adjust_axes(self, xmin, ymin, xmax, ymax):
  231. """
  232. Adjusts all axes while maintaining the use of the whole canvas
  233. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  234. request that will be modified to fit these restrictions.
  235. :param xmin: Requested minimum value for the X axis.
  236. :type xmin: float
  237. :param ymin: Requested minimum value for the Y axis.
  238. :type ymin: float
  239. :param xmax: Requested maximum value for the X axis.
  240. :type xmax: float
  241. :param ymax: Requested maximum value for the Y axis.
  242. :type ymax: float
  243. :return: None
  244. """
  245. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  246. width = xmax - xmin
  247. height = ymax - ymin
  248. try:
  249. r = width / height
  250. except ZeroDivisionError:
  251. FlatCAMApp.App.log.error("Height is %f" % height)
  252. return
  253. canvas_w, canvas_h = self.canvas.get_width_height()
  254. canvas_r = float(canvas_w) / canvas_h
  255. x_ratio = float(self.x_margin) / canvas_w
  256. y_ratio = float(self.y_margin) / canvas_h
  257. if r > canvas_r:
  258. ycenter = (ymin + ymax) / 2.0
  259. newheight = height * r / canvas_r
  260. ymin = ycenter - newheight / 2.0
  261. ymax = ycenter + newheight / 2.0
  262. else:
  263. xcenter = (xmax + xmin) / 2.0
  264. newwidth = width * canvas_r / r
  265. xmin = xcenter - newwidth / 2.0
  266. xmax = xcenter + newwidth / 2.0
  267. # Adjust axes
  268. for ax in self.figure.get_axes():
  269. if ax._label != 'base':
  270. ax.set_frame_on(False) # No frame
  271. ax.set_xticks([]) # No tick
  272. ax.set_yticks([]) # No ticks
  273. ax.patch.set_visible(False) # No background
  274. ax.set_aspect(1)
  275. ax.set_xlim((xmin, xmax))
  276. ax.set_ylim((ymin, ymax))
  277. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  278. # Sync re-draw to proper paint on form resize
  279. self.canvas.draw()
  280. # #### Temporary place-holder for cached update #####
  281. self.update_screen_request.emit([0, 0, 0, 0, 0])
  282. def auto_adjust_axes(self, *args):
  283. """
  284. Calls ``adjust_axes()`` using the extents of the base axes.
  285. :rtype : None
  286. :return: None
  287. """
  288. xmin, xmax = self.axes.get_xlim()
  289. ymin, ymax = self.axes.get_ylim()
  290. self.adjust_axes(xmin, ymin, xmax, ymax)
  291. def zoom(self, factor, center=None):
  292. """
  293. Zooms the plot by factor around a given
  294. center point. Takes care of re-drawing.
  295. :param factor: Number by which to scale the plot.
  296. :type factor: float
  297. :param center: Coordinates [x, y] of the point around which to scale the plot.
  298. :type center: list
  299. :return: None
  300. """
  301. xmin, xmax = self.axes.get_xlim()
  302. ymin, ymax = self.axes.get_ylim()
  303. width = xmax - xmin
  304. height = ymax - ymin
  305. if center is None or center == [None, None]:
  306. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  307. # For keeping the point at the pointer location
  308. relx = (xmax - center[0]) / width
  309. rely = (ymax - center[1]) / height
  310. new_width = width / factor
  311. new_height = height / factor
  312. xmin = center[0] - new_width * (1 - relx)
  313. xmax = center[0] + new_width * relx
  314. ymin = center[1] - new_height * (1 - rely)
  315. ymax = center[1] + new_height * rely
  316. # Adjust axes
  317. for ax in self.figure.get_axes():
  318. ax.set_xlim((xmin, xmax))
  319. ax.set_ylim((ymin, ymax))
  320. # Async re-draw
  321. self.canvas.draw_idle()
  322. # #### Temporary place-holder for cached update #####
  323. self.update_screen_request.emit([0, 0, 0, 0, 0])
  324. def pan(self, x, y):
  325. xmin, xmax = self.axes.get_xlim()
  326. ymin, ymax = self.axes.get_ylim()
  327. width = xmax - xmin
  328. height = ymax - ymin
  329. # Adjust axes
  330. for ax in self.figure.get_axes():
  331. ax.set_xlim((xmin + x * width, xmax + x * width))
  332. ax.set_ylim((ymin + y * height, ymax + y * height))
  333. # Re-draw
  334. self.canvas.draw_idle()
  335. # #### Temporary place-holder for cached update #####
  336. self.update_screen_request.emit([0, 0, 0, 0, 0])
  337. def new_axes(self, name):
  338. """
  339. Creates and returns an Axes object attached to this object's Figure.
  340. :param name: Unique label for the axes.
  341. :return: Axes attached to the figure.
  342. :rtype: Axes
  343. """
  344. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  345. def on_scroll(self, event):
  346. """
  347. Scroll event handler.
  348. :param event: Event object containing the event information.
  349. :return: None
  350. """
  351. # So it can receive key presses
  352. # self.canvas.grab_focus()
  353. self.canvas.setFocus()
  354. # Event info
  355. # z, direction = event.get_scroll_direction()
  356. if self.key is None:
  357. if event.button == 'up':
  358. self.zoom(1.5, self.mouse)
  359. else:
  360. self.zoom(1 / 1.5, self.mouse)
  361. return
  362. if self.key == 'shift':
  363. if event.button == 'up':
  364. self.pan(0.3, 0)
  365. else:
  366. self.pan(-0.3, 0)
  367. return
  368. if self.key == 'control':
  369. if event.button == 'up':
  370. self.pan(0, 0.3)
  371. else:
  372. self.pan(0, -0.3)
  373. return
  374. def on_mouse_press(self, event):
  375. self.is_dragging = True
  376. # Check for middle mouse button press
  377. if self.app.defaults["global_pan_button"] == '2':
  378. pan_button = 3 # right button for Matplotlib
  379. else:
  380. pan_button = 2 # middle button for Matplotlib
  381. if event.button == pan_button:
  382. # Prepare axes for pan (using 'matplotlib' pan function)
  383. self.pan_axes = []
  384. for a in self.figure.get_axes():
  385. if (event.x is not None and event.y is not None and a.in_axes(event) and
  386. a.get_navigate() and a.can_pan()):
  387. a.start_pan(event.x, event.y, 1)
  388. self.pan_axes.append(a)
  389. # Set pan view flag
  390. if len(self.pan_axes) > 0:
  391. self.panning = True
  392. if event.dblclick:
  393. self.double_click.emit(event)
  394. def on_mouse_release(self, event):
  395. self.is_dragging = False
  396. # Check for middle mouse button release to complete pan procedure
  397. # Check for middle mouse button press
  398. if self.app.defaults["global_pan_button"] == '2':
  399. pan_button = 3 # right button for Matplotlib
  400. else:
  401. pan_button = 2 # middle button for Matplotlib
  402. if event.button == pan_button:
  403. for a in self.pan_axes:
  404. a.end_pan()
  405. # Clear pan flag
  406. self.panning = False
  407. def on_mouse_move(self, event):
  408. """
  409. Mouse movement event hadler. Stores the coordinates. Updates view on pan.
  410. :param event: Contains information about the event.
  411. :return: None
  412. """
  413. self.mouse = [event.xdata, event.ydata]
  414. # Update pan view on mouse move
  415. if self.panning is True:
  416. for a in self.pan_axes:
  417. a.drag_pan(1, event.key, event.x, event.y)
  418. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  419. self.canvas.draw_idle()
  420. # #### Temporary place-holder for cached update #####
  421. self.update_screen_request.emit([0, 0, 0, 0, 0])
  422. def translate_coords(self, position):
  423. """
  424. This does not do much. It's just for code compatibility
  425. :param position: Mouse event position
  426. :return: Tuple with mouse position
  427. """
  428. return (position[0], position[1])
  429. def on_draw(self, renderer):
  430. # Store background on canvas redraw
  431. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  432. def get_axes_pixelsize(self):
  433. """
  434. Axes size in pixels.
  435. :return: Pixel width and height
  436. :rtype: tuple
  437. """
  438. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  439. width, height = bbox.width, bbox.height
  440. width *= self.figure.dpi
  441. height *= self.figure.dpi
  442. return width, height
  443. def get_density(self):
  444. """
  445. Returns unit length per pixel on horizontal
  446. and vertical axes.
  447. :return: X and Y density
  448. :rtype: tuple
  449. """
  450. xpx, ypx = self.get_axes_pixelsize()
  451. xmin, xmax = self.axes.get_xlim()
  452. ymin, ymax = self.axes.get_ylim()
  453. width = xmax - xmin
  454. height = ymax - ymin
  455. return width / xpx, height / ypx
  456. class MplCursor(Cursor):
  457. def __init__(self, axes, color='red', linewidth=1):
  458. super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  459. self._enabled = True
  460. self.axes = axes
  461. self.color = color
  462. self.linewidth = linewidth
  463. self.x = None
  464. self.y = None
  465. @property
  466. def enabled(self):
  467. return True if self._enabled else False
  468. @enabled.setter
  469. def enabled(self, value):
  470. self._enabled = value
  471. self.visible = self._enabled
  472. self.canvas.draw()
  473. def onmove(self, event):
  474. pass
  475. def set_data(self, event, pos):
  476. """Internal event handler to draw the cursor when the mouse moves."""
  477. self.x = pos[0]
  478. self.y = pos[1]
  479. if self.ignore(event):
  480. return
  481. if not self.canvas.widgetlock.available(self):
  482. return
  483. if event.inaxes != self.ax:
  484. self.linev.set_visible(False)
  485. self.lineh.set_visible(False)
  486. if self.needclear:
  487. self.canvas.draw()
  488. self.needclear = False
  489. return
  490. self.needclear = True
  491. if not self.visible:
  492. return
  493. self.linev.set_xdata((self.x, self.x))
  494. self.lineh.set_ydata((self.y, self.y))
  495. self.linev.set_visible(self.visible and self.vertOn)
  496. self.lineh.set_visible(self.visible and self.horizOn)
  497. self._update()
  498. class ShapeCollectionLegacy():
  499. def __init__(self):
  500. self._shapes = []
  501. def add(self, shape):
  502. try:
  503. for sh in shape:
  504. self._shapes.append(sh)
  505. except TypeError:
  506. self._shapes.append(shape)
  507. def clear(self, update=None):
  508. self._shapes[:] = []
  509. if update is True:
  510. self.redraw()
  511. def redraw(self):
  512. pass