PlotCanvasLegacy.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. :return:
  323. """
  324. # there is no point in drawing mouse cursor when panning as it jumps in a confusing way
  325. if self.app.app_cursor.enabled is True and self.panning is False:
  326. if color:
  327. color = color
  328. else:
  329. if self.app.defaults['global_theme'] == 'white':
  330. color = '#000000'
  331. else:
  332. color = '#FFFFFF'
  333. if self.big_cursor is False:
  334. try:
  335. x, y = self.app.geo_editor.snap(x_pos, y_pos)
  336. # Pointer (snapped)
  337. # The size of the cursor is multiplied by 1.65 because that value made the cursor similar with the
  338. # one in the OpenGL(3D) graphic engine
  339. pointer_size = int(float(self.app.defaults["global_cursor_size"] ) * 1.65)
  340. elements = self.axes.plot(x, y, '+', color=color, ms=pointer_size,
  341. mew=self.app.defaults["global_cursor_width"], animated=True)
  342. for el in elements:
  343. self.axes.draw_artist(el)
  344. except Exception:
  345. # this happen at app initialization since self.app.geo_editor does not exist yet
  346. # I could reshuffle the object instantiating order but what's the point?
  347. # I could crash something else and that's pythonic, too
  348. pass
  349. else:
  350. self.ch_line.set_ydata(y_pos)
  351. self.cv_line.set_xdata(x_pos)
  352. self.canvas.draw_idle()
  353. self.canvas.blit(self.axes.bbox)
  354. def clear_cursor(self, state):
  355. if state is True:
  356. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  357. else:
  358. if self.big_cursor is True:
  359. self.ch_line.remove()
  360. self.cv_line.remove()
  361. self.canvas.draw_idle()
  362. self.canvas.restore_region(self.background)
  363. self.canvas.blit(self.axes.bbox)
  364. def on_key_down(self, event):
  365. """
  366. :param event:
  367. :return:
  368. """
  369. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  370. self.key = event.key
  371. def on_key_up(self, event):
  372. """
  373. :param event:
  374. :return:
  375. """
  376. self.key = None
  377. def connect(self, event_name, callback):
  378. """
  379. Attach an event handler to the canvas through the native Qt interface.
  380. :param event_name: Name of the event
  381. :type event_name: str
  382. :param callback: Function to call
  383. :type callback: function
  384. :return: Nothing
  385. """
  386. self.canvas.connect(event_name, callback)
  387. def clear(self):
  388. """
  389. Clears axes and figure.
  390. :return: None
  391. """
  392. # Clear
  393. self.axes.cla()
  394. try:
  395. self.figure.clf()
  396. except KeyError:
  397. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  398. # Re-build
  399. self.figure.add_axes(self.axes)
  400. self.axes.set_aspect(1)
  401. self.axes.grid(True)
  402. self.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  403. self.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  404. self.adjust_axes(-10, -10, 100, 100)
  405. # Re-draw
  406. self.canvas.draw_idle()
  407. def redraw(self):
  408. """
  409. Created only to serve for compatibility with the VisPy plotcanvas (the other graphic engine, 3D)
  410. :return:
  411. """
  412. self.clear()
  413. def adjust_axes(self, xmin, ymin, xmax, ymax):
  414. """
  415. Adjusts all axes while maintaining the use of the whole canvas
  416. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  417. request that will be modified to fit these restrictions.
  418. :param xmin: Requested minimum value for the X axis.
  419. :type xmin: float
  420. :param ymin: Requested minimum value for the Y axis.
  421. :type ymin: float
  422. :param xmax: Requested maximum value for the X axis.
  423. :type xmax: float
  424. :param ymax: Requested maximum value for the Y axis.
  425. :type ymax: float
  426. :return: None
  427. """
  428. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  429. if not self.app.collection.get_list():
  430. xmin = -10
  431. ymin = -10
  432. xmax = 100
  433. ymax = 100
  434. width = xmax - xmin
  435. height = ymax - ymin
  436. try:
  437. r = width / height
  438. except ZeroDivisionError:
  439. FlatCAMApp.App.log.error("Height is %f" % height)
  440. return
  441. canvas_w, canvas_h = self.canvas.get_width_height()
  442. canvas_r = float(canvas_w) / canvas_h
  443. x_ratio = float(self.x_margin) / canvas_w
  444. y_ratio = float(self.y_margin) / canvas_h
  445. if r > canvas_r:
  446. ycenter = (ymin + ymax) / 2.0
  447. newheight = height * r / canvas_r
  448. ymin = ycenter - newheight / 2.0
  449. ymax = ycenter + newheight / 2.0
  450. else:
  451. xcenter = (xmax + xmin) / 2.0
  452. newwidth = width * canvas_r / r
  453. xmin = xcenter - newwidth / 2.0
  454. xmax = xcenter + newwidth / 2.0
  455. # Adjust axes
  456. for ax in self.figure.get_axes():
  457. if ax._label != 'base':
  458. ax.set_frame_on(False) # No frame
  459. ax.set_xticks([]) # No tick
  460. ax.set_yticks([]) # No ticks
  461. ax.patch.set_visible(False) # No background
  462. ax.set_aspect(1)
  463. ax.set_xlim((xmin, xmax))
  464. ax.set_ylim((ymin, ymax))
  465. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  466. # Sync re-draw to proper paint on form resize
  467. self.canvas.draw()
  468. # #### Temporary place-holder for cached update #####
  469. self.update_screen_request.emit([0, 0, 0, 0, 0])
  470. def auto_adjust_axes(self, *args):
  471. """
  472. Calls ``adjust_axes()`` using the extents of the base axes.
  473. :rtype : None
  474. :return: None
  475. """
  476. xmin, xmax = self.axes.get_xlim()
  477. ymin, ymax = self.axes.get_ylim()
  478. self.adjust_axes(xmin, ymin, xmax, ymax)
  479. def fit_view(self):
  480. self.auto_adjust_axes()
  481. def fit_center(self, loc, rect=None):
  482. x = loc[0]
  483. y = loc[1]
  484. xmin, xmax = self.axes.get_xlim()
  485. ymin, ymax = self.axes.get_ylim()
  486. half_width = (xmax - xmin) / 2
  487. half_height = (ymax - ymin) / 2
  488. # Adjust axes
  489. for ax in self.figure.get_axes():
  490. ax.set_xlim((x - half_width, x + half_width))
  491. ax.set_ylim((y - half_height, y + half_height))
  492. # Re-draw
  493. self.canvas.draw()
  494. # #### Temporary place-holder for cached update #####
  495. self.update_screen_request.emit([0, 0, 0, 0, 0])
  496. def zoom(self, factor, center=None):
  497. """
  498. Zooms the plot by factor around a given
  499. center point. Takes care of re-drawing.
  500. :param factor: Number by which to scale the plot.
  501. :type factor: float
  502. :param center: Coordinates [x, y] of the point around which to scale the plot.
  503. :type center: list
  504. :return: None
  505. """
  506. factor = 1 / factor
  507. xmin, xmax = self.axes.get_xlim()
  508. ymin, ymax = self.axes.get_ylim()
  509. width = xmax - xmin
  510. height = ymax - ymin
  511. if center is None or center == [None, None]:
  512. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  513. # For keeping the point at the pointer location
  514. relx = (xmax - center[0]) / width
  515. rely = (ymax - center[1]) / height
  516. new_width = width / factor
  517. new_height = height / factor
  518. xmin = center[0] - new_width * (1 - relx)
  519. xmax = center[0] + new_width * relx
  520. ymin = center[1] - new_height * (1 - rely)
  521. ymax = center[1] + new_height * rely
  522. # Adjust axes
  523. for ax in self.figure.get_axes():
  524. ax.set_xlim((xmin, xmax))
  525. ax.set_ylim((ymin, ymax))
  526. # Async re-draw
  527. self.canvas.draw_idle()
  528. # #### Temporary place-holder for cached update #####
  529. self.update_screen_request.emit([0, 0, 0, 0, 0])
  530. def pan(self, x, y, idle=True):
  531. xmin, xmax = self.axes.get_xlim()
  532. ymin, ymax = self.axes.get_ylim()
  533. width = xmax - xmin
  534. height = ymax - ymin
  535. # Adjust axes
  536. for ax in self.figure.get_axes():
  537. ax.set_xlim((xmin + x * width, xmax + x * width))
  538. ax.set_ylim((ymin + y * height, ymax + y * height))
  539. # Re-draw
  540. if idle:
  541. self.canvas.draw_idle()
  542. else:
  543. self.canvas.draw()
  544. # #### Temporary place-holder for cached update #####
  545. self.update_screen_request.emit([0, 0, 0, 0, 0])
  546. def new_axes(self, name):
  547. """
  548. Creates and returns an Axes object attached to this object's Figure.
  549. :param name: Unique label for the axes.
  550. :return: Axes attached to the figure.
  551. :rtype: Axes
  552. """
  553. new_ax = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  554. return new_ax
  555. def remove_current_axes(self):
  556. """
  557. :return: The name of the deleted axes
  558. """
  559. axes_to_remove = self.figure.axes.gca()
  560. current_axes_name = deepcopy(axes_to_remove._label)
  561. self.figure.axes.remove(axes_to_remove)
  562. return current_axes_name
  563. def on_scroll(self, event):
  564. """
  565. Scroll event handler.
  566. :param event: Event object containing the event information.
  567. :return: None
  568. """
  569. # So it can receive key presses
  570. # self.canvas.grab_focus()
  571. self.canvas.setFocus()
  572. # Event info
  573. # z, direction = event.get_scroll_direction()
  574. if self.key is None:
  575. if event.button == 'up':
  576. self.zoom(1 / 1.5, self.mouse)
  577. else:
  578. self.zoom(1.5, self.mouse)
  579. return
  580. if self.key == 'shift':
  581. if event.button == 'up':
  582. self.pan(0.3, 0)
  583. else:
  584. self.pan(-0.3, 0)
  585. return
  586. if self.key == 'control':
  587. if event.button == 'up':
  588. self.pan(0, 0.3)
  589. else:
  590. self.pan(0, -0.3)
  591. return
  592. def on_mouse_press(self, event):
  593. self.is_dragging = True
  594. # Check for middle mouse button press
  595. if self.app.defaults["global_pan_button"] == '2':
  596. pan_button = 3 # right button for Matplotlib
  597. else:
  598. pan_button = 2 # middle button for Matplotlib
  599. if event.button == pan_button:
  600. # Prepare axes for pan (using 'matplotlib' pan function)
  601. self.pan_axes = []
  602. for a in self.figure.get_axes():
  603. if (event.x is not None and event.y is not None and a.in_axes(event) and
  604. a.get_navigate() and a.can_pan()):
  605. a.start_pan(event.x, event.y, 1)
  606. self.pan_axes.append(a)
  607. # Set pan view flag
  608. if len(self.pan_axes) > 0:
  609. self.panning = True
  610. if event.dblclick:
  611. self.double_click.emit(event)
  612. def on_mouse_release(self, event):
  613. self.is_dragging = False
  614. # Check for middle mouse button release to complete pan procedure
  615. # Check for middle mouse button press
  616. if self.app.defaults["global_pan_button"] == '2':
  617. pan_button = 3 # right button for Matplotlib
  618. else:
  619. pan_button = 2 # middle button for Matplotlib
  620. if event.button == pan_button:
  621. for a in self.pan_axes:
  622. a.end_pan()
  623. # Clear pan flag
  624. self.panning = False
  625. # And update the cursor
  626. self.draw_cursor(x_pos=self.mouse[0], y_pos=self.mouse[1])
  627. def on_mouse_move(self, event):
  628. """
  629. Mouse movement event handler. Stores the coordinates. Updates view on pan.
  630. :param event: Contains information about the event.
  631. :return: None
  632. """
  633. try:
  634. x = float(event.xdata)
  635. y = float(event.ydata)
  636. except TypeError:
  637. return
  638. self.mouse = [event.xdata, event.ydata]
  639. self.canvas.restore_region(self.background)
  640. # Update pan view on mouse move
  641. if self.panning is True:
  642. for a in self.pan_axes:
  643. a.drag_pan(1, event.key, event.x, event.y)
  644. # x_pan, y_pan = self.app.geo_editor.snap(event.xdata, event.ydata)
  645. # self.draw_cursor(x_pos=x_pan, y_pos=y_pan)
  646. # Async re-draw (redraws only on thread idle state, uses timer on backend)
  647. self.canvas.draw_idle()
  648. # #### Temporary place-holder for cached update #####
  649. self.update_screen_request.emit([0, 0, 0, 0, 0])
  650. self.draw_cursor(x_pos=x, y_pos=y)
  651. # self.canvas.blit(self.axes.bbox)
  652. def translate_coords(self, position):
  653. """
  654. This does not do much. It's just for code compatibility
  655. :param position: Mouse event position
  656. :return: Tuple with mouse position
  657. """
  658. return position[0], position[1]
  659. def on_draw(self, renderer):
  660. # Store background on canvas redraw
  661. self.background = self.canvas.copy_from_bbox(self.axes.bbox)
  662. def get_axes_pixelsize(self):
  663. """
  664. Axes size in pixels.
  665. :return: Pixel width and height
  666. :rtype: tuple
  667. """
  668. bbox = self.axes.get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
  669. width, height = bbox.width, bbox.height
  670. width *= self.figure.dpi
  671. height *= self.figure.dpi
  672. return width, height
  673. def get_density(self):
  674. """
  675. Returns unit length per pixel on horizontal
  676. and vertical axes.
  677. :return: X and Y density
  678. :rtype: tuple
  679. """
  680. xpx, ypx = self.get_axes_pixelsize()
  681. xmin, xmax = self.axes.get_xlim()
  682. ymin, ymax = self.axes.get_ylim()
  683. width = xmax - xmin
  684. height = ymax - ymin
  685. return width / xpx, height / ypx
  686. class FakeCursor(QtCore.QObject):
  687. """
  688. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  689. This way I don't have to chane (disable) things related to the cursor all over when
  690. using the low performance Matplotlib 2D graphic engine.
  691. """
  692. mouse_state_updated = pyqtSignal(bool)
  693. def __init__(self):
  694. super().__init__()
  695. self._enabled = True
  696. @property
  697. def enabled(self):
  698. return True if self._enabled else False
  699. @enabled.setter
  700. def enabled(self, value):
  701. self._enabled = value
  702. self.mouse_state_updated.emit(value)
  703. def set_data(self, pos, **kwargs):
  704. """Internal event handler to draw the cursor when the mouse moves."""
  705. class ShapeCollectionLegacy:
  706. """
  707. This will create the axes for each collection of shapes and will also
  708. hold the collection of shapes into a dict self._shapes.
  709. This handles the shapes redraw on canvas.
  710. """
  711. def __init__(self, obj, app, name=None, annotation_job=None):
  712. """
  713. :param obj: this is the object to which the shapes collection is attached and for
  714. which it will have to draw shapes
  715. :param app: this is the FLatCAM.App usually, needed because we have to access attributes there
  716. :param name: this is the name given to the Matplotlib axes; it needs to be unique due of Matplotlib requurements
  717. :param annotation_job: make this True if the job needed is just for annotation
  718. """
  719. self.obj = obj
  720. self.app = app
  721. self.annotation_job = annotation_job
  722. self._shapes = dict()
  723. self.shape_dict = dict()
  724. self.shape_id = 0
  725. self._color = None
  726. self._face_color = None
  727. self._visible = True
  728. self._update = False
  729. self._alpha = None
  730. self._tool_tolerance = None
  731. self._tooldia = None
  732. self._obj = None
  733. self._gcode_parsed = None
  734. if name is None:
  735. axes_name = self.obj.options['name']
  736. else:
  737. axes_name = name
  738. # Axes must exist and be attached to canvas.
  739. if axes_name not in self.app.plotcanvas.figure.axes:
  740. self.axes = self.app.plotcanvas.new_axes(axes_name)
  741. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  742. update=False, layer=1, tolerance=0.01, obj=None, gcode_parsed=None, tool_tolerance=None, tooldia=None,
  743. linewidth=None):
  744. """
  745. This function will add shapes to the shape collection
  746. :param shape: the Shapely shape to be added to the shape collection
  747. :param color: edge color of the shape, hex value
  748. :param face_color: the body color of the shape, hex value
  749. :param alpha: level of transparency of the shape [0.0 ... 1.0]; Float
  750. :param visible: if True will allow the shapes to be added
  751. :param update: not used; just for compatibility with VIsPy canvas
  752. :param layer: just for compatibility with VIsPy canvas
  753. :param tolerance: just for compatibility with VIsPy canvas
  754. :param obj: not used
  755. :param gcode_parsed: not used; just for compatibility with VIsPy canvas
  756. :param tool_tolerance: just for compatibility with VIsPy canvas
  757. :param tooldia:
  758. :param linewidth: the width of the line
  759. :return:
  760. """
  761. self._color = color if color is not None else "#006E20"
  762. self._face_color = face_color if face_color is not None else "#BBF268"
  763. if len(self._color) > 7:
  764. self._color = self._color[:7]
  765. if len(self._face_color) > 7:
  766. self._face_color = self._face_color[:7]
  767. # self._alpha = int(self._face_color[-2:], 16) / 255
  768. self._alpha = 0.75
  769. if alpha is not None:
  770. self._alpha = alpha
  771. self._visible = visible
  772. self._update = update
  773. # CNCJob object related arguments
  774. self._obj = obj
  775. self._gcode_parsed = gcode_parsed
  776. self._tool_tolerance = tool_tolerance
  777. self._tooldia = tooldia
  778. # if self._update:
  779. # self.clear()
  780. try:
  781. for sh in shape:
  782. self.shape_id += 1
  783. self.shape_dict.update({
  784. 'color': self._color,
  785. 'face_color': self._face_color,
  786. 'linewidth': linewidth,
  787. 'alpha': self._alpha,
  788. 'shape': sh
  789. })
  790. self._shapes.update({
  791. self.shape_id: deepcopy(self.shape_dict)
  792. })
  793. except TypeError:
  794. self.shape_id += 1
  795. self.shape_dict.update({
  796. 'color': self._color,
  797. 'face_color': self._face_color,
  798. 'linewidth': linewidth,
  799. 'alpha': self._alpha,
  800. 'shape': shape
  801. })
  802. self._shapes.update({
  803. self.shape_id: deepcopy(self.shape_dict)
  804. })
  805. return self.shape_id
  806. def remove(self, shape_id, update=None):
  807. for k in list(self._shapes.keys()):
  808. if shape_id == k:
  809. self._shapes.pop(k, None)
  810. if update is True:
  811. self.redraw()
  812. def clear(self, update=None):
  813. """
  814. Clear the canvas of the shapes.
  815. :param update:
  816. :return: None
  817. """
  818. self._shapes.clear()
  819. self.shape_id = 0
  820. self.axes.cla()
  821. try:
  822. self.app.plotcanvas.auto_adjust_axes()
  823. except Exception as e:
  824. log.debug("ShapeCollectionLegacy.clear() --> %s" % str(e))
  825. if update is True:
  826. self.redraw()
  827. def redraw(self, update_colors=None):
  828. """
  829. This draw the shapes in the shapes collection, on canvas
  830. :return: None
  831. """
  832. path_num = 0
  833. local_shapes = deepcopy(self._shapes)
  834. try:
  835. obj_type = self.obj.kind
  836. except AttributeError:
  837. obj_type = 'utility'
  838. if self._visible:
  839. # if we don't use this then when adding each new shape, the old ones will be added again, too
  840. if obj_type == 'utility':
  841. self.axes.patches.clear()
  842. for element in local_shapes:
  843. if obj_type == 'excellon':
  844. # Plot excellon (All polygons?)
  845. if self.obj.options["solid"] and isinstance(local_shapes[element]['shape'], Polygon):
  846. patch = PolygonPatch(local_shapes[element]['shape'],
  847. facecolor="#C40000",
  848. edgecolor="#750000",
  849. alpha=local_shapes[element]['alpha'],
  850. zorder=3)
  851. self.axes.add_patch(patch)
  852. else:
  853. x, y = local_shapes[element]['shape'].exterior.coords.xy
  854. self.axes.plot(x, y, 'r-')
  855. for ints in local_shapes[element]['shape'].interiors:
  856. x, y = ints.coords.xy
  857. self.axes.plot(x, y, 'o-')
  858. elif obj_type == 'geometry':
  859. if type(local_shapes[element]['shape']) == Polygon:
  860. x, y = local_shapes[element]['shape'].exterior.coords.xy
  861. self.axes.plot(x, y, local_shapes[element]['color'],
  862. linestyle='-',
  863. linewidth=local_shapes[element]['linewidth'])
  864. for ints in local_shapes[element]['shape'].interiors:
  865. x, y = ints.coords.xy
  866. self.axes.plot(x, y, local_shapes[element]['color'],
  867. linestyle='-',
  868. linewidth=local_shapes[element]['linewidth'])
  869. elif type(local_shapes[element]['shape']) == LineString or \
  870. type(local_shapes[element]['shape']) == LinearRing:
  871. x, y = local_shapes[element]['shape'].coords.xy
  872. self.axes.plot(x, y, local_shapes[element]['color'],
  873. linestyle='-',
  874. linewidth=local_shapes[element]['linewidth'])
  875. elif obj_type == 'gerber':
  876. if self.obj.options["multicolored"]:
  877. linespec = '-'
  878. else:
  879. linespec = 'k-'
  880. if self.obj.options["solid"]:
  881. if update_colors:
  882. gerber_fill_color = update_colors[0]
  883. gerber_outline_color = update_colors[1]
  884. else:
  885. gerber_fill_color = local_shapes[element]['face_color']
  886. gerber_outline_color = local_shapes[element]['color']
  887. try:
  888. patch = PolygonPatch(local_shapes[element]['shape'],
  889. facecolor=gerber_fill_color,
  890. edgecolor=gerber_outline_color,
  891. alpha=local_shapes[element]['alpha'],
  892. zorder=2)
  893. self.axes.add_patch(patch)
  894. except AssertionError:
  895. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  896. FlatCAMApp.App.log.warning(str(element))
  897. except Exception as e:
  898. FlatCAMApp.App.log.debug("PlotCanvasLegacy.ShepeCollectionLegacy.redraw() --> %s" % str(e))
  899. else:
  900. x, y = local_shapes[element]['shape'].exterior.xy
  901. self.axes.plot(x, y, linespec)
  902. for ints in local_shapes[element]['shape'].interiors:
  903. x, y = ints.coords.xy
  904. self.axes.plot(x, y, linespec)
  905. elif obj_type == 'cncjob':
  906. if local_shapes[element]['face_color'] is None:
  907. linespec = '--'
  908. linecolor = local_shapes[element]['color']
  909. # if geo['kind'][0] == 'C':
  910. # linespec = 'k-'
  911. x, y = local_shapes[element]['shape'].coords.xy
  912. self.axes.plot(x, y, linespec, color=linecolor)
  913. else:
  914. path_num += 1
  915. if self.obj.ui.annotation_cb.get_value():
  916. if isinstance(local_shapes[element]['shape'], Polygon):
  917. self.axes.annotate(
  918. str(path_num),
  919. xy=local_shapes[element]['shape'].exterior.coords[0],
  920. xycoords='data', fontsize=20)
  921. else:
  922. self.axes.annotate(
  923. str(path_num),
  924. xy=local_shapes[element]['shape'].coords[0],
  925. xycoords='data', fontsize=20)
  926. patch = PolygonPatch(local_shapes[element]['shape'],
  927. facecolor=local_shapes[element]['face_color'],
  928. edgecolor=local_shapes[element]['color'],
  929. alpha=local_shapes[element]['alpha'], zorder=2)
  930. self.axes.add_patch(patch)
  931. elif obj_type == 'utility':
  932. # not a FlatCAM object, must be utility
  933. if local_shapes[element]['face_color']:
  934. try:
  935. patch = PolygonPatch(local_shapes[element]['shape'],
  936. facecolor=local_shapes[element]['face_color'],
  937. edgecolor=local_shapes[element]['color'],
  938. alpha=local_shapes[element]['alpha'],
  939. zorder=2)
  940. self.axes.add_patch(patch)
  941. except Exception as e:
  942. log.debug("ShapeCollectionLegacy.redraw() --> %s" % str(e))
  943. else:
  944. if isinstance(local_shapes[element]['shape'], Polygon):
  945. ext_shape = local_shapes[element]['shape'].exterior
  946. if ext_shape is not None:
  947. x, y = ext_shape.xy
  948. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  949. for ints in local_shapes[element]['shape'].interiors:
  950. if ints is not None:
  951. x, y = ints.coords.xy
  952. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  953. else:
  954. if local_shapes[element]['shape'] is not None:
  955. x, y = local_shapes[element]['shape'].coords.xy
  956. self.axes.plot(x, y, local_shapes[element]['color'], linestyle='-')
  957. self.app.plotcanvas.auto_adjust_axes()
  958. def set(self, text, pos, visible=True, font_size=16, color=None):
  959. """
  960. This will set annotations on the canvas.
  961. :param text: a list of text elements to be used as annotations
  962. :param pos: a list of positions for showing the text elements above
  963. :param visible: if True will display annotations, if False will clear them on canvas
  964. :param font_size: the font size or the annotations
  965. :param color: color of the annotations
  966. :return: None
  967. """
  968. if color is None:
  969. color = "#000000FF"
  970. if visible is not True:
  971. self.clear()
  972. return
  973. if len(text) != len(pos):
  974. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not annotate due of a difference between the number "
  975. "of text elements and the number of text positions."))
  976. return
  977. for idx in range(len(text)):
  978. try:
  979. self.axes.annotate(text[idx], xy=pos[idx], xycoords='data', fontsize=font_size, color=color)
  980. except Exception as e:
  981. log.debug("ShapeCollectionLegacy.set() --> %s" % str(e))
  982. self.app.plotcanvas.auto_adjust_axes()
  983. @property
  984. def visible(self):
  985. return self._visible
  986. @visible.setter
  987. def visible(self, value):
  988. if value is False:
  989. self.axes.cla()
  990. self.app.plotcanvas.auto_adjust_axes()
  991. else:
  992. if self._visible is False:
  993. self.redraw()
  994. self._visible = value
  995. @property
  996. def enabled(self):
  997. return self._visible
  998. @enabled.setter
  999. def enabled(self, value):
  1000. if value is False:
  1001. self.axes.cla()
  1002. self.app.plotcanvas.auto_adjust_axes()
  1003. else:
  1004. if self._visible is False:
  1005. self.redraw()
  1006. self._visible = value
  1007. # class MplCursor(Cursor):
  1008. # """
  1009. # Unfortunately this gets attached to the current axes and if a new axes is added
  1010. # it will not be showed until that axes is deleted.
  1011. # Not the kind of behavior needed here so I don't use it anymore.
  1012. # """
  1013. # def __init__(self, axes, color='red', linewidth=1):
  1014. #
  1015. # super().__init__(ax=axes, useblit=True, color=color, linewidth=linewidth)
  1016. # self._enabled = True
  1017. #
  1018. # self.axes = axes
  1019. # self.color = color
  1020. # self.linewidth = linewidth
  1021. #
  1022. # self.x = None
  1023. # self.y = None
  1024. #
  1025. # @property
  1026. # def enabled(self):
  1027. # return True if self._enabled else False
  1028. #
  1029. # @enabled.setter
  1030. # def enabled(self, value):
  1031. # self._enabled = value
  1032. # self.visible = self._enabled
  1033. # self.canvas.draw()
  1034. #
  1035. # def onmove(self, event):
  1036. # pass
  1037. #
  1038. # def set_data(self, event, pos):
  1039. # """Internal event handler to draw the cursor when the mouse moves."""
  1040. # self.x = pos[0]
  1041. # self.y = pos[1]
  1042. #
  1043. # if self.ignore(event):
  1044. # return
  1045. # if not self.canvas.widgetlock.available(self):
  1046. # return
  1047. # if event.inaxes != self.ax:
  1048. # self.linev.set_visible(False)
  1049. # self.lineh.set_visible(False)
  1050. #
  1051. # if self.needclear:
  1052. # self.canvas.draw()
  1053. # self.needclear = False
  1054. # return
  1055. # self.needclear = True
  1056. # if not self.visible:
  1057. # return
  1058. # self.linev.set_xdata((self.x, self.x))
  1059. #
  1060. # self.lineh.set_ydata((self.y, self.y))
  1061. # self.linev.set_visible(self.visible and self.vertOn)
  1062. # self.lineh.set_visible(self.visible and self.horizOn)
  1063. #
  1064. # self._update()