PlotCanvasLegacy.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  243. # all CNC have a limited workspace
  244. if self.app.defaults['global_workspace'] is True:
  245. self.draw_workspace(workspace_size=self.app.defaults["global_workspaceT"])
  246. if self.app.defaults['global_hud'] is True:
  247. self.on_toggle_hud(state=True)
  248. def on_toggle_hud(self, state):
  249. if state:
  250. self.hud_enabled = True
  251. self.text_hud.add_artist()
  252. self.app.defaults['global_hud'] = True
  253. self.fcapp.ui.hud_label.setStyleSheet("""
  254. QLabel
  255. {
  256. color: black;
  257. background-color: lightblue;
  258. }
  259. """)
  260. else:
  261. self.hud_enabled = False
  262. self.text_hud.remove_artist()
  263. self.app.defaults['global_hud'] = False
  264. self.fcapp.ui.hud_label.setStyleSheet("")
  265. self.canvas.draw()
  266. class Thud(QtCore.QObject):
  267. text_changed = QtCore.pyqtSignal(str)
  268. def __init__(self, plotcanvas):
  269. super().__init__()
  270. self.p = plotcanvas
  271. units = self.p.app.defaults['units']
  272. self._text = 'Dx: %s [%s]\nDy: %s [%s]\n\nX: %s [%s]\nY: %s [%s]' % \
  273. ('0.0000', units, '0.0000', units, '0.0000', units, '0.0000', units)
  274. # set font size
  275. qsettings = QtCore.QSettings("Open Source", "FlatCAM")
  276. if qsettings.contains("hud_font_size"):
  277. # I multiply with 2.5 because this seems to be the difference between the value taken by the VisPy (3D)
  278. # and Matplotlib (Legacy2D FlatCAM graphic engine)
  279. fsize = int(qsettings.value('hud_font_size', type=int) * 2.5)
  280. else:
  281. fsize = 20
  282. self.hud_holder = AnchoredText(self._text, prop=dict(size=fsize), frameon=True, loc='upper left')
  283. self.hud_holder.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
  284. fc_color = self.p.rect_hud_color[:-2]
  285. fc_alpha = int(self.p.rect_hud_color[-2:], 16) / 255
  286. text_color = self.p.text_hud_color
  287. self.hud_holder.patch.set_facecolor(fc_color)
  288. self.hud_holder.patch.set_alpha(fc_alpha)
  289. self.hud_holder.patch.set_edgecolor((0, 0, 0, 0))
  290. self. hud_holder.txt._text.set_color(color=text_color)
  291. self.text_changed.connect(self.on_text_changed)
  292. @property
  293. def text(self):
  294. return self._text
  295. @text.setter
  296. def text(self, val):
  297. self.text_changed.emit(val)
  298. self._text = val
  299. def on_text_changed(self, txt):
  300. try:
  301. txt = txt.replace('\t', ' ')
  302. self.hud_holder.txt.set_text(txt)
  303. self.p.canvas.draw()
  304. except Exception:
  305. pass
  306. def add_artist(self):
  307. if self.hud_holder not in self.p.axes.artists:
  308. self.p.axes.add_artist(self.hud_holder)
  309. def remove_artist(self):
  310. if self.hud_holder in self.p.axes.artists:
  311. self.p.axes.artists.remove(self.hud_holder)
  312. def draw_workspace(self, workspace_size):
  313. """
  314. Draw a rectangular shape on canvas to specify our valid workspace.
  315. :param workspace_size: the workspace size; tuple
  316. :return:
  317. """
  318. try:
  319. if self.app.defaults['units'].upper() == 'MM':
  320. dims = self.pagesize_dict[workspace_size]
  321. else:
  322. dims = (self.pagesize_dict[workspace_size][0]/25.4, self.pagesize_dict[workspace_size][1]/25.4)
  323. except Exception as e:
  324. log.debug("PlotCanvasLegacy.draw_workspace() --> %s" % str(e))
  325. return
  326. if self.app.defaults['global_workspace_orientation'] == 'l':
  327. dims = (dims[1], dims[0])
  328. xdata = [0, dims[0], dims[0], 0, 0]
  329. ydata = [0, 0, dims[1], dims[1], 0]
  330. if self.workspace_line not in self.axes.lines:
  331. self.workspace_line = Line2D(xdata=xdata, ydata=ydata, linewidth=2, antialiased=True, color='#b34d4d')
  332. self.axes.add_line(self.workspace_line)
  333. self.canvas.draw()
  334. self.app.ui.wplace_label.set_value(workspace_size[:3])
  335. self.app.ui.wplace_label.setToolTip(workspace_size)
  336. self.fcapp.ui.wplace_label.setStyleSheet("""
  337. QLabel
  338. {
  339. color: black;
  340. background-color: lightgreen;
  341. }
  342. """)
  343. def delete_workspace(self):
  344. try:
  345. self.axes.lines.remove(self.workspace_line)
  346. self.canvas.draw()
  347. except Exception:
  348. pass
  349. self.fcapp.ui.wplace_label.setStyleSheet("")
  350. def graph_event_connect(self, event_name, callback):
  351. """
  352. Attach an event handler to the canvas through the Matplotlib interface.
  353. :param event_name: Name of the event
  354. :type event_name: str
  355. :param callback: Function to call
  356. :type callback: func
  357. :return: Connection id
  358. :rtype: int
  359. """
  360. if event_name == 'mouse_move':
  361. event_name = 'motion_notify_event'
  362. if event_name == 'mouse_press':
  363. event_name = 'button_press_event'
  364. if event_name == 'mouse_release':
  365. event_name = 'button_release_event'
  366. if event_name == 'mouse_double_click':
  367. return self.double_click.connect(callback)
  368. if event_name == 'key_press':
  369. event_name = 'key_press_event'
  370. return self.canvas.mpl_connect(event_name, callback)
  371. def graph_event_disconnect(self, cid):
  372. """
  373. Disconnect callback with the give id.
  374. :param cid: Callback id.
  375. :return: None
  376. """
  377. self.canvas.mpl_disconnect(cid)
  378. def on_new_screen(self):
  379. pass
  380. # log.debug("Cache updated the screen!")
  381. def new_cursor(self, axes=None, big=None):
  382. # if axes is None:
  383. # c = MplCursor(axes=self.axes, color='black', linewidth=1)
  384. # else:
  385. # c = MplCursor(axes=axes, color='black', linewidth=1)
  386. if self.app.defaults["global_cursor_color_enabled"]:
  387. color = self.app.defaults["global_cursor_color"]
  388. else:
  389. if self.app.defaults['global_theme'] == 'white':
  390. color = '#000000'
  391. else:
  392. color = '#FFFFFF'
  393. if big is True:
  394. self.big_cursor = True
  395. self.ch_line = self.axes.axhline(color=color, linewidth=self.app.defaults["global_cursor_width"])
  396. self.cv_line = self.axes.axvline(color=color, linewidth=self.app.defaults["global_cursor_width"])
  397. self.big_cursor_isdisabled = False
  398. else:
  399. self.big_cursor = False
  400. c = FakeCursor()
  401. c.mouse_state_updated.connect(self.clear_cursor)
  402. return c
  403. def draw_cursor(self, x_pos, y_pos, color=None):
  404. """
  405. Draw a cursor at the mouse grid snapped position
  406. :param x_pos: mouse x position
  407. :param y_pos: mouse y position
  408. :param color: custom color of the mouse
  409. :return:
  410. """
  411. # there is no point in drawing mouse cursor when panning as it jumps in a confusing way
  412. if self.app.app_cursor.enabled is True and self.panning is False:
  413. if color:
  414. color = color
  415. else:
  416. if self.app.defaults['global_theme'] == 'white':
  417. color = '#000000'
  418. else:
  419. color = '#FFFFFF'
  420. if self.big_cursor is False:
  421. try:
  422. x, y = self.snap(x_pos, y_pos)
  423. # Pointer (snapped)
  424. # The size of the cursor is multiplied by 1.65 because that value made the cursor similar with the
  425. # one in the OpenGL(3D) graphic engine
  426. pointer_size = int(float(self.app.defaults["global_cursor_size"]) * 1.65)
  427. elements = self.axes.plot(x, y, '+', color=color, ms=pointer_size,
  428. mew=self.app.defaults["global_cursor_width"], animated=True)
  429. for el in elements:
  430. self.axes.draw_artist(el)
  431. except Exception as e:
  432. # this happen at app initialization since self.app.geo_editor does not exist yet
  433. # I could reshuffle the object instantiating order but what's the point?
  434. # I could crash something else and that's pythonic, too
  435. log.debug("PlotCanvasLegacy.draw_cursor() big_cursor is False --> %s" % str(e))
  436. else:
  437. try:
  438. self.ch_line.set_markeredgewidth(self.app.defaults["global_cursor_width"])
  439. self.cv_line.set_markeredgewidth(self.app.defaults["global_cursor_width"])
  440. except Exception:
  441. pass
  442. try:
  443. x, y = self.app.geo_editor.snap(x_pos, y_pos)
  444. self.ch_line.set_ydata(y)
  445. self.cv_line.set_xdata(x)
  446. except Exception:
  447. # this happen at app initialization since self.app.geo_editor does not exist yet
  448. # I could reshuffle the object instantiating order but what's the point?
  449. # I could crash something else and that's pythonic, too
  450. pass
  451. self.canvas.draw_idle()
  452. self.canvas.blit(self.axes.bbox)
  453. def clear_cursor(self, state):
  454. if state is True:
  455. if self.big_cursor is True and self.big_cursor_isdisabled is True:
  456. if self.app.defaults["global_cursor_color_enabled"]:
  457. color = self.app.defaults["global_cursor_color"]
  458. else:
  459. if self.app.defaults['global_theme'] == 'white':
  460. color = '#000000'
  461. else:
  462. color = '#FFFFFF'
  463. self.ch_line = self.axes.axhline(color=color, linewidth=self.app.defaults["global_cursor_width"])
  464. self.cv_line = self.axes.axvline(color=color, linewidth=self.app.defaults["global_cursor_width"])
  465. self.big_cursor_isdisabled = False
  466. if self.app.defaults["global_cursor_color_enabled"] is True:
  467. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1], color=self.app.cursor_color_3D)
  468. else:
  469. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  470. else:
  471. if self.big_cursor is True:
  472. self.big_cursor_isdisabled = True
  473. try:
  474. self.ch_line.remove()
  475. self.cv_line.remove()
  476. self.canvas.draw_idle()
  477. except Exception as e:
  478. log.debug("PlotCanvasLegacy.clear_cursor() big_cursor is True --> %s" % str(e))
  479. self.canvas.restore_region(self.background)
  480. self.canvas.blit(self.axes.bbox)
  481. def on_key_down(self, event):
  482. """
  483. :param event:
  484. :return:
  485. """
  486. log.debug('on_key_down(): ' + str(event.key))
  487. self.key = event.key
  488. def on_key_up(self, event):
  489. """
  490. :param event:
  491. :return:
  492. """
  493. self.key = None
  494. def connect(self, event_name, callback):
  495. """
  496. Attach an event handler to the canvas through the native Qt interface.
  497. :param event_name: Name of the event
  498. :type event_name: str
  499. :param callback: Function to call
  500. :type callback: function
  501. :return: Nothing
  502. """
  503. self.canvas.connect(event_name, callback)
  504. def clear(self):
  505. """
  506. Clears axes and figure.
  507. :return: None
  508. """
  509. # Clear
  510. self.axes.cla()
  511. try:
  512. self.figure.clf()
  513. except KeyError:
  514. log.warning("KeyError in MPL figure.clf()")
  515. # Re-build
  516. self.figure.add_axes(self.axes)
  517. self.axes.set_aspect(1)
  518. self.axes.grid(True)
  519. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  520. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  521. self.adjust_axes(-10, -10, 100, 100)
  522. # Re-draw
  523. self.canvas.draw_idle()
  524. def redraw(self):
  525. """
  526. Created only to serve for compatibility with the VisPy plotcanvas (the other graphic engine, 3D)
  527. :return:
  528. """
  529. self.clear()
  530. def adjust_axes(self, xmin, ymin, xmax, ymax):
  531. """
  532. Adjusts all axes while maintaining the use of the whole canvas
  533. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  534. request that will be modified to fit these restrictions.
  535. :param xmin: Requested minimum value for the X axis.
  536. :type xmin: float
  537. :param ymin: Requested minimum value for the Y axis.
  538. :type ymin: float
  539. :param xmax: Requested maximum value for the X axis.
  540. :type xmax: float
  541. :param ymax: Requested maximum value for the Y axis.
  542. :type ymax: float
  543. :return: None
  544. """
  545. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  546. if not self.app.collection.get_list():
  547. xmin = -10
  548. ymin = -10
  549. xmax = 100
  550. ymax = 100
  551. width = xmax - xmin
  552. height = ymax - ymin
  553. try:
  554. r = width / height
  555. except ZeroDivisionError:
  556. log.error("Height is %f" % height)
  557. return
  558. canvas_w, canvas_h = self.canvas.get_width_height()
  559. canvas_r = float(canvas_w) / canvas_h
  560. x_ratio = float(self.x_margin) / canvas_w
  561. y_ratio = float(self.y_margin) / canvas_h
  562. if r > canvas_r:
  563. ycenter = (ymin + ymax) / 2.0
  564. newheight = height * r / canvas_r
  565. ymin = ycenter - newheight / 2.0
  566. ymax = ycenter + newheight / 2.0
  567. else:
  568. xcenter = (xmax + xmin) / 2.0
  569. newwidth = width * canvas_r / r
  570. xmin = xcenter - newwidth / 2.0
  571. xmax = xcenter + newwidth / 2.0
  572. # Adjust axes
  573. for ax in self.figure.get_axes():
  574. if ax._label != 'base':
  575. ax.set_frame_on(False) # No frame
  576. ax.set_xticks([]) # No tick
  577. ax.set_yticks([]) # No ticks
  578. ax.patch.set_visible(False) # No background
  579. ax.set_aspect(1)
  580. ax.set_xlim((xmin, xmax))
  581. ax.set_ylim((ymin, ymax))
  582. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  583. # Sync re-draw to proper paint on form resize
  584. self.canvas.draw()
  585. # #### Temporary place-holder for cached update #####
  586. self.update_screen_request.emit([0, 0, 0, 0, 0])
  587. def auto_adjust_axes(self, *args):
  588. """
  589. Calls ``adjust_axes()`` using the extents of the base axes.
  590. :rtype : None
  591. :return: None
  592. """
  593. xmin, xmax = self.axes.get_xlim()
  594. ymin, ymax = self.axes.get_ylim()
  595. self.adjust_axes(xmin, ymin, xmax, ymax)
  596. def fit_view(self):
  597. self.auto_adjust_axes()
  598. def fit_center(self, loc, rect=None):
  599. x = loc[0]
  600. y = loc[1]
  601. xmin, xmax = self.axes.get_xlim()
  602. ymin, ymax = self.axes.get_ylim()
  603. half_width = (xmax - xmin) / 2
  604. half_height = (ymax - ymin) / 2
  605. # Adjust axes
  606. for ax in self.figure.get_axes():
  607. ax.set_xlim((x - half_width, x + half_width))
  608. ax.set_ylim((y - half_height, y + half_height))
  609. # Re-draw
  610. self.canvas.draw()
  611. # #### Temporary place-holder for cached update #####
  612. self.update_screen_request.emit([0, 0, 0, 0, 0])
  613. def zoom(self, factor, center=None):
  614. """
  615. Zooms the plot by factor around a given
  616. center point. Takes care of re-drawing.
  617. :param factor: Number by which to scale the plot.
  618. :type factor: float
  619. :param center: Coordinates [x, y] of the point around which to scale the plot.
  620. :type center: list
  621. :return: None
  622. """
  623. factor = 1 / factor
  624. xmin, xmax = self.axes.get_xlim()
  625. ymin, ymax = self.axes.get_ylim()
  626. width = xmax - xmin
  627. height = ymax - ymin
  628. if center is None or center == [None, None]:
  629. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  630. # For keeping the point at the pointer location
  631. relx = (xmax - center[0]) / width
  632. rely = (ymax - center[1]) / height
  633. new_width = width / factor
  634. new_height = height / factor
  635. xmin = center[0] - new_width * (1 - relx)
  636. xmax = center[0] + new_width * relx
  637. ymin = center[1] - new_height * (1 - rely)
  638. ymax = center[1] + new_height * rely
  639. # Adjust axes
  640. for ax in self.figure.get_axes():
  641. ax.set_xlim((xmin, xmax))
  642. ax.set_ylim((ymin, ymax))
  643. # Async re-draw
  644. self.canvas.draw_idle()
  645. # #### Temporary place-holder for cached update #####
  646. self.update_screen_request.emit([0, 0, 0, 0, 0])
  647. def pan(self, x, y, idle=True):
  648. xmin, xmax = self.axes.get_xlim()
  649. ymin, ymax = self.axes.get_ylim()
  650. width = xmax - xmin
  651. height = ymax - ymin
  652. # Adjust axes
  653. for ax in self.figure.get_axes():
  654. ax.set_xlim((xmin + x * width, xmax + x * width))
  655. ax.set_ylim((ymin + y * height, ymax + y * height))
  656. # Re-draw
  657. if idle:
  658. self.canvas.draw_idle()
  659. else:
  660. self.canvas.draw()
  661. # #### Temporary place-holder for cached update #####
  662. self.update_screen_request.emit([0, 0, 0, 0, 0])
  663. def new_axes(self, name):
  664. """
  665. Creates and returns an Axes object attached to this object's Figure.
  666. :param name: Unique label for the axes.
  667. :return: Axes attached to the figure.
  668. :rtype: Axes
  669. """
  670. new_ax = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  671. return new_ax
  672. def remove_current_axes(self):
  673. """
  674. :return: The name of the deleted axes
  675. """
  676. axes_to_remove = self.figure.axes.gca()
  677. current_axes_name = deepcopy(axes_to_remove._label)
  678. self.figure.axes.remove(axes_to_remove)
  679. return current_axes_name
  680. def on_scroll(self, event):
  681. """
  682. Scroll event handler.
  683. :param event: Event object containing the event information.
  684. :return: None
  685. """
  686. # So it can receive key presses
  687. # self.canvas.grab_focus()
  688. self.canvas.setFocus()
  689. # Event info
  690. # z, direction = event.get_scroll_direction()
  691. if self.key is None:
  692. if event.button == 'up':
  693. self.zoom(1 / 1.5, self.mouse)
  694. else:
  695. self.zoom(1.5, self.mouse)
  696. return
  697. if self.key == 'shift':
  698. if event.button == 'up':
  699. self.pan(0.3, 0)
  700. else:
  701. self.pan(-0.3, 0)
  702. return
  703. if self.key == 'control':
  704. if event.button == 'up':
  705. self.pan(0, 0.3)
  706. else:
  707. self.pan(0, -0.3)
  708. return
  709. def on_mouse_press(self, event):
  710. self.is_dragging = True
  711. self.mouse_press_pos = (event.x, event.y)
  712. # Check for middle mouse button press
  713. if self.app.defaults["global_pan_button"] == '2':
  714. pan_button = 3 # right button for Matplotlib
  715. else:
  716. pan_button = 2 # middle button for Matplotlib
  717. if event.button == pan_button:
  718. # Prepare axes for pan (using 'matplotlib' pan function)
  719. self.pan_axes = []
  720. for a in self.figure.get_axes():
  721. if (event.x is not None and event.y is not None and a.in_axes(event) and
  722. a.get_navigate() and a.can_pan()):
  723. a.start_pan(event.x, event.y, 1)
  724. self.pan_axes.append(a)
  725. # Set pan view flag
  726. if len(self.pan_axes) > 0:
  727. self.panning = True
  728. if event.dblclick:
  729. self.double_click.emit(event)
  730. def on_mouse_release(self, event):
  731. mouse_release_pos = (event.x, event.y)
  732. delta = 0.05
  733. if abs(self.distance(self.mouse_press_pos, mouse_release_pos)) < delta:
  734. self.is_dragging = False
  735. # Check for middle mouse button release to complete pan procedure
  736. # Check for middle mouse button press
  737. if self.app.defaults["global_pan_button"] == '2':
  738. pan_button = 3 # right button for Matplotlib
  739. else:
  740. pan_button = 2 # middle button for Matplotlib
  741. if event.button == pan_button:
  742. for a in self.pan_axes:
  743. a.end_pan()
  744. # Clear pan flag
  745. self.panning = False
  746. # And update the cursor
  747. if self.app.defaults["global_cursor_color_enabled"] is True:
  748. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1], color=self.app.cursor_color_3D)
  749. else:
  750. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  751. def on_mouse_move(self, event):
  752. """
  753. Mouse movement event handler. Stores the coordinates. Updates view on pan.
  754. :param event: Contains information about the event.
  755. :return: None
  756. """
  757. try:
  758. x = float(event.xdata)
  759. y = float(event.ydata)
  760. except TypeError:
  761. return
  762. self.mouse = [event.xdata, event.ydata]
  763. self.canvas.restore_region(self.background)
  764. # Update pan view on mouse move
  765. if self.panning is True:
  766. for a in self.pan_axes:
  767. a.drag_pan(1, event.key, event.x, event.y)
  768. # x_pan, y_pan = self.app.geo_editor.snap(event.xdata, event.ydata)
  769. # self.draw_cursor(x_pos=x_pan, y_pos=y_pan)
  770. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  771. self.canvas.draw_idle()
  772. # #### Temporary place-holder for cached update #####
  773. # self.update_screen_request.emit([0, 0, 0, 0, 0])
  774. if self.app.defaults["global_cursor_color_enabled"] is True:
  775. self.draw_cursor(x_pos=x, y_pos=y, color=self.app.cursor_color_3D)
  776. else:
  777. self.draw_cursor(x_pos=x, y_pos=y)
  778. # self.canvas.blit(self.axes.bbox)
  779. def translate_coords(self, position):
  780. """
  781. This does not do much. It's just for code compatibility
  782. :param position: Mouse event position
  783. :return: Tuple with mouse position
  784. """
  785. return position[0], position[1]
  786. def on_draw(self, renderer):
  787. # Store background on canvas redraw
  788. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  789. def get_axes_pixelsize(self):
  790. """
  791. Axes size in pixels.
  792. :return: Pixel width and height
  793. :rtype: tuple
  794. """
  795. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  796. width, height = bbox.width, bbox.height
  797. width *= self.figure.dpi
  798. height *= self.figure.dpi
  799. return width, height
  800. def get_density(self):
  801. """
  802. Returns unit length per pixel on horizontal
  803. and vertical axes.
  804. :return: X and Y density
  805. :rtype: tuple
  806. """
  807. xpx, ypx = self.get_axes_pixelsize()
  808. xmin, xmax = self.axes.get_xlim()
  809. ymin, ymax = self.axes.get_ylim()
  810. width = xmax - xmin
  811. height = ymax - ymin
  812. return width / xpx, height / ypx
  813. def snap(self, x, y):
  814. """
  815. Adjusts coordinates to snap settings.
  816. :param x: Input coordinate X
  817. :param y: Input coordinate Y
  818. :return: Snapped (x, y)
  819. """
  820. snap_x, snap_y = (x, y)
  821. snap_distance = np.Inf
  822. # ### Grid snap
  823. if self.app.grid_status():
  824. if self.app.defaults["global_gridx"] != 0:
  825. try:
  826. snap_x_ = round(x / float(self.app.defaults["global_gridx"])) * \
  827. float(self.app.defaults["global_gridx"])
  828. except TypeError:
  829. snap_x_ = x
  830. else:
  831. snap_x_ = x
  832. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  833. # and it will use the snap distance from GridX entry
  834. if self.app.ui.grid_gap_link_cb.isChecked():
  835. if self.app.defaults["global_gridx"] != 0:
  836. try:
  837. snap_y_ = round(y / float(self.app.defaults["global_gridx"])) * \
  838. float(self.app.defaults["global_gridx"])
  839. except TypeError:
  840. snap_y_ = y
  841. else:
  842. snap_y_ = y
  843. else:
  844. if self.app.defaults["global_gridy"] != 0:
  845. try:
  846. snap_y_ = round(y / float(self.app.defaults["global_gridy"])) * \
  847. float(self.app.defaults["global_gridy"])
  848. except TypeError:
  849. snap_y_ = y
  850. else:
  851. snap_y_ = y
  852. nearest_grid_distance = self.distance((x, y), (snap_x_, snap_y_))
  853. if nearest_grid_distance < snap_distance:
  854. snap_x, snap_y = (snap_x_, snap_y_)
  855. return snap_x, snap_y
  856. @staticmethod
  857. def distance(pt1, pt2):
  858. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  859. class FakeCursor(QtCore.QObject):
  860. """
  861. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  862. This way I don't have to chane (disable) things related to the cursor all over when
  863. using the low performance Matplotlib 2D graphic engine.
  864. """
  865. mouse_state_updated = pyqtSignal(bool)
  866. def __init__(self):
  867. super().__init__()
  868. self._enabled = True
  869. @property
  870. def enabled(self):
  871. return True if self._enabled else False
  872. @enabled.setter
  873. def enabled(self, value):
  874. self._enabled = value
  875. self.mouse_state_updated.emit(value)
  876. def set_data(self, pos, **kwargs):
  877. """Internal event handler to draw the cursor when the mouse moves."""
  878. return
  879. class ShapeCollectionLegacy:
  880. """
  881. This will create the axes for each collection of shapes and will also
  882. hold the collection of shapes into a dict self._shapes.
  883. This handles the shapes redraw on canvas.
  884. """
  885. def __init__(self, obj, app, name=None, annotation_job=None, linewidth=1):
  886. """
  887. :param obj: This is the object to which the shapes collection is attached and for
  888. which it will have to draw shapes
  889. :param app: This is the FLatCAM.App usually, needed because we have to access attributes there
  890. :param name: This is the name given to the Matplotlib axes; it needs to be unique due of
  891. Matplotlib requurements
  892. :param annotation_job: Make this True if the job needed is just for annotation
  893. :param linewidth: THe width of the line (outline where is the case)
  894. """
  895. self.obj = obj
  896. self.app = app
  897. self.annotation_job = annotation_job
  898. self._shapes = {}
  899. self.shape_dict = {}
  900. self.shape_id = 0
  901. self._color = None
  902. self._face_color = None
  903. self._visible = True
  904. self._update = False
  905. self._alpha = None
  906. self._tool_tolerance = None
  907. self._tooldia = None
  908. self._obj = None
  909. self._gcode_parsed = None
  910. self._linewidth = linewidth
  911. if name is None:
  912. axes_name = self.obj.options['name']
  913. else:
  914. axes_name = name
  915. # Axes must exist and be attached to canvas.
  916. if axes_name not in self.app.plotcanvas.figure.axes:
  917. self.axes = self.app.plotcanvas.new_axes(axes_name)
  918. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  919. update=False, layer=1, tolerance=0.01, obj=None, gcode_parsed=None, tool_tolerance=None, tooldia=None,
  920. linewidth=None):
  921. """
  922. This function will add shapes to the shape collection
  923. :param shape: the Shapely shape to be added to the shape collection
  924. :param color: edge color of the shape, hex value
  925. :param face_color: the body color of the shape, hex value
  926. :param alpha: level of transparency of the shape [0.0 ... 1.0]; Float
  927. :param visible: if True will allow the shapes to be added
  928. :param update: not used; just for compatibility with VIsPy canvas
  929. :param layer: just for compatibility with VIsPy canvas
  930. :param tolerance: just for compatibility with VIsPy canvas
  931. :param obj: not used
  932. :param gcode_parsed: not used; just for compatibility with VIsPy canvas
  933. :param tool_tolerance: just for compatibility with VIsPy canvas
  934. :param tooldia:
  935. :param linewidth: the width of the line
  936. :return:
  937. """
  938. self._color = color if color is not None else "#006E20"
  939. # self._face_color = face_color if face_color is not None else "#BBF268"
  940. self._face_color = face_color
  941. if linewidth is None:
  942. line_width = self._linewidth
  943. else:
  944. line_width = linewidth
  945. if len(self._color) > 7:
  946. self._color = self._color[:7]
  947. if self._face_color is not None:
  948. if len(self._face_color) > 7:
  949. self._face_color = self._face_color[:7]
  950. # self._alpha = int(self._face_color[-2:], 16) / 255
  951. self._alpha = 0.75
  952. if alpha is not None:
  953. self._alpha = alpha
  954. self._visible = visible
  955. self._update = update
  956. # CNCJob object related arguments
  957. self._obj = obj
  958. self._gcode_parsed = gcode_parsed
  959. self._tool_tolerance = tool_tolerance
  960. self._tooldia = tooldia
  961. # if self._update:
  962. # self.clear()
  963. try:
  964. for sh in shape:
  965. self.shape_id += 1
  966. self.shape_dict.update({
  967. 'color': self._color,
  968. 'face_color': self._face_color,
  969. 'linewidth': line_width,
  970. 'alpha': self._alpha,
  971. 'shape': sh
  972. })
  973. self._shapes.update({
  974. self.shape_id: deepcopy(self.shape_dict)
  975. })
  976. except TypeError:
  977. self.shape_id += 1
  978. self.shape_dict.update({
  979. 'color': self._color,
  980. 'face_color': self._face_color,
  981. 'linewidth': line_width,
  982. 'alpha': self._alpha,
  983. 'shape': shape
  984. })
  985. self._shapes.update({
  986. self.shape_id: deepcopy(self.shape_dict)
  987. })
  988. return self.shape_id
  989. def remove(self, shape_id, update=None):
  990. for k in list(self._shapes.keys()):
  991. if shape_id == k:
  992. self._shapes.pop(k, None)
  993. if update is True:
  994. self.redraw()
  995. def clear(self, update=None):
  996. """
  997. Clear the canvas of the shapes.
  998. :param update:
  999. :return: None
  1000. """
  1001. self._shapes.clear()
  1002. self.shape_id = 0
  1003. self.axes.cla()
  1004. try:
  1005. self.app.plotcanvas.auto_adjust_axes()
  1006. except Exception as e:
  1007. log.debug("ShapeCollectionLegacy.clear() --> %s" % str(e))
  1008. if update is True:
  1009. self.redraw()
  1010. def redraw(self, update_colors=None):
  1011. """
  1012. This draw the shapes in the shapes collection, on canvas
  1013. :return: None
  1014. """
  1015. path_num = 0
  1016. local_shapes = deepcopy(self._shapes)
  1017. try:
  1018. obj_type = self.obj.kind
  1019. except AttributeError:
  1020. obj_type = 'utility'
  1021. if self._visible:
  1022. # if we don't use this then when adding each new shape, the old ones will be added again, too
  1023. if obj_type == 'utility':
  1024. self.axes.patches.clear()
  1025. for element in local_shapes:
  1026. if obj_type == 'excellon':
  1027. # Plot excellon (All polygons?)
  1028. if self.obj.options["solid"] and isinstance(local_shapes[element]['shape'], Polygon):
  1029. try:
  1030. patch = PolygonPatch(local_shapes[element]['shape'],
  1031. facecolor="#C40000",
  1032. edgecolor="#750000",
  1033. alpha=local_shapes[element]['alpha'],
  1034. zorder=3,
  1035. linewidth=local_shapes[element]['linewidth']
  1036. )
  1037. self.axes.add_patch(patch)
  1038. except Exception as e:
  1039. log.debug("ShapeCollectionLegacy.redraw() excellon poly --> %s" % str(e))
  1040. else:
  1041. try:
  1042. x, y = local_shapes[element]['shape'].exterior.coords.xy
  1043. self.axes.plot(x, y, 'r-', linewidth=local_shapes[element]['linewidth'])
  1044. for ints in local_shapes[element]['shape'].interiors:
  1045. x, y = ints.coords.xy
  1046. self.axes.plot(x, y, 'o-', linewidth=local_shapes[element]['linewidth'])
  1047. except Exception as e:
  1048. log.debug("ShapeCollectionLegacy.redraw() excellon no poly --> %s" % str(e))
  1049. elif obj_type == 'geometry':
  1050. if type(local_shapes[element]['shape']) == Polygon:
  1051. try:
  1052. x, y = local_shapes[element]['shape'].exterior.coords.xy
  1053. self.axes.plot(x, y, local_shapes[element]['color'],
  1054. linestyle='-',
  1055. linewidth=local_shapes[element]['linewidth'])
  1056. for ints in local_shapes[element]['shape'].interiors:
  1057. x, y = ints.coords.xy
  1058. self.axes.plot(x, y, local_shapes[element]['color'],
  1059. linestyle='-',
  1060. linewidth=local_shapes[element]['linewidth'])
  1061. except Exception as e:
  1062. log.debug("ShapeCollectionLegacy.redraw() geometry poly --> %s" % str(e))
  1063. elif type(local_shapes[element]['shape']) == LineString or \
  1064. type(local_shapes[element]['shape']) == LinearRing:
  1065. try:
  1066. x, y = local_shapes[element]['shape'].coords.xy
  1067. self.axes.plot(x, y, local_shapes[element]['color'],
  1068. linestyle='-',
  1069. linewidth=local_shapes[element]['linewidth'])
  1070. except Exception as e:
  1071. log.debug("ShapeCollectionLegacy.redraw() geometry no poly --> %s" % str(e))
  1072. elif obj_type == 'gerber':
  1073. if self.obj.options["multicolored"]:
  1074. linespec = '-'
  1075. else:
  1076. linespec = 'k-'
  1077. if self.obj.options["solid"]:
  1078. if update_colors:
  1079. gerber_fill_color = update_colors[0]
  1080. gerber_outline_color = update_colors[1]
  1081. else:
  1082. gerber_fill_color = local_shapes[element]['face_color']
  1083. gerber_outline_color = local_shapes[element]['color']
  1084. try:
  1085. patch = PolygonPatch(local_shapes[element]['shape'],
  1086. facecolor=gerber_fill_color,
  1087. edgecolor=gerber_outline_color,
  1088. alpha=local_shapes[element]['alpha'],
  1089. zorder=2,
  1090. linewidth=local_shapes[element]['linewidth'])
  1091. self.axes.add_patch(patch)
  1092. except AssertionError:
  1093. log.warning("A geometry component was not a polygon:")
  1094. log.warning(str(element))
  1095. except Exception as e:
  1096. log.debug(
  1097. "PlotCanvasLegacy.ShepeCollectionLegacy.redraw() gerber 'solid' --> %s" % str(e))
  1098. else:
  1099. try:
  1100. x, y = local_shapes[element]['shape'].exterior.xy
  1101. self.axes.plot(x, y, linespec, linewidth=local_shapes[element]['linewidth'])
  1102. for ints in local_shapes[element]['shape'].interiors:
  1103. x, y = ints.coords.xy
  1104. self.axes.plot(x, y, linespec, linewidth=local_shapes[element]['linewidth'])
  1105. except Exception as e:
  1106. log.debug("ShapeCollectionLegacy.redraw() gerber no 'solid' --> %s" % str(e))
  1107. elif obj_type == 'cncjob':
  1108. if local_shapes[element]['face_color'] is None:
  1109. try:
  1110. linespec = '--'
  1111. linecolor = local_shapes[element]['color']
  1112. # if geo['kind'][0] == 'C':
  1113. # linespec = 'k-'
  1114. x, y = local_shapes[element]['shape'].coords.xy
  1115. self.axes.plot(x, y, linespec, color=linecolor,
  1116. linewidth=local_shapes[element]['linewidth'])
  1117. except Exception as e:
  1118. log.debug("ShapeCollectionLegacy.redraw() cncjob with face_color --> %s" % str(e))
  1119. else:
  1120. try:
  1121. path_num += 1
  1122. if self.obj.ui.annotation_cb.get_value():
  1123. if isinstance(local_shapes[element]['shape'], Polygon):
  1124. self.axes.annotate(
  1125. str(path_num),
  1126. xy=local_shapes[element]['shape'].exterior.coords[0],
  1127. xycoords='data', fontsize=20)
  1128. else:
  1129. self.axes.annotate(
  1130. str(path_num),
  1131. xy=local_shapes[element]['shape'].coords[0],
  1132. xycoords='data', fontsize=20)
  1133. patch = PolygonPatch(local_shapes[element]['shape'],
  1134. facecolor=local_shapes[element]['face_color'],
  1135. edgecolor=local_shapes[element]['color'],
  1136. alpha=local_shapes[element]['alpha'], zorder=2,
  1137. linewidth=local_shapes[element]['linewidth'])
  1138. self.axes.add_patch(patch)
  1139. except Exception as e:
  1140. log.debug("ShapeCollectionLegacy.redraw() cncjob no face_color --> %s" % str(e))
  1141. elif obj_type == 'utility':
  1142. # not a FlatCAM object, must be utility
  1143. if local_shapes[element]['face_color']:
  1144. try:
  1145. patch = PolygonPatch(local_shapes[element]['shape'],
  1146. facecolor=local_shapes[element]['face_color'],
  1147. edgecolor=local_shapes[element]['color'],
  1148. alpha=local_shapes[element]['alpha'],
  1149. zorder=2,
  1150. linewidth=local_shapes[element]['linewidth'])
  1151. self.axes.add_patch(patch)
  1152. except Exception as e:
  1153. log.debug("ShapeCollectionLegacy.redraw() utility poly with face_color --> %s" % str(e))
  1154. else:
  1155. if isinstance(local_shapes[element]['shape'], Polygon):
  1156. try:
  1157. ext_shape = local_shapes[element]['shape'].exterior
  1158. if ext_shape is not None:
  1159. x, y = ext_shape.xy
  1160. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-',
  1161. linewidth=local_shapes[element]['linewidth'])
  1162. for ints in local_shapes[element]['shape'].interiors:
  1163. if ints is not None:
  1164. x, y = ints.coords.xy
  1165. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-',
  1166. linewidth=local_shapes[element]['linewidth'])
  1167. except Exception as e:
  1168. log.debug("ShapeCollectionLegacy.redraw() utility poly no face_color --> %s" % str(e))
  1169. else:
  1170. try:
  1171. if local_shapes[element]['shape'] is not None:
  1172. x, y = local_shapes[element]['shape'].coords.xy
  1173. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-',
  1174. linewidth=local_shapes[element]['linewidth'])
  1175. except Exception as e:
  1176. log.debug("ShapeCollectionLegacy.redraw() utility lines no face_color --> %s" % str(e))
  1177. self.app.plotcanvas.auto_adjust_axes()
  1178. def set(self, text, pos, visible=True, font_size=16, color=None):
  1179. """
  1180. This will set annotations on the canvas.
  1181. :param text: a list of text elements to be used as annotations
  1182. :param pos: a list of positions for showing the text elements above
  1183. :param visible: if True will display annotations, if False will clear them on canvas
  1184. :param font_size: the font size or the annotations
  1185. :param color: color of the annotations
  1186. :return: None
  1187. """
  1188. if color is None:
  1189. color = "#000000FF"
  1190. if visible is not True:
  1191. self.clear()
  1192. return
  1193. if len(text) != len(pos):
  1194. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not annotate due of a difference between the number "
  1195. "of text elements and the number of text positions."))
  1196. return
  1197. for idx in range(len(text)):
  1198. try:
  1199. self.axes.annotate(text[idx], xy=pos[idx], xycoords='data', fontsize=font_size, color=color)
  1200. except Exception as e:
  1201. log.debug("ShapeCollectionLegacy.set() --> %s" % str(e))
  1202. self.app.plotcanvas.auto_adjust_axes()
  1203. @property
  1204. def visible(self):
  1205. return self._visible
  1206. @visible.setter
  1207. def visible(self, value):
  1208. if value is False:
  1209. self.axes.cla()
  1210. self.app.plotcanvas.auto_adjust_axes()
  1211. else:
  1212. if self._visible is False:
  1213. self.redraw()
  1214. self._visible = value
  1215. @property
  1216. def enabled(self):
  1217. return self._visible
  1218. @enabled.setter
  1219. def enabled(self, value):
  1220. if value is False:
  1221. self.axes.cla()
  1222. self.app.plotcanvas.auto_adjust_axes()
  1223. else:
  1224. if self._visible is False:
  1225. self.redraw()
  1226. self._visible = value
  1227. # class MplCursor(Cursor):
  1228. # """
  1229. # Unfortunately this gets attached to the current axes and if a new axes is added
  1230. # it will not be showed until that axes is deleted.
  1231. # Not the kind of behavior needed here so I don't use it anymore.
  1232. # """
  1233. # def __init__(self, axes, color='red', linewidth=1):
  1234. #
  1235. # super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  1236. # self._enabled = True
  1237. #
  1238. # self.axes = axes
  1239. # self.color = color
  1240. # self.linewidth = linewidth
  1241. #
  1242. # self.x = None
  1243. # self.y = None
  1244. #
  1245. # @property
  1246. # def enabled(self):
  1247. # return True if self._enabled else False
  1248. #
  1249. # @enabled.setter
  1250. # def enabled(self, value):
  1251. # self._enabled = value
  1252. # self.visible = self._enabled
  1253. # self.canvas.draw()
  1254. #
  1255. # def onmove(self, event):
  1256. # pass
  1257. #
  1258. # def set_data(self, event, pos):
  1259. # """Internal event handler to draw the cursor when the mouse moves."""
  1260. # self.x = pos[0]
  1261. # self.y = pos[1]
  1262. #
  1263. # if self.ignore(event):
  1264. # return
  1265. # if not self.canvas.widgetlock.available(self):
  1266. # return
  1267. # if event.inaxes != self.ax:
  1268. # self.linev.set_visible(False)
  1269. # self.lineh.set_visible(False)
  1270. #
  1271. # if self.needclear:
  1272. # self.canvas.draw()
  1273. # self.needclear = False
  1274. # return
  1275. # self.needclear = True
  1276. # if not self.visible:
  1277. # return
  1278. # self.linev.set_xdata((self.x, self.x))
  1279. #
  1280. # self.lineh.set_ydata((self.y, self.y))
  1281. # self.linev.set_visible(self.visible and self.vertOn)
  1282. # self.lineh.set_visible(self.visible and self.horizOn)
  1283. #
  1284. # self._update()