PlotCanvasLegacy.py 46 KB

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