PlotCanvasLegacy.py 60 KB

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