PlotCanvasLegacy.py 56 KB

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