PlotCanvasLegacy.py 59 KB

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