PlotCanvasLegacy.py 40 KB

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