PlotCanvasLegacy.py 55 KB

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