PlotCanvasLegacy.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. if not self.app.collection.get_list():
  252. xmin = -10
  253. ymin = -10
  254. xmax = 100
  255. ymax = 100
  256. width = xmax - xmin
  257. height = ymax - ymin
  258. try:
  259. r = width / height
  260. except ZeroDivisionError:
  261. FlatCAMApp.App.log.error("Height is %f" % height)
  262. return
  263. canvas_w, canvas_h = self.canvas.get_width_height()
  264. canvas_r = float(canvas_w) / canvas_h
  265. x_ratio = float(self.x_margin) / canvas_w
  266. y_ratio = float(self.y_margin) / canvas_h
  267. if r > canvas_r:
  268. ycenter = (ymin + ymax) / 2.0
  269. newheight = height * r / canvas_r
  270. ymin = ycenter - newheight / 2.0
  271. ymax = ycenter + newheight / 2.0
  272. else:
  273. xcenter = (xmax + xmin) / 2.0
  274. newwidth = width * canvas_r / r
  275. xmin = xcenter - newwidth / 2.0
  276. xmax = xcenter + newwidth / 2.0
  277. # Adjust axes
  278. for ax in self.figure.get_axes():
  279. if ax._label != 'base':
  280. ax.set_frame_on(False) # No frame
  281. ax.set_xticks([]) # No tick
  282. ax.set_yticks([]) # No ticks
  283. ax.patch.set_visible(False) # No background
  284. ax.set_aspect(1)
  285. ax.set_xlim((xmin, xmax))
  286. ax.set_ylim((ymin, ymax))
  287. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  288. # Sync re-draw to proper paint on form resize
  289. self.canvas.draw()
  290. # #### Temporary place-holder for cached update #####
  291. self.update_screen_request.emit([0, 0, 0, 0, 0])
  292. def auto_adjust_axes(self, *args):
  293. """
  294. Calls ``adjust_axes()`` using the extents of the base axes.
  295. :rtype : None
  296. :return: None
  297. """
  298. xmin, xmax = self.axes.get_xlim()
  299. ymin, ymax = self.axes.get_ylim()
  300. self.adjust_axes(xmin, ymin, xmax, ymax)
  301. def fit_view(self):
  302. self.auto_adjust_axes()
  303. def zoom(self, factor, center=None):
  304. """
  305. Zooms the plot by factor around a given
  306. center point. Takes care of re-drawing.
  307. :param factor: Number by which to scale the plot.
  308. :type factor: float
  309. :param center: Coordinates [x, y] of the point around which to scale the plot.
  310. :type center: list
  311. :return: None
  312. """
  313. factor = 1 / factor
  314. xmin, xmax = self.axes.get_xlim()
  315. ymin, ymax = self.axes.get_ylim()
  316. width = xmax - xmin
  317. height = ymax - ymin
  318. if center is None or center == [None, None]:
  319. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  320. # For keeping the point at the pointer location
  321. relx = (xmax - center[0]) / width
  322. rely = (ymax - center[1]) / height
  323. new_width = width / factor
  324. new_height = height / factor
  325. xmin = center[0] - new_width * (1 - relx)
  326. xmax = center[0] + new_width * relx
  327. ymin = center[1] - new_height * (1 - rely)
  328. ymax = center[1] + new_height * rely
  329. # Adjust axes
  330. for ax in self.figure.get_axes():
  331. ax.set_xlim((xmin, xmax))
  332. ax.set_ylim((ymin, ymax))
  333. # Async re-draw
  334. self.canvas.draw_idle()
  335. # #### Temporary place-holder for cached update #####
  336. self.update_screen_request.emit([0, 0, 0, 0, 0])
  337. def pan(self, x, y):
  338. xmin, xmax = self.axes.get_xlim()
  339. ymin, ymax = self.axes.get_ylim()
  340. width = xmax - xmin
  341. height = ymax - ymin
  342. # Adjust axes
  343. for ax in self.figure.get_axes():
  344. ax.set_xlim((xmin + x * width, xmax + x * width))
  345. ax.set_ylim((ymin + y * height, ymax + y * height))
  346. # Re-draw
  347. self.canvas.draw_idle()
  348. # #### Temporary place-holder for cached update #####
  349. self.update_screen_request.emit([0, 0, 0, 0, 0])
  350. def new_axes(self, name):
  351. """
  352. Creates and returns an Axes object attached to this object's Figure.
  353. :param name: Unique label for the axes.
  354. :return: Axes attached to the figure.
  355. :rtype: Axes
  356. """
  357. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  358. def on_scroll(self, event):
  359. """
  360. Scroll event handler.
  361. :param event: Event object containing the event information.
  362. :return: None
  363. """
  364. # So it can receive key presses
  365. # self.canvas.grab_focus()
  366. self.canvas.setFocus()
  367. # Event info
  368. # z, direction = event.get_scroll_direction()
  369. if self.key is None:
  370. if event.button == 'up':
  371. self.zoom(1 / 1.5, self.mouse)
  372. else:
  373. self.zoom(1.5, self.mouse)
  374. return
  375. if self.key == 'shift':
  376. if event.button == 'up':
  377. self.pan(0.3, 0)
  378. else:
  379. self.pan(-0.3, 0)
  380. return
  381. if self.key == 'control':
  382. if event.button == 'up':
  383. self.pan(0, 0.3)
  384. else:
  385. self.pan(0, -0.3)
  386. return
  387. def on_mouse_press(self, event):
  388. self.is_dragging = True
  389. # Check for middle mouse button press
  390. if self.app.defaults["global_pan_button"] == '2':
  391. pan_button = 3 # right button for Matplotlib
  392. else:
  393. pan_button = 2 # middle button for Matplotlib
  394. if event.button == pan_button:
  395. # Prepare axes for pan (using 'matplotlib' pan function)
  396. self.pan_axes = []
  397. for a in self.figure.get_axes():
  398. if (event.x is not None and event.y is not None and a.in_axes(event) and
  399. a.get_navigate() and a.can_pan()):
  400. a.start_pan(event.x, event.y, 1)
  401. self.pan_axes.append(a)
  402. # Set pan view flag
  403. if len(self.pan_axes) > 0:
  404. self.panning = True
  405. if event.dblclick:
  406. self.double_click.emit(event)
  407. def on_mouse_release(self, event):
  408. self.is_dragging = False
  409. # Check for middle mouse button release to complete pan procedure
  410. # Check for middle mouse button press
  411. if self.app.defaults["global_pan_button"] == '2':
  412. pan_button = 3 # right button for Matplotlib
  413. else:
  414. pan_button = 2 # middle button for Matplotlib
  415. if event.button == pan_button:
  416. for a in self.pan_axes:
  417. a.end_pan()
  418. # Clear pan flag
  419. self.panning = False
  420. def on_mouse_move(self, event):
  421. """
  422. Mouse movement event hadler. Stores the coordinates. Updates view on pan.
  423. :param event: Contains information about the event.
  424. :return: None
  425. """
  426. try:
  427. x = float(event.xdata)
  428. y = float(event.ydata)
  429. except TypeError:
  430. return
  431. self.mouse = [event.xdata, event.ydata]
  432. self.canvas.restore_region(self.background)
  433. # Update pan view on mouse move
  434. if self.panning is True:
  435. # x_pan, y_pan = self.app.geo_editor.snap(event.xdata, event.ydata)
  436. # self.app.app_cursor.set_data(event, (x_pan, y_pan))
  437. for a in self.pan_axes:
  438. a.drag_pan(1, event.key, event.x, event.y)
  439. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  440. self.canvas.draw_idle()
  441. # #### Temporary place-holder for cached update #####
  442. self.update_screen_request.emit([0, 0, 0, 0, 0])
  443. x, y = self.app.geo_editor.snap(x, y)
  444. if self.app.app_cursor.enabled is True:
  445. # Pointer (snapped)
  446. elements = self.axes.plot(x, y, 'k+', ms=40, mew=2, animated=True)
  447. for el in elements:
  448. self.axes.draw_artist(el)
  449. self.canvas.blit(self.axes.bbox)
  450. def translate_coords(self, position):
  451. """
  452. This does not do much. It's just for code compatibility
  453. :param position: Mouse event position
  454. :return: Tuple with mouse position
  455. """
  456. return position[0], position[1]
  457. def on_draw(self, renderer):
  458. # Store background on canvas redraw
  459. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  460. def get_axes_pixelsize(self):
  461. """
  462. Axes size in pixels.
  463. :return: Pixel width and height
  464. :rtype: tuple
  465. """
  466. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  467. width, height = bbox.width, bbox.height
  468. width *= self.figure.dpi
  469. height *= self.figure.dpi
  470. return width, height
  471. def get_density(self):
  472. """
  473. Returns unit length per pixel on horizontal
  474. and vertical axes.
  475. :return: X and Y density
  476. :rtype: tuple
  477. """
  478. xpx, ypx = self.get_axes_pixelsize()
  479. xmin, xmax = self.axes.get_xlim()
  480. ymin, ymax = self.axes.get_ylim()
  481. width = xmax - xmin
  482. height = ymax - ymin
  483. return width / xpx, height / ypx
  484. class FakeCursor:
  485. """
  486. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  487. This way I don't have to chane (disable) things related to the cursor all over when
  488. using the low performance Matplotlib 2D graphic engine.
  489. """
  490. def __init__(self):
  491. self._enabled = True
  492. @property
  493. def enabled(self):
  494. return True if self._enabled else False
  495. @enabled.setter
  496. def enabled(self, value):
  497. self._enabled = value
  498. def set_data(self, pos, **kwargs):
  499. """Internal event handler to draw the cursor when the mouse moves."""
  500. pass
  501. class MplCursor(Cursor):
  502. """
  503. Unfortunately this gets attached to the current axes and if a new axes is added
  504. it will not be showed until that axes is deleted.
  505. Not the kind of behavior needed here so I don't use it anymore.
  506. """
  507. def __init__(self, axes, color='red', linewidth=1):
  508. super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  509. self._enabled = True
  510. self.axes = axes
  511. self.color = color
  512. self.linewidth = linewidth
  513. self.x = None
  514. self.y = None
  515. @property
  516. def enabled(self):
  517. return True if self._enabled else False
  518. @enabled.setter
  519. def enabled(self, value):
  520. self._enabled = value
  521. self.visible = self._enabled
  522. self.canvas.draw()
  523. def onmove(self, event):
  524. pass
  525. def set_data(self, event, pos):
  526. """Internal event handler to draw the cursor when the mouse moves."""
  527. self.x = pos[0]
  528. self.y = pos[1]
  529. if self.ignore(event):
  530. return
  531. if not self.canvas.widgetlock.available(self):
  532. return
  533. if event.inaxes != self.ax:
  534. self.linev.set_visible(False)
  535. self.lineh.set_visible(False)
  536. if self.needclear:
  537. self.canvas.draw()
  538. self.needclear = False
  539. return
  540. self.needclear = True
  541. if not self.visible:
  542. return
  543. self.linev.set_xdata((self.x, self.x))
  544. self.lineh.set_ydata((self.y, self.y))
  545. self.linev.set_visible(self.visible and self.vertOn)
  546. self.lineh.set_visible(self.visible and self.horizOn)
  547. self._update()
  548. class ShapeCollectionLegacy:
  549. """
  550. This will create the axes for each collection of shapes and will also
  551. hold the collection of shapes into a dict self._shapes.
  552. This handles the shapes redraw on canvas.
  553. """
  554. def __init__(self, obj, app, name=None, annotation_job=None):
  555. """
  556. :param obj: this is the object to which the shapes collection is attached and for
  557. which it will have to draw shapes
  558. :param app: this is the FLatCAM.App usually, needed because we have to access attributes there
  559. :param name: this is the name given to the Matplotlib axes; it needs to be unique due of Matplotlib requurements
  560. :param annotation_job: make this True if the job needed is just for annotation
  561. """
  562. self.obj = obj
  563. self.app = app
  564. self.annotation_job = annotation_job
  565. self._shapes = dict()
  566. self.shape_dict = dict()
  567. self.shape_id = 0
  568. self._color = None
  569. self._face_color = None
  570. self._visible = True
  571. self._update = False
  572. self._alpha = None
  573. self._tool_tolerance = None
  574. self._tooldia = None
  575. self._obj = None
  576. self._gcode_parsed = None
  577. if name is None:
  578. axes_name = self.obj.options['name']
  579. else:
  580. axes_name = name
  581. # Axes must exist and be attached to canvas.
  582. if axes_name not in self.app.plotcanvas.figure.axes:
  583. self.axes = self.app.plotcanvas.new_axes(axes_name)
  584. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  585. update=False, layer=1, tolerance=0.01, obj=None, gcode_parsed=None, tool_tolerance=None, tooldia=None):
  586. """
  587. This function will add shapes to the shape collection
  588. :param shape: the Shapely shape to be added to the shape collection
  589. :param color: edge color of the shape, hex value
  590. :param face_color: the body color of the shape, hex value
  591. :param alpha: level of transparency of the shape [0.0 ... 1.0]; Float
  592. :param visible: if True will allow the shapes to be added
  593. :param update: not used; just for compatibility with VIsPy canvas
  594. :param layer: just for compatibility with VIsPy canvas
  595. :param tolerance: just for compatibility with VIsPy canvas
  596. :param obj: not used
  597. :param gcode_parsed: not used; just for compatibility with VIsPy canvas
  598. :param tool_tolerance: just for compatibility with VIsPy canvas
  599. :param tooldia:
  600. :return:
  601. """
  602. self._color = color[:-2] if color is not None else None
  603. self._face_color = face_color[:-2] if face_color is not None else None
  604. self._alpha = int(face_color[-2:], 16) / 255 if face_color is not None else 0.75
  605. if alpha is not None:
  606. self._alpha = alpha
  607. self._visible = visible
  608. self._update = update
  609. # CNCJob object related arguments
  610. self._obj = obj
  611. self._gcode_parsed = gcode_parsed
  612. self._tool_tolerance = tool_tolerance
  613. self._tooldia = tooldia
  614. # if self._update:
  615. # self.clear()
  616. try:
  617. for sh in shape:
  618. self.shape_id += 1
  619. self.shape_dict.update({
  620. 'color': self._color,
  621. 'face_color': self._face_color,
  622. 'alpha': self._alpha,
  623. 'shape': sh
  624. })
  625. self._shapes.update({
  626. self.shape_id: deepcopy(self.shape_dict)
  627. })
  628. except TypeError:
  629. self.shape_id += 1
  630. self.shape_dict.update({
  631. 'color': self._color,
  632. 'face_color': self._face_color,
  633. 'alpha': self._alpha,
  634. 'shape': shape
  635. })
  636. self._shapes.update({
  637. self.shape_id: deepcopy(self.shape_dict)
  638. })
  639. return self.shape_id
  640. def clear(self, update=None):
  641. """
  642. Clear the canvas of the shapes.
  643. :param update:
  644. :return: None
  645. """
  646. self._shapes.clear()
  647. self.shape_id = 0
  648. self.axes.cla()
  649. self.app.plotcanvas.auto_adjust_axes()
  650. if update is True:
  651. self.redraw()
  652. def redraw(self):
  653. """
  654. This draw the shapes in the shapes collection, on canvas
  655. :return: None
  656. """
  657. path_num = 0
  658. local_shapes = deepcopy(self._shapes)
  659. try:
  660. obj_type = self.obj.kind
  661. except AttributeError:
  662. obj_type = 'utility'
  663. if self._visible:
  664. for element in local_shapes:
  665. if obj_type == 'excellon':
  666. # Plot excellon (All polygons?)
  667. if self.obj.options["solid"] and isinstance(local_shapes[element]['shape'], Polygon):
  668. patch = PolygonPatch(local_shapes[element]['shape'],
  669. facecolor="#C40000",
  670. edgecolor="#750000",
  671. alpha=local_shapes[element]['alpha'],
  672. zorder=3)
  673. self.axes.add_patch(patch)
  674. else:
  675. x, y = local_shapes[element]['shape'].exterior.coords.xy
  676. self.axes.plot(x, y, 'r-')
  677. for ints in local_shapes[element]['shape'].interiors:
  678. x, y = ints.coords.xy
  679. self.axes.plot(x, y, 'o-')
  680. elif obj_type == 'geometry':
  681. if type(local_shapes[element]['shape']) == Polygon:
  682. x, y = local_shapes[element]['shape'].exterior.coords.xy
  683. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  684. for ints in local_shapes[element]['shape'].interiors:
  685. x, y = ints.coords.xy
  686. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  687. elif type(local_shapes[element]['shape']) == LineString or \
  688. type(local_shapes[element]['shape']) == LinearRing:
  689. x, y = local_shapes[element]['shape'].coords.xy
  690. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  691. elif obj_type == 'gerber':
  692. if self.obj.options["multicolored"]:
  693. linespec = '-'
  694. else:
  695. linespec = 'k-'
  696. if self.obj.options["solid"]:
  697. try:
  698. patch = PolygonPatch(local_shapes[element]['shape'],
  699. facecolor=local_shapes[element]['face_color'],
  700. edgecolor=local_shapes[element]['color'],
  701. alpha=local_shapes[element]['alpha'],
  702. zorder=2)
  703. self.axes.add_patch(patch)
  704. except AssertionError:
  705. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  706. FlatCAMApp.App.log.warning(str(element))
  707. else:
  708. x, y = local_shapes[element]['shape'].exterior.xy
  709. self.axes.plot(x, y, linespec)
  710. for ints in local_shapes[element]['shape'].interiors:
  711. x, y = ints.coords.xy
  712. self.axes.plot(x, y, linespec)
  713. elif obj_type == 'cncjob':
  714. if local_shapes[element]['face_color'] is None:
  715. linespec = '--'
  716. linecolor = local_shapes[element]['color']
  717. # if geo['kind'][0] == 'C':
  718. # linespec = 'k-'
  719. x, y = local_shapes[element]['shape'].coords.xy
  720. self.axes.plot(x, y, linespec, color=linecolor)
  721. else:
  722. path_num += 1
  723. if isinstance(local_shapes[element]['shape'], Polygon):
  724. self.axes.annotate(str(path_num), xy=local_shapes[element]['shape'].exterior.coords[0],
  725. xycoords='data', fontsize=20)
  726. else:
  727. self.axes.annotate(str(path_num), xy=local_shapes[element]['shape'].coords[0],
  728. xycoords='data', fontsize=20)
  729. patch = PolygonPatch(local_shapes[element]['shape'],
  730. facecolor=local_shapes[element]['face_color'],
  731. edgecolor=local_shapes[element]['color'],
  732. alpha=local_shapes[element]['alpha'], zorder=2)
  733. self.axes.add_patch(patch)
  734. elif obj_type == 'utility':
  735. # not a FlatCAM object, must be utility
  736. if local_shapes[element]['face_color']:
  737. try:
  738. patch = PolygonPatch(local_shapes[element]['shape'],
  739. facecolor=local_shapes[element]['face_color'],
  740. edgecolor=local_shapes[element]['color'],
  741. alpha=local_shapes[element]['alpha'],
  742. zorder=2)
  743. self.axes.add_patch(patch)
  744. except Exception as e:
  745. log.debug("ShapeCollectionLegacy.redraw() --> %s" % str(e))
  746. else:
  747. if isinstance(local_shapes[element]['shape'], Polygon):
  748. x, y = local_shapes[element]['shape'].exterior.xy
  749. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  750. for ints in local_shapes[element]['shape'].interiors:
  751. x, y = ints.coords.xy
  752. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  753. else:
  754. x, y = local_shapes[element]['shape'].coords.xy
  755. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  756. self.app.plotcanvas.auto_adjust_axes()
  757. def set(self, text, pos, visible=True, font_size=16, color=None):
  758. """
  759. This will set annotations on the canvas.
  760. :param text: a list of text elements to be used as annotations
  761. :param pos: a list of positions for showing the text elements above
  762. :param visible: if True will display annotations, if False will clear them on canvas
  763. :param font_size: the font size or the annotations
  764. :param color: color of the annotations
  765. :return: None
  766. """
  767. if color is None:
  768. color = "#000000FF"
  769. if visible is not True:
  770. self.clear()
  771. return
  772. if len(text) != len(pos):
  773. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not annotate due of a difference between the number "
  774. "of text elements and the number of text positions."))
  775. return
  776. for idx in range(len(text)):
  777. try:
  778. self.axes.annotate(text[idx], xy=pos[idx], xycoords='data', fontsize=font_size, color=color)
  779. except Exception as e:
  780. log.debug("ShapeCollectionLegacy.set() --> %s" % str(e))
  781. self.app.plotcanvas.auto_adjust_axes()
  782. @property
  783. def visible(self):
  784. return self._visible
  785. @visible.setter
  786. def visible(self, value):
  787. if value is False:
  788. self.axes.cla()
  789. self.app.plotcanvas.auto_adjust_axes()
  790. else:
  791. if self._visible is False:
  792. self.redraw()
  793. self._visible = value
  794. @property
  795. def enabled(self):
  796. return self._visible
  797. @enabled.setter
  798. def enabled(self, value):
  799. if value is False:
  800. self.axes.cla()
  801. self.app.plotcanvas.auto_adjust_axes()
  802. else:
  803. if self._visible is False:
  804. self.redraw()
  805. self._visible = value