PlotCanvasLegacy.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. # Modified by Marius Stanciu 09/21/2019 #
  8. ############################################################
  9. from PyQt5 import QtGui, QtCore, QtWidgets
  10. from PyQt5.QtCore import pyqtSignal
  11. # needed for legacy mode
  12. # Used for solid polygons in Matplotlib
  13. from descartes.patch import PolygonPatch
  14. from shapely.geometry import Polygon, LineString, LinearRing, Point, MultiPolygon, MultiLineString
  15. import FlatCAMApp
  16. from copy import deepcopy
  17. import logging
  18. import gettext
  19. import FlatCAMTranslation as fcTranslate
  20. import builtins
  21. # Prevent conflict with Qt5 and above.
  22. from matplotlib import use as mpl_use
  23. mpl_use("Qt5Agg")
  24. from matplotlib.figure import Figure
  25. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  26. # from matplotlib.widgets import Cursor
  27. fcTranslate.apply_language('strings')
  28. if '_' not in builtins.__dict__:
  29. _ = gettext.gettext
  30. log = logging.getLogger('base')
  31. class CanvasCache(QtCore.QObject):
  32. """
  33. Case story #1:
  34. 1) No objects in the project.
  35. 2) Object is created (new_object() emits object_created(obj)).
  36. on_object_created() adds (i) object to collection and emits
  37. (ii) new_object_available() then calls (iii) object.plot()
  38. 3) object.plot() creates axes if necessary on
  39. app.collection.figure. Then plots on it.
  40. 4) Plots on a cache-size canvas (in background).
  41. 5) Plot completes. Bitmap is generated.
  42. 6) Visible canvas is painted.
  43. """
  44. # Signals:
  45. # A bitmap is ready to be displayed.
  46. new_screen = QtCore.pyqtSignal()
  47. def __init__(self, plotcanvas, app, dpi=50):
  48. super(CanvasCache, self).__init__()
  49. self.app = app
  50. self.plotcanvas = plotcanvas
  51. self.dpi = dpi
  52. self.figure = Figure(dpi=dpi)
  53. self.axes = self.figure.add_axes([0.0, 0.0, 1.0, 1.0], alpha=1.0)
  54. self.axes.set_frame_on(False)
  55. self.axes.set_xticks([])
  56. self.axes.set_yticks([])
  57. self.canvas = FigureCanvas(self.figure)
  58. self.cache = None
  59. def run(self):
  60. log.debug("CanvasCache Thread Started!")
  61. self.plotcanvas.update_screen_request.connect(self.on_update_req)
  62. def on_update_req(self, extents):
  63. """
  64. Event handler for an updated display request.
  65. :param extents: [xmin, xmax, ymin, ymax, zoom(optional)]
  66. """
  67. # log.debug("Canvas update requested: %s" % str(extents))
  68. # Note: This information below might be out of date. Establish
  69. # a protocol regarding when to change the canvas in the main
  70. # thread and when to check these values here in the background,
  71. # or pass this data in the signal (safer).
  72. # log.debug("Size: %s [px]" % str(self.plotcanvas.get_axes_pixelsize()))
  73. # log.debug("Density: %s [units/px]" % str(self.plotcanvas.get_density()))
  74. # Move the requested screen portion to the main thread
  75. # and inform about the update:
  76. self.new_screen.emit()
  77. # Continue to update the cache.
  78. # def on_new_object_available(self):
  79. #
  80. # log.debug("A new object is available. Should plot it!")
  81. class PlotCanvasLegacy(QtCore.QObject):
  82. """
  83. Class handling the plotting area in the application.
  84. """
  85. # Signals:
  86. # Request for new bitmap to display. The parameter
  87. # is a list with [xmin, xmax, ymin, ymax, zoom(optional)]
  88. update_screen_request = QtCore.pyqtSignal(list)
  89. double_click = QtCore.pyqtSignal(object)
  90. def __init__(self, container, app):
  91. """
  92. The constructor configures the Matplotlib figure that
  93. will contain all plots, creates the base axes and connects
  94. events to the plotting area.
  95. :param container: The parent container in which to draw plots.
  96. :rtype: PlotCanvas
  97. """
  98. super(PlotCanvasLegacy, self).__init__()
  99. self.app = app
  100. # Options
  101. self.x_margin = 15 # pixels
  102. self.y_margin = 25 # Pixels
  103. # Parent container
  104. self.container = container
  105. # Plots go onto a single matplotlib.figure
  106. self.figure = Figure(dpi=50) # TODO: dpi needed?
  107. self.figure.patch.set_visible(False)
  108. # These axes show the ticks and grid. No plotting done here.
  109. # New axes must have a label, otherwise mpl returns an existing one.
  110. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  111. self.axes.set_aspect(1)
  112. self.axes.grid(True)
  113. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  114. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  115. # The canvas is the top level container (FigureCanvasQTAgg)
  116. self.canvas = FigureCanvas(self.figure)
  117. self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
  118. self.canvas.setFocus()
  119. self.native = self.canvas
  120. self.adjust_axes(-10, -10, 100, 100)
  121. # self.canvas.set_can_focus(True) # For key press
  122. # Attach to parent
  123. # self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  124. self.container.addWidget(self.canvas) # Qt
  125. # Copy a bitmap of the canvas for quick animation.
  126. # Update every time the canvas is re-drawn.
  127. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  128. # ################### NOT IMPLEMENTED YET - EXPERIMENTAL #######################
  129. # ## Bitmap Cache
  130. # self.cache = CanvasCache(self, self.app)
  131. # self.cache_thread = QtCore.QThread()
  132. # self.cache.moveToThread(self.cache_thread)
  133. # # super(PlotCanvas, self).connect(self.cache_thread, QtCore.SIGNAL("started()"), self.cache.run)
  134. # self.cache_thread.started.connect(self.cache.run)
  135. #
  136. # self.cache_thread.start()
  137. # self.cache.new_screen.connect(self.on_new_screen)
  138. # ##############################################################################
  139. # Events
  140. self.mp = self.graph_event_connect('button_press_event', self.on_mouse_press)
  141. self.mr = self.graph_event_connect('button_release_event', self.on_mouse_release)
  142. self.mm = self.graph_event_connect('motion_notify_event', self.on_mouse_move)
  143. # self.canvas.connect('configure-event', self.auto_adjust_axes)
  144. self.aaa = self.graph_event_connect('resize_event', self.auto_adjust_axes)
  145. # self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  146. # self.canvas.connect("scroll-event", self.on_scroll)
  147. self.osc = self.graph_event_connect('scroll_event', self.on_scroll)
  148. # self.graph_event_connect('key_press_event', self.on_key_down)
  149. # self.graph_event_connect('key_release_event', self.on_key_up)
  150. self.odr = self.graph_event_connect('draw_event', self.on_draw)
  151. self.key = None
  152. self.pan_axes = []
  153. self.panning = False
  154. self.mouse = [0, 0]
  155. # signal is the mouse is dragging
  156. self.is_dragging = False
  157. # signal if there is a doubleclick
  158. self.is_dblclk = False
  159. def graph_event_connect(self, event_name, callback):
  160. """
  161. Attach an event handler to the canvas through the Matplotlib interface.
  162. :param event_name: Name of the event
  163. :type event_name: str
  164. :param callback: Function to call
  165. :type callback: func
  166. :return: Connection id
  167. :rtype: int
  168. """
  169. if event_name == 'mouse_move':
  170. event_name = 'motion_notify_event'
  171. if event_name == 'mouse_press':
  172. event_name = 'button_press_event'
  173. if event_name == 'mouse_release':
  174. event_name = 'button_release_event'
  175. if event_name == 'mouse_double_click':
  176. return self.double_click.connect(callback)
  177. if event_name == 'key_press':
  178. event_name = 'key_press_event'
  179. return self.canvas.mpl_connect(event_name, callback)
  180. def graph_event_disconnect(self, cid):
  181. """
  182. Disconnect callback with the give id.
  183. :param cid: Callback id.
  184. :return: None
  185. """
  186. # self.double_click.disconnect(cid)
  187. self.canvas.mpl_disconnect(cid)
  188. def on_new_screen(self):
  189. pass
  190. # log.debug("Cache updated the screen!")
  191. def new_cursor(self, axes=None):
  192. # if axes is None:
  193. # c = MplCursor(axes=self.axes, color='black', linewidth=1)
  194. # else:
  195. # c = MplCursor(axes=axes, color='black', linewidth=1)
  196. c = FakeCursor()
  197. try:
  198. c.mouse_state_updated.connect(self.clear_cursor)
  199. except Exception as e:
  200. print(str(e))
  201. return c
  202. def draw_cursor(self, x_pos, y_pos):
  203. """
  204. Draw a cursor at the mouse grid snapped position
  205. :param x_pos: mouse x position
  206. :param y_pos: mouse y position
  207. :return:
  208. """
  209. # there is no point in drawing mouse cursor when panning as it jumps in a confusing way
  210. if self.app.app_cursor.enabled is True and self.panning is False:
  211. try:
  212. x, y = self.app.geo_editor.snap(x_pos, y_pos)
  213. # Pointer (snapped)
  214. elements = self.axes.plot(x, y, 'k+', ms=40, mew=2, animated=True)
  215. for el in elements:
  216. self.axes.draw_artist(el)
  217. except Exception as e:
  218. # this happen at app initialization since self.app.geo_editor does not exist yet
  219. # I could reshuffle the object instantiating order but what's the point? I could crash something else
  220. # and that's pythonic, too
  221. pass
  222. self.canvas.blit(self.axes.bbox)
  223. def clear_cursor(self, state):
  224. if state is True:
  225. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  226. else:
  227. self.canvas.restore_region(self.background)
  228. self.canvas.blit(self.axes.bbox)
  229. def on_key_down(self, event):
  230. """
  231. :param event:
  232. :return:
  233. """
  234. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  235. self.key = event.key
  236. def on_key_up(self, event):
  237. """
  238. :param event:
  239. :return:
  240. """
  241. self.key = None
  242. def connect(self, event_name, callback):
  243. """
  244. Attach an event handler to the canvas through the native Qt interface.
  245. :param event_name: Name of the event
  246. :type event_name: str
  247. :param callback: Function to call
  248. :type callback: function
  249. :return: Nothing
  250. """
  251. self.canvas.connect(event_name, callback)
  252. def clear(self):
  253. """
  254. Clears axes and figure.
  255. :return: None
  256. """
  257. # Clear
  258. self.axes.cla()
  259. try:
  260. self.figure.clf()
  261. except KeyError:
  262. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  263. # Re-build
  264. self.figure.add_axes(self.axes)
  265. self.axes.set_aspect(1)
  266. self.axes.grid(True)
  267. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  268. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  269. self.adjust_axes(-10, -10, 100, 100)
  270. # Re-draw
  271. self.canvas.draw_idle()
  272. def redraw(self):
  273. """
  274. Created only to serve for compatibility with the VisPy plotcanvas (the other graphic engine, 3D)
  275. :return:
  276. """
  277. self.clear()
  278. def adjust_axes(self, xmin, ymin, xmax, ymax):
  279. """
  280. Adjusts all axes while maintaining the use of the whole canvas
  281. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  282. request that will be modified to fit these restrictions.
  283. :param xmin: Requested minimum value for the X axis.
  284. :type xmin: float
  285. :param ymin: Requested minimum value for the Y axis.
  286. :type ymin: float
  287. :param xmax: Requested maximum value for the X axis.
  288. :type xmax: float
  289. :param ymax: Requested maximum value for the Y axis.
  290. :type ymax: float
  291. :return: None
  292. """
  293. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  294. if not self.app.collection.get_list():
  295. xmin = -10
  296. ymin = -10
  297. xmax = 100
  298. ymax = 100
  299. width = xmax - xmin
  300. height = ymax - ymin
  301. try:
  302. r = width / height
  303. except ZeroDivisionError:
  304. FlatCAMApp.App.log.error("Height is %f" % height)
  305. return
  306. canvas_w, canvas_h = self.canvas.get_width_height()
  307. canvas_r = float(canvas_w) / canvas_h
  308. x_ratio = float(self.x_margin) / canvas_w
  309. y_ratio = float(self.y_margin) / canvas_h
  310. if r > canvas_r:
  311. ycenter = (ymin + ymax) / 2.0
  312. newheight = height * r / canvas_r
  313. ymin = ycenter - newheight / 2.0
  314. ymax = ycenter + newheight / 2.0
  315. else:
  316. xcenter = (xmax + xmin) / 2.0
  317. newwidth = width * canvas_r / r
  318. xmin = xcenter - newwidth / 2.0
  319. xmax = xcenter + newwidth / 2.0
  320. # Adjust axes
  321. for ax in self.figure.get_axes():
  322. if ax._label != 'base':
  323. ax.set_frame_on(False) # No frame
  324. ax.set_xticks([]) # No tick
  325. ax.set_yticks([]) # No ticks
  326. ax.patch.set_visible(False) # No background
  327. ax.set_aspect(1)
  328. ax.set_xlim((xmin, xmax))
  329. ax.set_ylim((ymin, ymax))
  330. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  331. # Sync re-draw to proper paint on form resize
  332. self.canvas.draw()
  333. # #### Temporary place-holder for cached update #####
  334. self.update_screen_request.emit([0, 0, 0, 0, 0])
  335. def auto_adjust_axes(self, *args):
  336. """
  337. Calls ``adjust_axes()`` using the extents of the base axes.
  338. :rtype : None
  339. :return: None
  340. """
  341. xmin, xmax = self.axes.get_xlim()
  342. ymin, ymax = self.axes.get_ylim()
  343. self.adjust_axes(xmin, ymin, xmax, ymax)
  344. def fit_view(self):
  345. self.auto_adjust_axes()
  346. def zoom(self, factor, center=None):
  347. """
  348. Zooms the plot by factor around a given
  349. center point. Takes care of re-drawing.
  350. :param factor: Number by which to scale the plot.
  351. :type factor: float
  352. :param center: Coordinates [x, y] of the point around which to scale the plot.
  353. :type center: list
  354. :return: None
  355. """
  356. factor = 1 / factor
  357. xmin, xmax = self.axes.get_xlim()
  358. ymin, ymax = self.axes.get_ylim()
  359. width = xmax - xmin
  360. height = ymax - ymin
  361. if center is None or center == [None, None]:
  362. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  363. # For keeping the point at the pointer location
  364. relx = (xmax - center[0]) / width
  365. rely = (ymax - center[1]) / height
  366. new_width = width / factor
  367. new_height = height / factor
  368. xmin = center[0] - new_width * (1 - relx)
  369. xmax = center[0] + new_width * relx
  370. ymin = center[1] - new_height * (1 - rely)
  371. ymax = center[1] + new_height * rely
  372. # Adjust axes
  373. for ax in self.figure.get_axes():
  374. ax.set_xlim((xmin, xmax))
  375. ax.set_ylim((ymin, ymax))
  376. # Async re-draw
  377. self.canvas.draw_idle()
  378. # #### Temporary place-holder for cached update #####
  379. self.update_screen_request.emit([0, 0, 0, 0, 0])
  380. def pan(self, x, y):
  381. xmin, xmax = self.axes.get_xlim()
  382. ymin, ymax = self.axes.get_ylim()
  383. width = xmax - xmin
  384. height = ymax - ymin
  385. # Adjust axes
  386. for ax in self.figure.get_axes():
  387. ax.set_xlim((xmin + x * width, xmax + x * width))
  388. ax.set_ylim((ymin + y * height, ymax + y * height))
  389. # Re-draw
  390. self.canvas.draw_idle()
  391. # #### Temporary place-holder for cached update #####
  392. self.update_screen_request.emit([0, 0, 0, 0, 0])
  393. def new_axes(self, name):
  394. """
  395. Creates and returns an Axes object attached to this object's Figure.
  396. :param name: Unique label for the axes.
  397. :return: Axes attached to the figure.
  398. :rtype: Axes
  399. """
  400. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  401. def remove_current_axes(self):
  402. """
  403. :return: The name of the deleted axes
  404. """
  405. axes_to_remove = self.figure.axes.gca()
  406. current_axes_name = deepcopy(axes_to_remove._label)
  407. self.figure.axes.remove(axes_to_remove)
  408. return current_axes_name
  409. def on_scroll(self, event):
  410. """
  411. Scroll event handler.
  412. :param event: Event object containing the event information.
  413. :return: None
  414. """
  415. # So it can receive key presses
  416. # self.canvas.grab_focus()
  417. self.canvas.setFocus()
  418. # Event info
  419. # z, direction = event.get_scroll_direction()
  420. if self.key is None:
  421. if event.button == 'up':
  422. self.zoom(1 / 1.5, self.mouse)
  423. else:
  424. self.zoom(1.5, self.mouse)
  425. return
  426. if self.key == 'shift':
  427. if event.button == 'up':
  428. self.pan(0.3, 0)
  429. else:
  430. self.pan(-0.3, 0)
  431. return
  432. if self.key == 'control':
  433. if event.button == 'up':
  434. self.pan(0, 0.3)
  435. else:
  436. self.pan(0, -0.3)
  437. return
  438. def on_mouse_press(self, event):
  439. self.is_dragging = True
  440. # Check for middle mouse button press
  441. if self.app.defaults["global_pan_button"] == '2':
  442. pan_button = 3 # right button for Matplotlib
  443. else:
  444. pan_button = 2 # middle button for Matplotlib
  445. if event.button == pan_button:
  446. # Prepare axes for pan (using 'matplotlib' pan function)
  447. self.pan_axes = []
  448. for a in self.figure.get_axes():
  449. if (event.x is not None and event.y is not None and a.in_axes(event) and
  450. a.get_navigate() and a.can_pan()):
  451. a.start_pan(event.x, event.y, 1)
  452. self.pan_axes.append(a)
  453. # Set pan view flag
  454. if len(self.pan_axes) > 0:
  455. self.panning = True
  456. if event.dblclick:
  457. self.double_click.emit(event)
  458. def on_mouse_release(self, event):
  459. self.is_dragging = False
  460. # Check for middle mouse button release to complete pan procedure
  461. # Check for middle mouse button press
  462. if self.app.defaults["global_pan_button"] == '2':
  463. pan_button = 3 # right button for Matplotlib
  464. else:
  465. pan_button = 2 # middle button for Matplotlib
  466. if event.button == pan_button:
  467. for a in self.pan_axes:
  468. a.end_pan()
  469. # Clear pan flag
  470. self.panning = False
  471. # And update the cursor
  472. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  473. def on_mouse_move(self, event):
  474. """
  475. Mouse movement event handler. Stores the coordinates. Updates view on pan.
  476. :param event: Contains information about the event.
  477. :return: None
  478. """
  479. try:
  480. x = float(event.xdata)
  481. y = float(event.ydata)
  482. except TypeError:
  483. return
  484. self.mouse = [event.xdata, event.ydata]
  485. self.canvas.restore_region(self.background)
  486. # Update pan view on mouse move
  487. if self.panning is True:
  488. for a in self.pan_axes:
  489. a.drag_pan(1, event.key, event.x, event.y)
  490. # x_pan, y_pan = self.app.geo_editor.snap(event.xdata, event.ydata)
  491. # self.draw_cursor(x_pos=x_pan, y_pos=y_pan)
  492. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  493. self.canvas.draw_idle()
  494. # #### Temporary place-holder for cached update #####
  495. self.update_screen_request.emit([0, 0, 0, 0, 0])
  496. self.draw_cursor(x_pos=x, y_pos=y)
  497. # self.canvas.blit(self.axes.bbox)
  498. def translate_coords(self, position):
  499. """
  500. This does not do much. It's just for code compatibility
  501. :param position: Mouse event position
  502. :return: Tuple with mouse position
  503. """
  504. return position[0], position[1]
  505. def on_draw(self, renderer):
  506. # Store background on canvas redraw
  507. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  508. def get_axes_pixelsize(self):
  509. """
  510. Axes size in pixels.
  511. :return: Pixel width and height
  512. :rtype: tuple
  513. """
  514. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  515. width, height = bbox.width, bbox.height
  516. width *= self.figure.dpi
  517. height *= self.figure.dpi
  518. return width, height
  519. def get_density(self):
  520. """
  521. Returns unit length per pixel on horizontal
  522. and vertical axes.
  523. :return: X and Y density
  524. :rtype: tuple
  525. """
  526. xpx, ypx = self.get_axes_pixelsize()
  527. xmin, xmax = self.axes.get_xlim()
  528. ymin, ymax = self.axes.get_ylim()
  529. width = xmax - xmin
  530. height = ymax - ymin
  531. return width / xpx, height / ypx
  532. class FakeCursor(QtCore.QObject):
  533. """
  534. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  535. This way I don't have to chane (disable) things related to the cursor all over when
  536. using the low performance Matplotlib 2D graphic engine.
  537. """
  538. mouse_state_updated = pyqtSignal(bool)
  539. def __init__(self):
  540. super().__init__()
  541. self._enabled = True
  542. @property
  543. def enabled(self):
  544. return True if self._enabled else False
  545. @enabled.setter
  546. def enabled(self, value):
  547. self._enabled = value
  548. self.mouse_state_updated.emit(value)
  549. def set_data(self, pos, **kwargs):
  550. """Internal event handler to draw the cursor when the mouse moves."""
  551. pass
  552. class ShapeCollectionLegacy:
  553. """
  554. This will create the axes for each collection of shapes and will also
  555. hold the collection of shapes into a dict self._shapes.
  556. This handles the shapes redraw on canvas.
  557. """
  558. def __init__(self, obj, app, name=None, annotation_job=None):
  559. """
  560. :param obj: this is the object to which the shapes collection is attached and for
  561. which it will have to draw shapes
  562. :param app: this is the FLatCAM.App usually, needed because we have to access attributes there
  563. :param name: this is the name given to the Matplotlib axes; it needs to be unique due of Matplotlib requurements
  564. :param annotation_job: make this True if the job needed is just for annotation
  565. """
  566. self.obj = obj
  567. self.app = app
  568. self.annotation_job = annotation_job
  569. self._shapes = dict()
  570. self.shape_dict = dict()
  571. self.shape_id = 0
  572. self._color = None
  573. self._face_color = None
  574. self._visible = True
  575. self._update = False
  576. self._alpha = None
  577. self._tool_tolerance = None
  578. self._tooldia = None
  579. self._obj = None
  580. self._gcode_parsed = None
  581. if name is None:
  582. axes_name = self.obj.options['name']
  583. else:
  584. axes_name = name
  585. # Axes must exist and be attached to canvas.
  586. if axes_name not in self.app.plotcanvas.figure.axes:
  587. self.axes = self.app.plotcanvas.new_axes(axes_name)
  588. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  589. update=False, layer=1, tolerance=0.01, obj=None, gcode_parsed=None, tool_tolerance=None, tooldia=None):
  590. """
  591. This function will add shapes to the shape collection
  592. :param shape: the Shapely shape to be added to the shape collection
  593. :param color: edge color of the shape, hex value
  594. :param face_color: the body color of the shape, hex value
  595. :param alpha: level of transparency of the shape [0.0 ... 1.0]; Float
  596. :param visible: if True will allow the shapes to be added
  597. :param update: not used; just for compatibility with VIsPy canvas
  598. :param layer: just for compatibility with VIsPy canvas
  599. :param tolerance: just for compatibility with VIsPy canvas
  600. :param obj: not used
  601. :param gcode_parsed: not used; just for compatibility with VIsPy canvas
  602. :param tool_tolerance: just for compatibility with VIsPy canvas
  603. :param tooldia:
  604. :return:
  605. """
  606. self._color = color[:-2] if color is not None else None
  607. self._face_color = face_color[:-2] if face_color is not None else None
  608. self._alpha = int(face_color[-2:], 16) / 255 if face_color is not None else 0.75
  609. if alpha is not None:
  610. self._alpha = alpha
  611. self._visible = visible
  612. self._update = update
  613. # CNCJob object related arguments
  614. self._obj = obj
  615. self._gcode_parsed = gcode_parsed
  616. self._tool_tolerance = tool_tolerance
  617. self._tooldia = tooldia
  618. # if self._update:
  619. # self.clear()
  620. try:
  621. for sh in shape:
  622. self.shape_id += 1
  623. self.shape_dict.update({
  624. 'color': self._color,
  625. 'face_color': self._face_color,
  626. 'alpha': self._alpha,
  627. 'shape': sh
  628. })
  629. self._shapes.update({
  630. self.shape_id: deepcopy(self.shape_dict)
  631. })
  632. except TypeError:
  633. self.shape_id += 1
  634. self.shape_dict.update({
  635. 'color': self._color,
  636. 'face_color': self._face_color,
  637. 'alpha': self._alpha,
  638. 'shape': shape
  639. })
  640. self._shapes.update({
  641. self.shape_id: deepcopy(self.shape_dict)
  642. })
  643. return self.shape_id
  644. def clear(self, update=None):
  645. """
  646. Clear the canvas of the shapes.
  647. :param update:
  648. :return: None
  649. """
  650. self._shapes.clear()
  651. self.shape_id = 0
  652. self.axes.cla()
  653. try:
  654. self.app.plotcanvas.auto_adjust_axes()
  655. except Exception as e:
  656. log.debug("ShapeCollectionLegacy.clear() --> %s" % str(e))
  657. if update is True:
  658. self.redraw()
  659. def redraw(self):
  660. """
  661. This draw the shapes in the shapes collection, on canvas
  662. :return: None
  663. """
  664. path_num = 0
  665. local_shapes = deepcopy(self._shapes)
  666. try:
  667. obj_type = self.obj.kind
  668. except AttributeError:
  669. obj_type = 'utility'
  670. if self._visible:
  671. for element in local_shapes:
  672. if obj_type == 'excellon':
  673. # Plot excellon (All polygons?)
  674. if self.obj.options["solid"] and isinstance(local_shapes[element]['shape'], Polygon):
  675. patch = PolygonPatch(local_shapes[element]['shape'],
  676. facecolor="#C40000",
  677. edgecolor="#750000",
  678. alpha=local_shapes[element]['alpha'],
  679. zorder=3)
  680. self.axes.add_patch(patch)
  681. else:
  682. x, y = local_shapes[element]['shape'].exterior.coords.xy
  683. self.axes.plot(x, y, 'r-')
  684. for ints in local_shapes[element]['shape'].interiors:
  685. x, y = ints.coords.xy
  686. self.axes.plot(x, y, 'o-')
  687. elif obj_type == 'geometry':
  688. if type(local_shapes[element]['shape']) == Polygon:
  689. x, y = local_shapes[element]['shape'].exterior.coords.xy
  690. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  691. for ints in local_shapes[element]['shape'].interiors:
  692. x, y = ints.coords.xy
  693. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  694. elif type(local_shapes[element]['shape']) == LineString or \
  695. type(local_shapes[element]['shape']) == LinearRing:
  696. x, y = local_shapes[element]['shape'].coords.xy
  697. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  698. elif obj_type == 'gerber':
  699. if self.obj.options["multicolored"]:
  700. linespec = '-'
  701. else:
  702. linespec = 'k-'
  703. if self.obj.options["solid"]:
  704. try:
  705. patch = PolygonPatch(local_shapes[element]['shape'],
  706. facecolor=local_shapes[element]['face_color'],
  707. edgecolor=local_shapes[element]['color'],
  708. alpha=local_shapes[element]['alpha'],
  709. zorder=2)
  710. self.axes.add_patch(patch)
  711. except AssertionError:
  712. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  713. FlatCAMApp.App.log.warning(str(element))
  714. else:
  715. x, y = local_shapes[element]['shape'].exterior.xy
  716. self.axes.plot(x, y, linespec)
  717. for ints in local_shapes[element]['shape'].interiors:
  718. x, y = ints.coords.xy
  719. self.axes.plot(x, y, linespec)
  720. elif obj_type == 'cncjob':
  721. if local_shapes[element]['face_color'] is None:
  722. linespec = '--'
  723. linecolor = local_shapes[element]['color']
  724. # if geo['kind'][0] == 'C':
  725. # linespec = 'k-'
  726. x, y = local_shapes[element]['shape'].coords.xy
  727. self.axes.plot(x, y, linespec, color=linecolor)
  728. else:
  729. path_num += 1
  730. if self.obj.ui.annotation_cb.get_value():
  731. if isinstance(local_shapes[element]['shape'], Polygon):
  732. self.axes.annotate(
  733. str(path_num),
  734. xy=local_shapes[element]['shape'].exterior.coords[0],
  735. xycoords='data', fontsize=20)
  736. else:
  737. self.axes.annotate(
  738. str(path_num),
  739. xy=local_shapes[element]['shape'].coords[0],
  740. xycoords='data', fontsize=20)
  741. patch = PolygonPatch(local_shapes[element]['shape'],
  742. facecolor=local_shapes[element]['face_color'],
  743. edgecolor=local_shapes[element]['color'],
  744. alpha=local_shapes[element]['alpha'], zorder=2)
  745. self.axes.add_patch(patch)
  746. elif obj_type == 'utility':
  747. # not a FlatCAM object, must be utility
  748. if local_shapes[element]['face_color']:
  749. try:
  750. patch = PolygonPatch(local_shapes[element]['shape'],
  751. facecolor=local_shapes[element]['face_color'],
  752. edgecolor=local_shapes[element]['color'],
  753. alpha=local_shapes[element]['alpha'],
  754. zorder=2)
  755. self.axes.add_patch(patch)
  756. except Exception as e:
  757. log.debug("ShapeCollectionLegacy.redraw() --> %s" % str(e))
  758. else:
  759. if isinstance(local_shapes[element]['shape'], Polygon):
  760. x, y = local_shapes[element]['shape'].exterior.xy
  761. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  762. for ints in local_shapes[element]['shape'].interiors:
  763. x, y = ints.coords.xy
  764. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  765. else:
  766. x, y = local_shapes[element]['shape'].coords.xy
  767. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  768. self.app.plotcanvas.auto_adjust_axes()
  769. def set(self, text, pos, visible=True, font_size=16, color=None):
  770. """
  771. This will set annotations on the canvas.
  772. :param text: a list of text elements to be used as annotations
  773. :param pos: a list of positions for showing the text elements above
  774. :param visible: if True will display annotations, if False will clear them on canvas
  775. :param font_size: the font size or the annotations
  776. :param color: color of the annotations
  777. :return: None
  778. """
  779. if color is None:
  780. color = "#000000FF"
  781. if visible is not True:
  782. self.clear()
  783. return
  784. if len(text) != len(pos):
  785. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not annotate due of a difference between the number "
  786. "of text elements and the number of text positions."))
  787. return
  788. for idx in range(len(text)):
  789. try:
  790. self.axes.annotate(text[idx], xy=pos[idx], xycoords='data', fontsize=font_size, color=color)
  791. except Exception as e:
  792. log.debug("ShapeCollectionLegacy.set() --> %s" % str(e))
  793. self.app.plotcanvas.auto_adjust_axes()
  794. @property
  795. def visible(self):
  796. return self._visible
  797. @visible.setter
  798. def visible(self, value):
  799. if value is False:
  800. self.axes.cla()
  801. self.app.plotcanvas.auto_adjust_axes()
  802. else:
  803. if self._visible is False:
  804. self.redraw()
  805. self._visible = value
  806. @property
  807. def enabled(self):
  808. return self._visible
  809. @enabled.setter
  810. def enabled(self, value):
  811. if value is False:
  812. self.axes.cla()
  813. self.app.plotcanvas.auto_adjust_axes()
  814. else:
  815. if self._visible is False:
  816. self.redraw()
  817. self._visible = value
  818. # class MplCursor(Cursor):
  819. # """
  820. # Unfortunately this gets attached to the current axes and if a new axes is added
  821. # it will not be showed until that axes is deleted.
  822. # Not the kind of behavior needed here so I don't use it anymore.
  823. # """
  824. # def __init__(self, axes, color='red', linewidth=1):
  825. #
  826. # super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  827. # self._enabled = True
  828. #
  829. # self.axes = axes
  830. # self.color = color
  831. # self.linewidth = linewidth
  832. #
  833. # self.x = None
  834. # self.y = None
  835. #
  836. # @property
  837. # def enabled(self):
  838. # return True if self._enabled else False
  839. #
  840. # @enabled.setter
  841. # def enabled(self, value):
  842. # self._enabled = value
  843. # self.visible = self._enabled
  844. # self.canvas.draw()
  845. #
  846. # def onmove(self, event):
  847. # pass
  848. #
  849. # def set_data(self, event, pos):
  850. # """Internal event handler to draw the cursor when the mouse moves."""
  851. # self.x = pos[0]
  852. # self.y = pos[1]
  853. #
  854. # if self.ignore(event):
  855. # return
  856. # if not self.canvas.widgetlock.available(self):
  857. # return
  858. # if event.inaxes != self.ax:
  859. # self.linev.set_visible(False)
  860. # self.lineh.set_visible(False)
  861. #
  862. # if self.needclear:
  863. # self.canvas.draw()
  864. # self.needclear = False
  865. # return
  866. # self.needclear = True
  867. # if not self.visible:
  868. # return
  869. # self.linev.set_xdata((self.x, self.x))
  870. #
  871. # self.lineh.set_ydata((self.y, self.y))
  872. # self.linev.set_visible(self.visible and self.vertOn)
  873. # self.lineh.set_visible(self.visible and self.horizOn)
  874. #
  875. # self._update()