PlotCanvasLegacy.py 44 KB

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