PlotCanvasLegacy.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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 QtGui, QtCore, QtWidgets
  10. # Prevent conflict with Qt5 and above.
  11. from matplotlib import use as mpl_use
  12. mpl_use("Qt5Agg")
  13. from matplotlib.figure import Figure
  14. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  15. from matplotlib.backends.backend_agg import FigureCanvasAgg
  16. from matplotlib.widgets import Cursor
  17. # needed for legacy mode
  18. # Used for solid polygons in Matplotlib
  19. from descartes.patch import PolygonPatch
  20. from shapely.geometry import Polygon, LineString, LinearRing, Point, MultiPolygon, MultiLineString
  21. import FlatCAMApp
  22. from copy import deepcopy
  23. import logging
  24. import gettext
  25. import FlatCAMTranslation as fcTranslate
  26. import builtins
  27. fcTranslate.apply_language('strings')
  28. if '_' not in builtins.__dict__:
  29. _ = gettext.gettext
  30. log = logging.getLogger('base')
  31. class CanvasCache(QtCore.QObject):
  32. """
  33. Case story #1:
  34. 1) No objects in the project.
  35. 2) Object is created (new_object() emits object_created(obj)).
  36. on_object_created() adds (i) object to collection and emits
  37. (ii) new_object_available() then calls (iii) object.plot()
  38. 3) object.plot() creates axes if necessary on
  39. app.collection.figure. Then plots on it.
  40. 4) Plots on a cache-size canvas (in background).
  41. 5) Plot completes. Bitmap is generated.
  42. 6) Visible canvas is painted.
  43. """
  44. # Signals:
  45. # A bitmap is ready to be displayed.
  46. new_screen = QtCore.pyqtSignal()
  47. def __init__(self, plotcanvas, app, dpi=50):
  48. super(CanvasCache, self).__init__()
  49. self.app = app
  50. self.plotcanvas = plotcanvas
  51. self.dpi = dpi
  52. self.figure = Figure(dpi=dpi)
  53. self.axes = self.figure.add_axes([0.0, 0.0, 1.0, 1.0], alpha=1.0)
  54. self.axes.set_frame_on(False)
  55. self.axes.set_xticks([])
  56. self.axes.set_yticks([])
  57. self.canvas = FigureCanvasAgg(self.figure)
  58. self.cache = None
  59. def run(self):
  60. log.debug("CanvasCache Thread Started!")
  61. self.plotcanvas.update_screen_request.connect(self.on_update_req)
  62. def on_update_req(self, extents):
  63. """
  64. Event handler for an updated display request.
  65. :param extents: [xmin, xmax, ymin, ymax, zoom(optional)]
  66. """
  67. # log.debug("Canvas update requested: %s" % str(extents))
  68. # Note: This information below might be out of date. Establish
  69. # a protocol regarding when to change the canvas in the main
  70. # thread and when to check these values here in the background,
  71. # or pass this data in the signal (safer).
  72. # log.debug("Size: %s [px]" % str(self.plotcanvas.get_axes_pixelsize()))
  73. # log.debug("Density: %s [units/px]" % str(self.plotcanvas.get_density()))
  74. # Move the requested screen portion to the main thread
  75. # and inform about the update:
  76. self.new_screen.emit()
  77. # Continue to update the cache.
  78. # def on_new_object_available(self):
  79. #
  80. # log.debug("A new object is available. Should plot it!")
  81. class PlotCanvasLegacy(QtCore.QObject):
  82. """
  83. Class handling the plotting area in the application.
  84. """
  85. # Signals:
  86. # Request for new bitmap to display. The parameter
  87. # is a list with [xmin, xmax, ymin, ymax, zoom(optional)]
  88. update_screen_request = QtCore.pyqtSignal(list)
  89. double_click = QtCore.pyqtSignal(object)
  90. def __init__(self, container, app):
  91. """
  92. The constructor configures the Matplotlib figure that
  93. will contain all plots, creates the base axes and connects
  94. events to the plotting area.
  95. :param container: The parent container in which to draw plots.
  96. :rtype: PlotCanvas
  97. """
  98. super(PlotCanvasLegacy, self).__init__()
  99. self.app = app
  100. # Options
  101. self.x_margin = 15 # pixels
  102. self.y_margin = 25 # Pixels
  103. # Parent container
  104. self.container = container
  105. # Plots go onto a single matplotlib.figure
  106. self.figure = Figure(dpi=50) # TODO: dpi needed?
  107. self.figure.patch.set_visible(False)
  108. # These axes show the ticks and grid. No plotting done here.
  109. # New axes must have a label, otherwise mpl returns an existing one.
  110. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  111. self.axes.set_aspect(1)
  112. self.axes.grid(True)
  113. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  114. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  115. # The canvas is the top level container (FigureCanvasQTAgg)
  116. self.canvas = FigureCanvas(self.figure)
  117. self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
  118. self.canvas.setFocus()
  119. self.native = self.canvas
  120. self.adjust_axes(-10, -10, 100, 100)
  121. # self.canvas.set_can_focus(True) # For key press
  122. # Attach to parent
  123. # self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  124. self.container.addWidget(self.canvas) # Qt
  125. # Copy a bitmap of the canvas for quick animation.
  126. # Update every time the canvas is re-drawn.
  127. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  128. # ## Bitmap Cache
  129. self.cache = CanvasCache(self, self.app)
  130. self.cache_thread = QtCore.QThread()
  131. self.cache.moveToThread(self.cache_thread)
  132. # super(PlotCanvas, self).connect(self.cache_thread, QtCore.SIGNAL("started()"), self.cache.run)
  133. self.cache_thread.started.connect(self.cache.run)
  134. self.cache_thread.start()
  135. self.cache.new_screen.connect(self.on_new_screen)
  136. # Events
  137. self.mp = self.graph_event_connect('button_press_event', self.on_mouse_press)
  138. self.mr = self.graph_event_connect('button_release_event', self.on_mouse_release)
  139. self.mm = self.graph_event_connect('motion_notify_event', self.on_mouse_move)
  140. # self.canvas.connect('configure-event', self.auto_adjust_axes)
  141. self.aaa = self.graph_event_connect('resize_event', self.auto_adjust_axes)
  142. # self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  143. # self.canvas.connect("scroll-event", self.on_scroll)
  144. self.osc = self.graph_event_connect('scroll_event', self.on_scroll)
  145. # self.graph_event_connect('key_press_event', self.on_key_down)
  146. # self.graph_event_connect('key_release_event', self.on_key_up)
  147. self.odr = self.graph_event_connect('draw_event', self.on_draw)
  148. self.mouse = [0, 0]
  149. self.key = None
  150. self.pan_axes = []
  151. self.panning = False
  152. # signal is the mouse is dragging
  153. self.is_dragging = False
  154. # signal if there is a doubleclick
  155. self.is_dblclk = False
  156. def graph_event_connect(self, event_name, callback):
  157. """
  158. Attach an event handler to the canvas through the Matplotlib interface.
  159. :param event_name: Name of the event
  160. :type event_name: str
  161. :param callback: Function to call
  162. :type callback: func
  163. :return: Connection id
  164. :rtype: int
  165. """
  166. if event_name == 'mouse_move':
  167. event_name = 'motion_notify_event'
  168. if event_name == 'mouse_press':
  169. event_name = 'button_press_event'
  170. if event_name == 'mouse_release':
  171. event_name = 'button_release_event'
  172. if event_name == 'mouse_double_click':
  173. return self.double_click.connect(callback)
  174. if event_name == 'key_press':
  175. event_name = 'key_press_event'
  176. return self.canvas.mpl_connect(event_name, callback)
  177. def graph_event_disconnect(self, cid):
  178. """
  179. Disconnect callback with the give id.
  180. :param cid: Callback id.
  181. :return: None
  182. """
  183. # self.double_click.disconnect(cid)
  184. self.canvas.mpl_disconnect(cid)
  185. def on_new_screen(self):
  186. pass
  187. # log.debug("Cache updated the screen!")
  188. def new_cursor(self, axes=None):
  189. # if axes is None:
  190. # c = MplCursor(axes=self.axes, color='black', linewidth=1)
  191. # else:
  192. # c = MplCursor(axes=axes, color='black', linewidth=1)
  193. c = FakeCursor()
  194. return c
  195. def on_key_down(self, event):
  196. """
  197. :param event:
  198. :return:
  199. """
  200. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  201. self.key = event.key
  202. def on_key_up(self, event):
  203. """
  204. :param event:
  205. :return:
  206. """
  207. self.key = None
  208. def connect(self, event_name, callback):
  209. """
  210. Attach an event handler to the canvas through the native Qt interface.
  211. :param event_name: Name of the event
  212. :type event_name: str
  213. :param callback: Function to call
  214. :type callback: function
  215. :return: Nothing
  216. """
  217. self.canvas.connect(event_name, callback)
  218. def clear(self):
  219. """
  220. Clears axes and figure.
  221. :return: None
  222. """
  223. # Clear
  224. self.axes.cla()
  225. try:
  226. self.figure.clf()
  227. except KeyError:
  228. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  229. # Re-build
  230. self.figure.add_axes(self.axes)
  231. self.axes.set_aspect(1)
  232. self.axes.grid(True)
  233. # Re-draw
  234. self.canvas.draw_idle()
  235. def adjust_axes(self, xmin, ymin, xmax, ymax):
  236. """
  237. Adjusts all axes while maintaining the use of the whole canvas
  238. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  239. request that will be modified to fit these restrictions.
  240. :param xmin: Requested minimum value for the X axis.
  241. :type xmin: float
  242. :param ymin: Requested minimum value for the Y axis.
  243. :type ymin: float
  244. :param xmax: Requested maximum value for the X axis.
  245. :type xmax: float
  246. :param ymax: Requested maximum value for the Y axis.
  247. :type ymax: float
  248. :return: None
  249. """
  250. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  251. width = xmax - xmin
  252. height = ymax - ymin
  253. try:
  254. r = width / height
  255. except ZeroDivisionError:
  256. FlatCAMApp.App.log.error("Height is %f" % height)
  257. return
  258. canvas_w, canvas_h = self.canvas.get_width_height()
  259. canvas_r = float(canvas_w) / canvas_h
  260. x_ratio = float(self.x_margin) / canvas_w
  261. y_ratio = float(self.y_margin) / canvas_h
  262. if r > canvas_r:
  263. ycenter = (ymin + ymax) / 2.0
  264. newheight = height * r / canvas_r
  265. ymin = ycenter - newheight / 2.0
  266. ymax = ycenter + newheight / 2.0
  267. else:
  268. xcenter = (xmax + xmin) / 2.0
  269. newwidth = width * canvas_r / r
  270. xmin = xcenter - newwidth / 2.0
  271. xmax = xcenter + newwidth / 2.0
  272. # Adjust axes
  273. for ax in self.figure.get_axes():
  274. if ax._label != 'base':
  275. ax.set_frame_on(False) # No frame
  276. ax.set_xticks([]) # No tick
  277. ax.set_yticks([]) # No ticks
  278. ax.patch.set_visible(False) # No background
  279. ax.set_aspect(1)
  280. ax.set_xlim((xmin, xmax))
  281. ax.set_ylim((ymin, ymax))
  282. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  283. # Sync re-draw to proper paint on form resize
  284. self.canvas.draw()
  285. # #### Temporary place-holder for cached update #####
  286. self.update_screen_request.emit([0, 0, 0, 0, 0])
  287. def auto_adjust_axes(self, *args):
  288. """
  289. Calls ``adjust_axes()`` using the extents of the base axes.
  290. :rtype : None
  291. :return: None
  292. """
  293. xmin, xmax = self.axes.get_xlim()
  294. ymin, ymax = self.axes.get_ylim()
  295. self.adjust_axes(xmin, ymin, xmax, ymax)
  296. def fit_view(self):
  297. self.auto_adjust_axes()
  298. def zoom(self, factor, center=None):
  299. """
  300. Zooms the plot by factor around a given
  301. center point. Takes care of re-drawing.
  302. :param factor: Number by which to scale the plot.
  303. :type factor: float
  304. :param center: Coordinates [x, y] of the point around which to scale the plot.
  305. :type center: list
  306. :return: None
  307. """
  308. factor = 1 / factor
  309. xmin, xmax = self.axes.get_xlim()
  310. ymin, ymax = self.axes.get_ylim()
  311. width = xmax - xmin
  312. height = ymax - ymin
  313. if center is None or center == [None, None]:
  314. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  315. # For keeping the point at the pointer location
  316. relx = (xmax - center[0]) / width
  317. rely = (ymax - center[1]) / height
  318. new_width = width / factor
  319. new_height = height / factor
  320. xmin = center[0] - new_width * (1 - relx)
  321. xmax = center[0] + new_width * relx
  322. ymin = center[1] - new_height * (1 - rely)
  323. ymax = center[1] + new_height * rely
  324. # Adjust axes
  325. for ax in self.figure.get_axes():
  326. ax.set_xlim((xmin, xmax))
  327. ax.set_ylim((ymin, ymax))
  328. # Async re-draw
  329. self.canvas.draw_idle()
  330. # #### Temporary place-holder for cached update #####
  331. self.update_screen_request.emit([0, 0, 0, 0, 0])
  332. def pan(self, x, y):
  333. xmin, xmax = self.axes.get_xlim()
  334. ymin, ymax = self.axes.get_ylim()
  335. width = xmax - xmin
  336. height = ymax - ymin
  337. # Adjust axes
  338. for ax in self.figure.get_axes():
  339. ax.set_xlim((xmin + x * width, xmax + x * width))
  340. ax.set_ylim((ymin + y * height, ymax + y * height))
  341. # Re-draw
  342. self.canvas.draw_idle()
  343. # #### Temporary place-holder for cached update #####
  344. self.update_screen_request.emit([0, 0, 0, 0, 0])
  345. def new_axes(self, name):
  346. """
  347. Creates and returns an Axes object attached to this object's Figure.
  348. :param name: Unique label for the axes.
  349. :return: Axes attached to the figure.
  350. :rtype: Axes
  351. """
  352. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  353. def on_scroll(self, event):
  354. """
  355. Scroll event handler.
  356. :param event: Event object containing the event information.
  357. :return: None
  358. """
  359. # So it can receive key presses
  360. # self.canvas.grab_focus()
  361. self.canvas.setFocus()
  362. # Event info
  363. # z, direction = event.get_scroll_direction()
  364. if self.key is None:
  365. if event.button == 'up':
  366. self.zoom(1 / 1.5, self.mouse)
  367. else:
  368. self.zoom(1.5, self.mouse)
  369. return
  370. if self.key == 'shift':
  371. if event.button == 'up':
  372. self.pan(0.3, 0)
  373. else:
  374. self.pan(-0.3, 0)
  375. return
  376. if self.key == 'control':
  377. if event.button == 'up':
  378. self.pan(0, 0.3)
  379. else:
  380. self.pan(0, -0.3)
  381. return
  382. def on_mouse_press(self, event):
  383. self.is_dragging = True
  384. # Check for middle mouse button press
  385. if self.app.defaults["global_pan_button"] == '2':
  386. pan_button = 3 # right button for Matplotlib
  387. else:
  388. pan_button = 2 # middle button for Matplotlib
  389. if event.button == pan_button:
  390. # Prepare axes for pan (using 'matplotlib' pan function)
  391. self.pan_axes = []
  392. for a in self.figure.get_axes():
  393. if (event.x is not None and event.y is not None and a.in_axes(event) and
  394. a.get_navigate() and a.can_pan()):
  395. a.start_pan(event.x, event.y, 1)
  396. self.pan_axes.append(a)
  397. # Set pan view flag
  398. if len(self.pan_axes) > 0:
  399. self.panning = True
  400. if event.dblclick:
  401. self.double_click.emit(event)
  402. def on_mouse_release(self, event):
  403. self.is_dragging = False
  404. # Check for middle mouse button release to complete pan procedure
  405. # Check for middle mouse button press
  406. if self.app.defaults["global_pan_button"] == '2':
  407. pan_button = 3 # right button for Matplotlib
  408. else:
  409. pan_button = 2 # middle button for Matplotlib
  410. if event.button == pan_button:
  411. for a in self.pan_axes:
  412. a.end_pan()
  413. # Clear pan flag
  414. self.panning = False
  415. def on_mouse_move(self, event):
  416. """
  417. Mouse movement event hadler. Stores the coordinates. Updates view on pan.
  418. :param event: Contains information about the event.
  419. :return: None
  420. """
  421. try:
  422. x = float(event.xdata)
  423. y = float(event.ydata)
  424. except TypeError:
  425. return
  426. self.mouse = [event.xdata, event.ydata]
  427. self.canvas.restore_region(self.background)
  428. # Update pan view on mouse move
  429. if self.panning is True:
  430. # x_pan, y_pan = self.app.geo_editor.snap(event.xdata, event.ydata)
  431. # self.app.app_cursor.set_data(event, (x_pan, y_pan))
  432. for a in self.pan_axes:
  433. a.drag_pan(1, event.key, event.x, event.y)
  434. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  435. self.canvas.draw_idle()
  436. # #### Temporary place-holder for cached update #####
  437. self.update_screen_request.emit([0, 0, 0, 0, 0])
  438. x, y = self.app.geo_editor.snap(x, y)
  439. if self.app.app_cursor.enabled is True:
  440. # Pointer (snapped)
  441. elements = self.axes.plot(x, y, 'k+', ms=40, mew=2, animated=True)
  442. for el in elements:
  443. self.axes.draw_artist(el)
  444. self.canvas.blit(self.axes.bbox)
  445. def translate_coords(self, position):
  446. """
  447. This does not do much. It's just for code compatibility
  448. :param position: Mouse event position
  449. :return: Tuple with mouse position
  450. """
  451. return (position[0], position[1])
  452. def on_draw(self, renderer):
  453. # Store background on canvas redraw
  454. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  455. def get_axes_pixelsize(self):
  456. """
  457. Axes size in pixels.
  458. :return: Pixel width and height
  459. :rtype: tuple
  460. """
  461. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  462. width, height = bbox.width, bbox.height
  463. width *= self.figure.dpi
  464. height *= self.figure.dpi
  465. return width, height
  466. def get_density(self):
  467. """
  468. Returns unit length per pixel on horizontal
  469. and vertical axes.
  470. :return: X and Y density
  471. :rtype: tuple
  472. """
  473. xpx, ypx = self.get_axes_pixelsize()
  474. xmin, xmax = self.axes.get_xlim()
  475. ymin, ymax = self.axes.get_ylim()
  476. width = xmax - xmin
  477. height = ymax - ymin
  478. return width / xpx, height / ypx
  479. class FakeCursor:
  480. """
  481. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  482. This way I don't have to chane (disable) things related to the cursor all over when
  483. using the low performance Matplotlib 2D graphic engine.
  484. """
  485. def __init__(self):
  486. self._enabled = True
  487. @property
  488. def enabled(self):
  489. return True if self._enabled else False
  490. @enabled.setter
  491. def enabled(self, value):
  492. self._enabled = value
  493. def set_data(self, pos, **kwargs):
  494. """Internal event handler to draw the cursor when the mouse moves."""
  495. pass
  496. class MplCursor(Cursor):
  497. """
  498. Unfortunately this gets attached to the current axes and if a new axes is added
  499. it will not be showed until that axes is deleted.
  500. Not the kind of behavior needed here so I don't use it anymore.
  501. """
  502. def __init__(self, axes, color='red', linewidth=1):
  503. super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  504. self._enabled = True
  505. self.axes = axes
  506. self.color = color
  507. self.linewidth = linewidth
  508. self.x = None
  509. self.y = None
  510. @property
  511. def enabled(self):
  512. return True if self._enabled else False
  513. @enabled.setter
  514. def enabled(self, value):
  515. self._enabled = value
  516. self.visible = self._enabled
  517. self.canvas.draw()
  518. def onmove(self, event):
  519. pass
  520. def set_data(self, event, pos):
  521. """Internal event handler to draw the cursor when the mouse moves."""
  522. self.x = pos[0]
  523. self.y = pos[1]
  524. if self.ignore(event):
  525. return
  526. if not self.canvas.widgetlock.available(self):
  527. return
  528. if event.inaxes != self.ax:
  529. self.linev.set_visible(False)
  530. self.lineh.set_visible(False)
  531. if self.needclear:
  532. self.canvas.draw()
  533. self.needclear = False
  534. return
  535. self.needclear = True
  536. if not self.visible:
  537. return
  538. self.linev.set_xdata((self.x, self.x))
  539. self.lineh.set_ydata((self.y, self.y))
  540. self.linev.set_visible(self.visible and self.vertOn)
  541. self.lineh.set_visible(self.visible and self.horizOn)
  542. self._update()
  543. class ShapeCollectionLegacy:
  544. """
  545. This will create the axes for each collection of shapes and will also
  546. hold the collection of shapes into a dict self._shapes.
  547. This handles the shapes redraw on canvas.
  548. """
  549. def __init__(self, obj, app, name=None, annotation_job=None):
  550. """
  551. :param obj: this is the object to which the shapes collection is attached and for
  552. which it will have to draw shapes
  553. :param app: this is the FLatCAM.App usually, needed because we have to access attributes there
  554. :param name: this is the name given to the Matplotlib axes; it needs to be unique due of Matplotlib requurements
  555. :param annotation_job: make this True if the job needed is just for annotation
  556. """
  557. self.obj = obj
  558. self.app = app
  559. self.annotation_job = annotation_job
  560. self._shapes = dict()
  561. self.shape_dict = dict()
  562. self.shape_id = 0
  563. self._color = None
  564. self._face_color = None
  565. self._visible = True
  566. self._update = False
  567. self._alpha = None
  568. self._tool_tolerance = None
  569. self._tooldia = None
  570. self._obj = None
  571. self._gcode_parsed = None
  572. if name is None:
  573. axes_name = self.obj.options['name']
  574. else:
  575. axes_name = name
  576. # Axes must exist and be attached to canvas.
  577. if axes_name not in self.app.plotcanvas.figure.axes:
  578. self.axes = self.app.plotcanvas.new_axes(axes_name)
  579. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  580. update=False, layer=1, tolerance=0.01, obj=None, gcode_parsed=None, tool_tolerance=None, tooldia=None):
  581. """
  582. This function will add shapes to the shape collection
  583. :param shape: the Shapely shape to be added to the shape collection
  584. :param color: edge color of the shape, hex value
  585. :param face_color: the body color of the shape, hex value
  586. :param alpha: level of transparency of the shape [0.0 ... 1.0]; Float
  587. :param visible: if True will allow the shapes to be added
  588. :param update: not used; just for compatibility with VIsPy canvas
  589. :param layer: just for compatibility with VIsPy canvas
  590. :param tolerance: just for compatibility with VIsPy canvas
  591. :param obj: not used
  592. :param gcode_parsed: not used; just for compatibility with VIsPy canvas
  593. :param tool_tolerance: just for compatibility with VIsPy canvas
  594. :param tooldia:
  595. :return:
  596. """
  597. self._color = color[:-2] if color is not None else None
  598. self._face_color = face_color[:-2] if face_color is not None else None
  599. self._alpha = int(face_color[-2:], 16) / 255 if face_color is not None else 0.75
  600. if alpha is not None:
  601. self._alpha = alpha
  602. self._visible = visible
  603. self._update = update
  604. # CNCJob object related arguments
  605. self._obj = obj
  606. self._gcode_parsed = gcode_parsed
  607. self._tool_tolerance = tool_tolerance
  608. self._tooldia = tooldia
  609. # if self._update:
  610. # self.clear()
  611. try:
  612. for sh in shape:
  613. self.shape_id += 1
  614. self.shape_dict.update({
  615. 'color': self._color,
  616. 'face_color': self._face_color,
  617. 'alpha': self._alpha,
  618. 'shape': sh
  619. })
  620. self._shapes.update({
  621. self.shape_id: deepcopy(self.shape_dict)
  622. })
  623. except TypeError:
  624. self.shape_id += 1
  625. self.shape_dict.update({
  626. 'color': self._color,
  627. 'face_color': self._face_color,
  628. 'alpha': self._alpha,
  629. 'shape': shape
  630. })
  631. self._shapes.update({
  632. self.shape_id: deepcopy(self.shape_dict)
  633. })
  634. return self.shape_id
  635. def clear(self, update=None):
  636. """
  637. Clear the canvas of the shapes.
  638. :param update:
  639. :return: None
  640. """
  641. self._shapes.clear()
  642. self.shape_id = 0
  643. self.axes.cla()
  644. self.app.plotcanvas.auto_adjust_axes()
  645. if update is True:
  646. self.redraw()
  647. def redraw(self):
  648. """
  649. This draw the shapes in the shapes collection, on canvas
  650. :return: None
  651. """
  652. path_num = 0
  653. local_shapes = deepcopy(self._shapes)
  654. try:
  655. obj_type = self.obj.kind
  656. except AttributeError:
  657. obj_type = 'utility'
  658. if self._visible:
  659. for element in local_shapes:
  660. if obj_type == 'excellon':
  661. # Plot excellon (All polygons?)
  662. if self.obj.options["solid"] and isinstance(local_shapes[element]['shape'], Polygon):
  663. patch = PolygonPatch(local_shapes[element]['shape'],
  664. facecolor="#C40000",
  665. edgecolor="#750000",
  666. alpha=local_shapes[element]['alpha'],
  667. zorder=3)
  668. self.axes.add_patch(patch)
  669. else:
  670. x, y = local_shapes[element]['shape'].exterior.coords.xy
  671. self.axes.plot(x, y, 'r-')
  672. for ints in local_shapes[element]['shape'].interiors:
  673. x, y = ints.coords.xy
  674. self.axes.plot(x, y, 'o-')
  675. elif obj_type == 'geometry':
  676. if type(local_shapes[element]['shape']) == Polygon:
  677. x, y = local_shapes[element]['shape'].exterior.coords.xy
  678. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  679. for ints in local_shapes[element]['shape'].interiors:
  680. x, y = ints.coords.xy
  681. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  682. elif type(local_shapes[element]['shape']) == LineString or \
  683. type(local_shapes[element]['shape']) == LinearRing:
  684. x, y = local_shapes[element]['shape'].coords.xy
  685. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  686. elif obj_type == 'gerber':
  687. if self.obj.options["multicolored"]:
  688. linespec = '-'
  689. else:
  690. linespec = 'k-'
  691. if self.obj.options["solid"]:
  692. try:
  693. patch = PolygonPatch(local_shapes[element]['shape'],
  694. facecolor=local_shapes[element]['face_color'],
  695. edgecolor=local_shapes[element]['color'],
  696. alpha=local_shapes[element]['alpha'],
  697. zorder=2)
  698. self.axes.add_patch(patch)
  699. except AssertionError:
  700. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  701. FlatCAMApp.App.log.warning(str(element))
  702. else:
  703. x, y = local_shapes[element]['shape'].exterior.xy
  704. self.axes.plot(x, y, linespec)
  705. for ints in local_shapes[element]['shape'].interiors:
  706. x, y = ints.coords.xy
  707. self.axes.plot(x, y, linespec)
  708. elif obj_type == 'cncjob':
  709. if local_shapes[element]['face_color'] is None:
  710. linespec = '--'
  711. linecolor = local_shapes[element]['color']
  712. # if geo['kind'][0] == 'C':
  713. # linespec = 'k-'
  714. x, y = local_shapes[element]['shape'].coords.xy
  715. self.axes.plot(x, y, linespec, color=linecolor)
  716. else:
  717. path_num += 1
  718. if isinstance(local_shapes[element]['shape'], Polygon):
  719. self.axes.annotate(str(path_num), xy=local_shapes[element]['shape'].exterior.coords[0],
  720. xycoords='data', fontsize=20)
  721. else:
  722. self.axes.annotate(str(path_num), xy=local_shapes[element]['shape'].coords[0],
  723. xycoords='data', fontsize=20)
  724. patch = PolygonPatch(local_shapes[element]['shape'],
  725. facecolor=local_shapes[element]['face_color'],
  726. edgecolor=local_shapes[element]['color'],
  727. alpha=local_shapes[element]['alpha'], zorder=2)
  728. self.axes.add_patch(patch)
  729. elif obj_type == 'utility':
  730. # not a FlatCAM object, must be utility
  731. if local_shapes[element]['face_color']:
  732. try:
  733. patch = PolygonPatch(local_shapes[element]['shape'],
  734. facecolor=local_shapes[element]['face_color'],
  735. edgecolor=local_shapes[element]['color'],
  736. alpha=local_shapes[element]['alpha'],
  737. zorder=2)
  738. self.axes.add_patch(patch)
  739. except Exception as e:
  740. log.debug("ShapeCollectionLegacy.redraw() --> %s" % str(e))
  741. else:
  742. if isinstance(local_shapes[element]['shape'], Polygon):
  743. x, y = local_shapes[element]['shape'].exterior.xy
  744. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  745. for ints in local_shapes[element]['shape'].interiors:
  746. x, y = ints.coords.xy
  747. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  748. else:
  749. x, y = local_shapes[element]['shape'].coords.xy
  750. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  751. self.app.plotcanvas.auto_adjust_axes()
  752. def set(self, text, pos, visible=True, font_size=16, color=None):
  753. """
  754. This will set annotations on the canvas.
  755. :param text: a list of text elements to be used as annotations
  756. :param pos: a list of positions for showing the text elements above
  757. :param visible: if True will display annotations, if False will clear them on canvas
  758. :param font_size: the font size or the annotations
  759. :param color: color of the annotations
  760. :return: None
  761. """
  762. if color is None:
  763. color = "#000000FF"
  764. if visible is not True:
  765. self.clear()
  766. return
  767. if len(text) != len(pos):
  768. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not annotate due of a difference between the number "
  769. "of text elements and the number of text positions."))
  770. return
  771. for idx in range(len(text)):
  772. try:
  773. self.axes.annotate(text[idx], xy=pos[idx], xycoords='data', fontsize=font_size, color=color)
  774. except Exception as e:
  775. log.debug("ShapeCollectionLegacy.set() --> %s" % str(e))
  776. self.app.plotcanvas.auto_adjust_axes()
  777. @property
  778. def visible(self):
  779. return self._visible
  780. @visible.setter
  781. def visible(self, value):
  782. if value is False:
  783. self.axes.cla()
  784. self.app.plotcanvas.auto_adjust_axes()
  785. else:
  786. if self._visible is False:
  787. self.redraw()
  788. self._visible = value
  789. @property
  790. def enabled(self):
  791. return self._visible
  792. @enabled.setter
  793. def enabled(self, value):
  794. if value is False:
  795. self.axes.cla()
  796. self.app.plotcanvas.auto_adjust_axes()
  797. else:
  798. if self._visible is False:
  799. self.redraw()
  800. self._visible = value