PlotCanvasLegacy.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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. 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, Point, MultiPolygon, MultiLineString
  15. import FlatCAMApp
  16. from copy import deepcopy
  17. import logging
  18. import gettext
  19. import FlatCAMTranslation as fcTranslate
  20. import builtins
  21. # Prevent conflict with Qt5 and above.
  22. from matplotlib import use as mpl_use
  23. mpl_use("Qt5Agg")
  24. from matplotlib.figure import Figure
  25. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  26. # from matplotlib.widgets import Cursor
  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 = FigureCanvas(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. self.ch_line = None
  116. self.cv_line = None
  117. # The canvas is the top level container (FigureCanvasQTAgg)
  118. self.canvas = FigureCanvas(self.figure)
  119. self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
  120. self.canvas.setFocus()
  121. self.native = self.canvas
  122. self.adjust_axes(-10, -10, 100, 100)
  123. # self.canvas.set_can_focus(True) # For key press
  124. # Attach to parent
  125. # self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  126. self.container.addWidget(self.canvas) # Qt
  127. # Copy a bitmap of the canvas for quick animation.
  128. # Update every time the canvas is re-drawn.
  129. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  130. # ################### NOT IMPLEMENTED YET - EXPERIMENTAL #######################
  131. # ## Bitmap Cache
  132. # self.cache = CanvasCache(self, self.app)
  133. # self.cache_thread = QtCore.QThread()
  134. # self.cache.moveToThread(self.cache_thread)
  135. # # super(PlotCanvas, self).connect(self.cache_thread, QtCore.SIGNAL("started()"), self.cache.run)
  136. # self.cache_thread.started.connect(self.cache.run)
  137. #
  138. # self.cache_thread.start()
  139. # self.cache.new_screen.connect(self.on_new_screen)
  140. # ##############################################################################
  141. # Events
  142. self.mp = self.graph_event_connect('button_press_event', self.on_mouse_press)
  143. self.mr = self.graph_event_connect('button_release_event', self.on_mouse_release)
  144. self.mm = self.graph_event_connect('motion_notify_event', self.on_mouse_move)
  145. # self.canvas.connect('configure-event', self.auto_adjust_axes)
  146. self.aaa = self.graph_event_connect('resize_event', self.auto_adjust_axes)
  147. # self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  148. # self.canvas.connect("scroll-event", self.on_scroll)
  149. self.osc = self.graph_event_connect('scroll_event', self.on_scroll)
  150. # self.graph_event_connect('key_press_event', self.on_key_down)
  151. # self.graph_event_connect('key_release_event', self.on_key_up)
  152. self.odr = self.graph_event_connect('draw_event', self.on_draw)
  153. self.key = None
  154. self.pan_axes = []
  155. self.panning = False
  156. self.mouse = [0, 0]
  157. self.big_cursor = False
  158. # signal is the mouse is dragging
  159. self.is_dragging = False
  160. # signal if there is a doubleclick
  161. self.is_dblclk = False
  162. def graph_event_connect(self, event_name, callback):
  163. """
  164. Attach an event handler to the canvas through the Matplotlib interface.
  165. :param event_name: Name of the event
  166. :type event_name: str
  167. :param callback: Function to call
  168. :type callback: func
  169. :return: Connection id
  170. :rtype: int
  171. """
  172. if event_name == 'mouse_move':
  173. event_name = 'motion_notify_event'
  174. if event_name == 'mouse_press':
  175. event_name = 'button_press_event'
  176. if event_name == 'mouse_release':
  177. event_name = 'button_release_event'
  178. if event_name == 'mouse_double_click':
  179. return self.double_click.connect(callback)
  180. if event_name == 'key_press':
  181. event_name = 'key_press_event'
  182. return self.canvas.mpl_connect(event_name, callback)
  183. def graph_event_disconnect(self, cid):
  184. """
  185. Disconnect callback with the give id.
  186. :param cid: Callback id.
  187. :return: None
  188. """
  189. # self.double_click.disconnect(cid)
  190. self.canvas.mpl_disconnect(cid)
  191. def on_new_screen(self):
  192. pass
  193. # log.debug("Cache updated the screen!")
  194. def new_cursor(self, axes=None, big=None):
  195. # if axes is None:
  196. # c = MplCursor(axes=self.axes, color='black', linewidth=1)
  197. # else:
  198. # c = MplCursor(axes=axes, color='black', linewidth=1)
  199. if big is True:
  200. self.big_cursor = True
  201. self.ch_line = self.axes.axhline(color=(0.0, 0.0, 0.0), linewidth=1)
  202. self.cv_line = self.axes.axvline(color=(0.0, 0.0, 0.0), linewidth=1)
  203. c = FakeCursor()
  204. c.mouse_state_updated.connect(self.clear_cursor)
  205. return c
  206. def draw_cursor(self, x_pos, y_pos):
  207. """
  208. Draw a cursor at the mouse grid snapped position
  209. :param x_pos: mouse x position
  210. :param y_pos: mouse y position
  211. :return:
  212. """
  213. # there is no point in drawing mouse cursor when panning as it jumps in a confusing way
  214. if self.app.app_cursor.enabled is True and self.panning is False:
  215. if self.big_cursor is False:
  216. try:
  217. x, y = self.app.geo_editor.snap(x_pos, y_pos)
  218. # Pointer (snapped)
  219. # The size of the cursor is multiplied by 1.65 because that value made the cursor similar with the
  220. # one in the OpenGL(3D) graphic engine
  221. pointer_size = int(float(self.app.defaults["global_cursor_size"] ) * 1.65)
  222. elements = self.axes.plot(x, y, 'k+', ms=pointer_size, mew=1, animated=True)
  223. for el in elements:
  224. self.axes.draw_artist(el)
  225. except Exception as e:
  226. # this happen at app initialization since self.app.geo_editor does not exist yet
  227. # I could reshuffle the object instantiating order but what's the point? I could crash something else
  228. # and that's pythonic, too
  229. pass
  230. else:
  231. self.ch_line.set_ydata(y_pos)
  232. self.cv_line.set_xdata(x_pos)
  233. self.canvas.draw_idle()
  234. self.canvas.blit(self.axes.bbox)
  235. def clear_cursor(self, state):
  236. if state is True:
  237. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  238. else:
  239. self.canvas.restore_region(self.background)
  240. self.canvas.blit(self.axes.bbox)
  241. def on_key_down(self, event):
  242. """
  243. :param event:
  244. :return:
  245. """
  246. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  247. self.key = event.key
  248. def on_key_up(self, event):
  249. """
  250. :param event:
  251. :return:
  252. """
  253. self.key = None
  254. def connect(self, event_name, callback):
  255. """
  256. Attach an event handler to the canvas through the native Qt interface.
  257. :param event_name: Name of the event
  258. :type event_name: str
  259. :param callback: Function to call
  260. :type callback: function
  261. :return: Nothing
  262. """
  263. self.canvas.connect(event_name, callback)
  264. def clear(self):
  265. """
  266. Clears axes and figure.
  267. :return: None
  268. """
  269. # Clear
  270. self.axes.cla()
  271. try:
  272. self.figure.clf()
  273. except KeyError:
  274. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  275. # Re-build
  276. self.figure.add_axes(self.axes)
  277. self.axes.set_aspect(1)
  278. self.axes.grid(True)
  279. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  280. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  281. self.adjust_axes(-10, -10, 100, 100)
  282. # Re-draw
  283. self.canvas.draw_idle()
  284. def redraw(self):
  285. """
  286. Created only to serve for compatibility with the VisPy plotcanvas (the other graphic engine, 3D)
  287. :return:
  288. """
  289. self.clear()
  290. def adjust_axes(self, xmin, ymin, xmax, ymax):
  291. """
  292. Adjusts all axes while maintaining the use of the whole canvas
  293. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  294. request that will be modified to fit these restrictions.
  295. :param xmin: Requested minimum value for the X axis.
  296. :type xmin: float
  297. :param ymin: Requested minimum value for the Y axis.
  298. :type ymin: float
  299. :param xmax: Requested maximum value for the X axis.
  300. :type xmax: float
  301. :param ymax: Requested maximum value for the Y axis.
  302. :type ymax: float
  303. :return: None
  304. """
  305. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  306. if not self.app.collection.get_list():
  307. xmin = -10
  308. ymin = -10
  309. xmax = 100
  310. ymax = 100
  311. width = xmax - xmin
  312. height = ymax - ymin
  313. try:
  314. r = width / height
  315. except ZeroDivisionError:
  316. FlatCAMApp.App.log.error("Height is %f" % height)
  317. return
  318. canvas_w, canvas_h = self.canvas.get_width_height()
  319. canvas_r = float(canvas_w) / canvas_h
  320. x_ratio = float(self.x_margin) / canvas_w
  321. y_ratio = float(self.y_margin) / canvas_h
  322. if r > canvas_r:
  323. ycenter = (ymin + ymax) / 2.0
  324. newheight = height * r / canvas_r
  325. ymin = ycenter - newheight / 2.0
  326. ymax = ycenter + newheight / 2.0
  327. else:
  328. xcenter = (xmax + xmin) / 2.0
  329. newwidth = width * canvas_r / r
  330. xmin = xcenter - newwidth / 2.0
  331. xmax = xcenter + newwidth / 2.0
  332. # Adjust axes
  333. for ax in self.figure.get_axes():
  334. if ax._label != 'base':
  335. ax.set_frame_on(False) # No frame
  336. ax.set_xticks([]) # No tick
  337. ax.set_yticks([]) # No ticks
  338. ax.patch.set_visible(False) # No background
  339. ax.set_aspect(1)
  340. ax.set_xlim((xmin, xmax))
  341. ax.set_ylim((ymin, ymax))
  342. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  343. # Sync re-draw to proper paint on form resize
  344. self.canvas.draw()
  345. # #### Temporary place-holder for cached update #####
  346. self.update_screen_request.emit([0, 0, 0, 0, 0])
  347. def auto_adjust_axes(self, *args):
  348. """
  349. Calls ``adjust_axes()`` using the extents of the base axes.
  350. :rtype : None
  351. :return: None
  352. """
  353. xmin, xmax = self.axes.get_xlim()
  354. ymin, ymax = self.axes.get_ylim()
  355. self.adjust_axes(xmin, ymin, xmax, ymax)
  356. def fit_view(self):
  357. self.auto_adjust_axes()
  358. def fit_center(self, loc, rect=None):
  359. x = loc[0]
  360. y = loc[1]
  361. xmin, xmax = self.axes.get_xlim()
  362. ymin, ymax = self.axes.get_ylim()
  363. half_width = (xmax - xmin) / 2
  364. half_height = (ymax - ymin) / 2
  365. # Adjust axes
  366. for ax in self.figure.get_axes():
  367. ax.set_xlim((x - half_width , x + half_width))
  368. ax.set_ylim((y - half_height, y + half_height))
  369. # Re-draw
  370. self.canvas.draw()
  371. # #### Temporary place-holder for cached update #####
  372. self.update_screen_request.emit([0, 0, 0, 0, 0])
  373. def zoom(self, factor, center=None):
  374. """
  375. Zooms the plot by factor around a given
  376. center point. Takes care of re-drawing.
  377. :param factor: Number by which to scale the plot.
  378. :type factor: float
  379. :param center: Coordinates [x, y] of the point around which to scale the plot.
  380. :type center: list
  381. :return: None
  382. """
  383. factor = 1 / factor
  384. xmin, xmax = self.axes.get_xlim()
  385. ymin, ymax = self.axes.get_ylim()
  386. width = xmax - xmin
  387. height = ymax - ymin
  388. if center is None or center == [None, None]:
  389. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  390. # For keeping the point at the pointer location
  391. relx = (xmax - center[0]) / width
  392. rely = (ymax - center[1]) / height
  393. new_width = width / factor
  394. new_height = height / factor
  395. xmin = center[0] - new_width * (1 - relx)
  396. xmax = center[0] + new_width * relx
  397. ymin = center[1] - new_height * (1 - rely)
  398. ymax = center[1] + new_height * rely
  399. # Adjust axes
  400. for ax in self.figure.get_axes():
  401. ax.set_xlim((xmin, xmax))
  402. ax.set_ylim((ymin, ymax))
  403. # Async re-draw
  404. self.canvas.draw_idle()
  405. # #### Temporary place-holder for cached update #####
  406. self.update_screen_request.emit([0, 0, 0, 0, 0])
  407. def pan(self, x, y, idle=True):
  408. xmin, xmax = self.axes.get_xlim()
  409. ymin, ymax = self.axes.get_ylim()
  410. width = xmax - xmin
  411. height = ymax - ymin
  412. # Adjust axes
  413. for ax in self.figure.get_axes():
  414. ax.set_xlim((xmin + x * width, xmax + x * width))
  415. ax.set_ylim((ymin + y * height, ymax + y * height))
  416. # Re-draw
  417. if idle:
  418. self.canvas.draw_idle()
  419. else:
  420. self.canvas.draw()
  421. # #### Temporary place-holder for cached update #####
  422. self.update_screen_request.emit([0, 0, 0, 0, 0])
  423. def new_axes(self, name):
  424. """
  425. Creates and returns an Axes object attached to this object's Figure.
  426. :param name: Unique label for the axes.
  427. :return: Axes attached to the figure.
  428. :rtype: Axes
  429. """
  430. new_ax = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  431. return new_ax
  432. def remove_current_axes(self):
  433. """
  434. :return: The name of the deleted axes
  435. """
  436. axes_to_remove = self.figure.axes.gca()
  437. current_axes_name = deepcopy(axes_to_remove._label)
  438. self.figure.axes.remove(axes_to_remove)
  439. return current_axes_name
  440. def on_scroll(self, event):
  441. """
  442. Scroll event handler.
  443. :param event: Event object containing the event information.
  444. :return: None
  445. """
  446. # So it can receive key presses
  447. # self.canvas.grab_focus()
  448. self.canvas.setFocus()
  449. # Event info
  450. # z, direction = event.get_scroll_direction()
  451. if self.key is None:
  452. if event.button == 'up':
  453. self.zoom(1 / 1.5, self.mouse)
  454. else:
  455. self.zoom(1.5, self.mouse)
  456. return
  457. if self.key == 'shift':
  458. if event.button == 'up':
  459. self.pan(0.3, 0)
  460. else:
  461. self.pan(-0.3, 0)
  462. return
  463. if self.key == 'control':
  464. if event.button == 'up':
  465. self.pan(0, 0.3)
  466. else:
  467. self.pan(0, -0.3)
  468. return
  469. def on_mouse_press(self, event):
  470. self.is_dragging = True
  471. # Check for middle mouse button press
  472. if self.app.defaults["global_pan_button"] == '2':
  473. pan_button = 3 # right button for Matplotlib
  474. else:
  475. pan_button = 2 # middle button for Matplotlib
  476. if event.button == pan_button:
  477. # Prepare axes for pan (using 'matplotlib' pan function)
  478. self.pan_axes = []
  479. for a in self.figure.get_axes():
  480. if (event.x is not None and event.y is not None and a.in_axes(event) and
  481. a.get_navigate() and a.can_pan()):
  482. a.start_pan(event.x, event.y, 1)
  483. self.pan_axes.append(a)
  484. # Set pan view flag
  485. if len(self.pan_axes) > 0:
  486. self.panning = True
  487. if event.dblclick:
  488. self.double_click.emit(event)
  489. def on_mouse_release(self, event):
  490. self.is_dragging = False
  491. # Check for middle mouse button release to complete pan procedure
  492. # Check for middle mouse button press
  493. if self.app.defaults["global_pan_button"] == '2':
  494. pan_button = 3 # right button for Matplotlib
  495. else:
  496. pan_button = 2 # middle button for Matplotlib
  497. if event.button == pan_button:
  498. for a in self.pan_axes:
  499. a.end_pan()
  500. # Clear pan flag
  501. self.panning = False
  502. # And update the cursor
  503. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  504. def on_mouse_move(self, event):
  505. """
  506. Mouse movement event handler. Stores the coordinates. Updates view on pan.
  507. :param event: Contains information about the event.
  508. :return: None
  509. """
  510. try:
  511. x = float(event.xdata)
  512. y = float(event.ydata)
  513. except TypeError:
  514. return
  515. self.mouse = [event.xdata, event.ydata]
  516. self.canvas.restore_region(self.background)
  517. # Update pan view on mouse move
  518. if self.panning is True:
  519. for a in self.pan_axes:
  520. a.drag_pan(1, event.key, event.x, event.y)
  521. # x_pan, y_pan = self.app.geo_editor.snap(event.xdata, event.ydata)
  522. # self.draw_cursor(x_pos=x_pan, y_pos=y_pan)
  523. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  524. self.canvas.draw_idle()
  525. # #### Temporary place-holder for cached update #####
  526. self.update_screen_request.emit([0, 0, 0, 0, 0])
  527. self.draw_cursor(x_pos=x, y_pos=y)
  528. # self.canvas.blit(self.axes.bbox)
  529. def translate_coords(self, position):
  530. """
  531. This does not do much. It's just for code compatibility
  532. :param position: Mouse event position
  533. :return: Tuple with mouse position
  534. """
  535. return position[0], position[1]
  536. def on_draw(self, renderer):
  537. # Store background on canvas redraw
  538. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  539. def get_axes_pixelsize(self):
  540. """
  541. Axes size in pixels.
  542. :return: Pixel width and height
  543. :rtype: tuple
  544. """
  545. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  546. width, height = bbox.width, bbox.height
  547. width *= self.figure.dpi
  548. height *= self.figure.dpi
  549. return width, height
  550. def get_density(self):
  551. """
  552. Returns unit length per pixel on horizontal
  553. and vertical axes.
  554. :return: X and Y density
  555. :rtype: tuple
  556. """
  557. xpx, ypx = self.get_axes_pixelsize()
  558. xmin, xmax = self.axes.get_xlim()
  559. ymin, ymax = self.axes.get_ylim()
  560. width = xmax - xmin
  561. height = ymax - ymin
  562. return width / xpx, height / ypx
  563. class FakeCursor(QtCore.QObject):
  564. """
  565. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  566. This way I don't have to chane (disable) things related to the cursor all over when
  567. using the low performance Matplotlib 2D graphic engine.
  568. """
  569. mouse_state_updated = pyqtSignal(bool)
  570. def __init__(self):
  571. super().__init__()
  572. self._enabled = True
  573. @property
  574. def enabled(self):
  575. return True if self._enabled else False
  576. @enabled.setter
  577. def enabled(self, value):
  578. self._enabled = value
  579. self.mouse_state_updated.emit(value)
  580. def set_data(self, pos, **kwargs):
  581. """Internal event handler to draw the cursor when the mouse moves."""
  582. class ShapeCollectionLegacy:
  583. """
  584. This will create the axes for each collection of shapes and will also
  585. hold the collection of shapes into a dict self._shapes.
  586. This handles the shapes redraw on canvas.
  587. """
  588. def __init__(self, obj, app, name=None, annotation_job=None):
  589. """
  590. :param obj: this is the object to which the shapes collection is attached and for
  591. which it will have to draw shapes
  592. :param app: this is the FLatCAM.App usually, needed because we have to access attributes there
  593. :param name: this is the name given to the Matplotlib axes; it needs to be unique due of Matplotlib requurements
  594. :param annotation_job: make this True if the job needed is just for annotation
  595. """
  596. self.obj = obj
  597. self.app = app
  598. self.annotation_job = annotation_job
  599. self._shapes = dict()
  600. self.shape_dict = dict()
  601. self.shape_id = 0
  602. self._color = None
  603. self._face_color = None
  604. self._visible = True
  605. self._update = False
  606. self._alpha = None
  607. self._tool_tolerance = None
  608. self._tooldia = None
  609. self._obj = None
  610. self._gcode_parsed = None
  611. if name is None:
  612. axes_name = self.obj.options['name']
  613. else:
  614. axes_name = name
  615. # Axes must exist and be attached to canvas.
  616. if axes_name not in self.app.plotcanvas.figure.axes:
  617. self.axes = self.app.plotcanvas.new_axes(axes_name)
  618. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  619. update=False, layer=1, tolerance=0.01, obj=None, gcode_parsed=None, tool_tolerance=None, tooldia=None):
  620. """
  621. This function will add shapes to the shape collection
  622. :param shape: the Shapely shape to be added to the shape collection
  623. :param color: edge color of the shape, hex value
  624. :param face_color: the body color of the shape, hex value
  625. :param alpha: level of transparency of the shape [0.0 ... 1.0]; Float
  626. :param visible: if True will allow the shapes to be added
  627. :param update: not used; just for compatibility with VIsPy canvas
  628. :param layer: just for compatibility with VIsPy canvas
  629. :param tolerance: just for compatibility with VIsPy canvas
  630. :param obj: not used
  631. :param gcode_parsed: not used; just for compatibility with VIsPy canvas
  632. :param tool_tolerance: just for compatibility with VIsPy canvas
  633. :param tooldia:
  634. :return:
  635. """
  636. self._color = color[:-2] if color is not None else None
  637. self._face_color = face_color[:-2] if face_color is not None else None
  638. self._alpha = int(face_color[-2:], 16) / 255 if face_color is not None else 0.75
  639. if alpha is not None:
  640. self._alpha = alpha
  641. self._visible = visible
  642. self._update = update
  643. # CNCJob object related arguments
  644. self._obj = obj
  645. self._gcode_parsed = gcode_parsed
  646. self._tool_tolerance = tool_tolerance
  647. self._tooldia = tooldia
  648. # if self._update:
  649. # self.clear()
  650. try:
  651. for sh in shape:
  652. self.shape_id += 1
  653. self.shape_dict.update({
  654. 'color': self._color,
  655. 'face_color': self._face_color,
  656. 'alpha': self._alpha,
  657. 'shape': sh
  658. })
  659. self._shapes.update({
  660. self.shape_id: deepcopy(self.shape_dict)
  661. })
  662. except TypeError:
  663. self.shape_id += 1
  664. self.shape_dict.update({
  665. 'color': self._color,
  666. 'face_color': self._face_color,
  667. 'alpha': self._alpha,
  668. 'shape': shape
  669. })
  670. self._shapes.update({
  671. self.shape_id: deepcopy(self.shape_dict)
  672. })
  673. return self.shape_id
  674. def clear(self, update=None):
  675. """
  676. Clear the canvas of the shapes.
  677. :param update:
  678. :return: None
  679. """
  680. self._shapes.clear()
  681. self.shape_id = 0
  682. self.axes.cla()
  683. try:
  684. self.app.plotcanvas.auto_adjust_axes()
  685. except Exception as e:
  686. log.debug("ShapeCollectionLegacy.clear() --> %s" % str(e))
  687. if update is True:
  688. self.redraw()
  689. def redraw(self):
  690. """
  691. This draw the shapes in the shapes collection, on canvas
  692. :return: None
  693. """
  694. path_num = 0
  695. local_shapes = deepcopy(self._shapes)
  696. try:
  697. obj_type = self.obj.kind
  698. except AttributeError:
  699. obj_type = 'utility'
  700. if self._visible:
  701. for element in local_shapes:
  702. if obj_type == 'excellon':
  703. # Plot excellon (All polygons?)
  704. if self.obj.options["solid"] and isinstance(local_shapes[element]['shape'], Polygon):
  705. patch = PolygonPatch(local_shapes[element]['shape'],
  706. facecolor="#C40000",
  707. edgecolor="#750000",
  708. alpha=local_shapes[element]['alpha'],
  709. zorder=3)
  710. self.axes.add_patch(patch)
  711. else:
  712. x, y = local_shapes[element]['shape'].exterior.coords.xy
  713. self.axes.plot(x, y, 'r-')
  714. for ints in local_shapes[element]['shape'].interiors:
  715. x, y = ints.coords.xy
  716. self.axes.plot(x, y, 'o-')
  717. elif obj_type == 'geometry':
  718. if type(local_shapes[element]['shape']) == Polygon:
  719. x, y = local_shapes[element]['shape'].exterior.coords.xy
  720. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  721. for ints in local_shapes[element]['shape'].interiors:
  722. x, y = ints.coords.xy
  723. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  724. elif type(local_shapes[element]['shape']) == LineString or \
  725. type(local_shapes[element]['shape']) == LinearRing:
  726. x, y = local_shapes[element]['shape'].coords.xy
  727. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  728. elif obj_type == 'gerber':
  729. if self.obj.options["multicolored"]:
  730. linespec = '-'
  731. else:
  732. linespec = 'k-'
  733. if self.obj.options["solid"]:
  734. try:
  735. patch = PolygonPatch(local_shapes[element]['shape'],
  736. facecolor=local_shapes[element]['face_color'],
  737. edgecolor=local_shapes[element]['color'],
  738. alpha=local_shapes[element]['alpha'],
  739. zorder=2)
  740. self.axes.add_patch(patch)
  741. except AssertionError:
  742. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  743. FlatCAMApp.App.log.warning(str(element))
  744. else:
  745. x, y = local_shapes[element]['shape'].exterior.xy
  746. self.axes.plot(x, y, linespec)
  747. for ints in local_shapes[element]['shape'].interiors:
  748. x, y = ints.coords.xy
  749. self.axes.plot(x, y, linespec)
  750. elif obj_type == 'cncjob':
  751. if local_shapes[element]['face_color'] is None:
  752. linespec = '--'
  753. linecolor = local_shapes[element]['color']
  754. # if geo['kind'][0] == 'C':
  755. # linespec = 'k-'
  756. x, y = local_shapes[element]['shape'].coords.xy
  757. self.axes.plot(x, y, linespec, color=linecolor)
  758. else:
  759. path_num += 1
  760. if self.obj.ui.annotation_cb.get_value():
  761. if isinstance(local_shapes[element]['shape'], Polygon):
  762. self.axes.annotate(
  763. str(path_num),
  764. xy=local_shapes[element]['shape'].exterior.coords[0],
  765. xycoords='data', fontsize=20)
  766. else:
  767. self.axes.annotate(
  768. str(path_num),
  769. xy=local_shapes[element]['shape'].coords[0],
  770. xycoords='data', fontsize=20)
  771. patch = PolygonPatch(local_shapes[element]['shape'],
  772. facecolor=local_shapes[element]['face_color'],
  773. edgecolor=local_shapes[element]['color'],
  774. alpha=local_shapes[element]['alpha'], zorder=2)
  775. self.axes.add_patch(patch)
  776. elif obj_type == 'utility':
  777. # not a FlatCAM object, must be utility
  778. if local_shapes[element]['face_color']:
  779. try:
  780. patch = PolygonPatch(local_shapes[element]['shape'],
  781. facecolor=local_shapes[element]['face_color'],
  782. edgecolor=local_shapes[element]['color'],
  783. alpha=local_shapes[element]['alpha'],
  784. zorder=2)
  785. self.axes.add_patch(patch)
  786. except Exception as e:
  787. log.debug("ShapeCollectionLegacy.redraw() --> %s" % str(e))
  788. else:
  789. if isinstance(local_shapes[element]['shape'], Polygon):
  790. ext_shape = local_shapes[element]['shape'].exterior
  791. if ext_shape is not None:
  792. x, y = ext_shape.xy
  793. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  794. for ints in local_shapes[element]['shape'].interiors:
  795. if ints is not None:
  796. x, y = ints.coords.xy
  797. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  798. else:
  799. if local_shapes[element]['shape'] is not None:
  800. x, y = local_shapes[element]['shape'].coords.xy
  801. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  802. self.app.plotcanvas.auto_adjust_axes()
  803. def set(self, text, pos, visible=True, font_size=16, color=None):
  804. """
  805. This will set annotations on the canvas.
  806. :param text: a list of text elements to be used as annotations
  807. :param pos: a list of positions for showing the text elements above
  808. :param visible: if True will display annotations, if False will clear them on canvas
  809. :param font_size: the font size or the annotations
  810. :param color: color of the annotations
  811. :return: None
  812. """
  813. if color is None:
  814. color = "#000000FF"
  815. if visible is not True:
  816. self.clear()
  817. return
  818. if len(text) != len(pos):
  819. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not annotate due of a difference between the number "
  820. "of text elements and the number of text positions."))
  821. return
  822. for idx in range(len(text)):
  823. try:
  824. self.axes.annotate(text[idx], xy=pos[idx], xycoords='data', fontsize=font_size, color=color)
  825. except Exception as e:
  826. log.debug("ShapeCollectionLegacy.set() --> %s" % str(e))
  827. self.app.plotcanvas.auto_adjust_axes()
  828. @property
  829. def visible(self):
  830. return self._visible
  831. @visible.setter
  832. def visible(self, value):
  833. if value is False:
  834. self.axes.cla()
  835. self.app.plotcanvas.auto_adjust_axes()
  836. else:
  837. if self._visible is False:
  838. self.redraw()
  839. self._visible = value
  840. @property
  841. def enabled(self):
  842. return self._visible
  843. @enabled.setter
  844. def enabled(self, value):
  845. if value is False:
  846. self.axes.cla()
  847. self.app.plotcanvas.auto_adjust_axes()
  848. else:
  849. if self._visible is False:
  850. self.redraw()
  851. self._visible = value
  852. # class MplCursor(Cursor):
  853. # """
  854. # Unfortunately this gets attached to the current axes and if a new axes is added
  855. # it will not be showed until that axes is deleted.
  856. # Not the kind of behavior needed here so I don't use it anymore.
  857. # """
  858. # def __init__(self, axes, color='red', linewidth=1):
  859. #
  860. # super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  861. # self._enabled = True
  862. #
  863. # self.axes = axes
  864. # self.color = color
  865. # self.linewidth = linewidth
  866. #
  867. # self.x = None
  868. # self.y = None
  869. #
  870. # @property
  871. # def enabled(self):
  872. # return True if self._enabled else False
  873. #
  874. # @enabled.setter
  875. # def enabled(self, value):
  876. # self._enabled = value
  877. # self.visible = self._enabled
  878. # self.canvas.draw()
  879. #
  880. # def onmove(self, event):
  881. # pass
  882. #
  883. # def set_data(self, event, pos):
  884. # """Internal event handler to draw the cursor when the mouse moves."""
  885. # self.x = pos[0]
  886. # self.y = pos[1]
  887. #
  888. # if self.ignore(event):
  889. # return
  890. # if not self.canvas.widgetlock.available(self):
  891. # return
  892. # if event.inaxes != self.ax:
  893. # self.linev.set_visible(False)
  894. # self.lineh.set_visible(False)
  895. #
  896. # if self.needclear:
  897. # self.canvas.draw()
  898. # self.needclear = False
  899. # return
  900. # self.needclear = True
  901. # if not self.visible:
  902. # return
  903. # self.linev.set_xdata((self.x, self.x))
  904. #
  905. # self.lineh.set_ydata((self.y, self.y))
  906. # self.linev.set_visible(self.visible and self.vertOn)
  907. # self.lineh.set_visible(self.visible and self.horizOn)
  908. #
  909. # self._update()