PlotCanvas.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # Author: Dennis Hayrullin (c) #
  4. # Date: 2016 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtCore
  8. import logging
  9. from flatcamGUI.VisPyCanvas import VisPyCanvas, Color
  10. from flatcamGUI.VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor
  11. from vispy.scene.visuals import InfiniteLine, Line
  12. import numpy as np
  13. from vispy.geometry import Rect
  14. log = logging.getLogger('base')
  15. class PlotCanvas(QtCore.QObject, VisPyCanvas):
  16. """
  17. Class handling the plotting area in the application.
  18. """
  19. def __init__(self, container, fcapp):
  20. """
  21. The constructor configures the VisPy figure that
  22. will contain all plots, creates the base axes and connects
  23. events to the plotting area.
  24. :param container: The parent container in which to draw plots.
  25. :rtype: PlotCanvas
  26. """
  27. # super(PlotCanvas, self).__init__()
  28. # QtCore.QObject.__init__(self)
  29. # VisPyCanvas.__init__(self)
  30. super().__init__()
  31. # VisPyCanvas does not allow new attributes. Override.
  32. self.unfreeze()
  33. self.fcapp = fcapp
  34. # Parent container
  35. self.container = container
  36. settings = QtCore.QSettings("Open Source", "FlatCAM")
  37. if settings.contains("theme"):
  38. theme = settings.value('theme', type=str)
  39. else:
  40. theme = 'white'
  41. if theme == 'white':
  42. self.line_color = (0.3, 0.0, 0.0, 1.0)
  43. else:
  44. self.line_color = (0.4, 0.4, 0.4, 1.0)
  45. # workspace lines; I didn't use the rectangle because I didn't want to add another VisPy Node,
  46. # which might decrease performance
  47. # self.b_line, self.r_line, self.t_line, self.l_line = None, None, None, None
  48. self.workspace_line = None
  49. self.pagesize_dict = {}
  50. self.pagesize_dict.update(
  51. {
  52. 'A0': (841, 1189),
  53. 'A1': (594, 841),
  54. 'A2': (420, 594),
  55. 'A3': (297, 420),
  56. 'A4': (210, 297),
  57. 'A5': (148, 210),
  58. 'A6': (105, 148),
  59. 'A7': (74, 105),
  60. 'A8': (52, 74),
  61. 'A9': (37, 52),
  62. 'A10': (26, 37),
  63. 'B0': (1000, 1414),
  64. 'B1': (707, 1000),
  65. 'B2': (500, 707),
  66. 'B3': (353, 500),
  67. 'B4': (250, 353),
  68. 'B5': (176, 250),
  69. 'B6': (125, 176),
  70. 'B7': (88, 125),
  71. 'B8': (62, 88),
  72. 'B9': (44, 62),
  73. 'B10': (31, 44),
  74. 'C0': (917, 1297),
  75. 'C1': (648, 917),
  76. 'C2': (458, 648),
  77. 'C3': (324, 458),
  78. 'C4': (229, 324),
  79. 'C5': (162, 229),
  80. 'C6': (114, 162),
  81. 'C7': (81, 114),
  82. 'C8': (57, 81),
  83. 'C9': (40, 57),
  84. 'C10': (28, 40),
  85. # American paper sizes
  86. 'LETTER': (8.5*25.4, 11*25.4),
  87. 'LEGAL': (8.5*25.4, 14*25.4),
  88. 'ELEVENSEVENTEEN': (11*25.4, 17*25.4),
  89. # From https://en.wikipedia.org/wiki/Paper_size
  90. 'JUNIOR_LEGAL': (5*25.4, 8*25.4),
  91. 'HALF_LETTER': (5.5*25.4, 8*25.4),
  92. 'GOV_LETTER': (8*25.4, 10.5*25.4),
  93. 'GOV_LEGAL': (8.5*25.4, 13*25.4),
  94. 'LEDGER': (17*25.4, 11*25.4),
  95. }
  96. )
  97. # <VisPyCanvas>
  98. self.create_native()
  99. self.native.setParent(self.fcapp.ui)
  100. # <QtCore.QObject>
  101. self.container.addWidget(self.native)
  102. # ## AXIS # ##
  103. self.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 0.8), vertical=True,
  104. parent=self.view.scene)
  105. self.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 0.8), vertical=False,
  106. parent=self.view.scene)
  107. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  108. # all CNC have a limited workspace
  109. if self.fcapp.defaults['global_workspace'] is True:
  110. self.draw_workspace(workspace_size=self.fcapp.defaults["global_workspaceT"])
  111. self.line_parent = None
  112. if self.fcapp.defaults["global_cursor_color_enabled"]:
  113. c_color = Color(self.fcapp.defaults["global_cursor_color"]).rgba
  114. else:
  115. c_color = self.line_color
  116. self.cursor_v_line = InfiniteLine(pos=None, color=c_color, vertical=True,
  117. parent=self.line_parent)
  118. self.cursor_h_line = InfiniteLine(pos=None, color=c_color, vertical=False,
  119. parent=self.line_parent)
  120. self.shape_collections = []
  121. self.shape_collection = self.new_shape_collection()
  122. self.fcapp.pool_recreated.connect(self.on_pool_recreated)
  123. self.text_collection = self.new_text_collection()
  124. # TODO: Should be setting to show/hide CNC job annotations (global or per object)
  125. self.text_collection.enabled = True
  126. self.c = None
  127. self.big_cursor = None
  128. # Keep VisPy canvas happy by letting it be "frozen" again.
  129. self.freeze()
  130. self.fit_view()
  131. self.graph_event_connect('mouse_wheel', self.on_mouse_scroll)
  132. def draw_workspace(self, workspace_size):
  133. """
  134. Draw a rectangular shape on canvas to specify our valid workspace.
  135. :param workspace_size: the workspace size; tuple
  136. :return:
  137. """
  138. try:
  139. if self.fcapp.defaults['units'].upper() == 'MM':
  140. dims = self.pagesize_dict[workspace_size]
  141. else:
  142. dims = (self.pagesize_dict[workspace_size][0]/25.4, self.pagesize_dict[workspace_size][1]/25.4)
  143. except Exception as e:
  144. log.debug("PlotCanvas.draw_workspace() --> %s" % str(e))
  145. return
  146. if self.fcapp.defaults['global_workspace_orientation'] == 'l':
  147. dims = (dims[1], dims[0])
  148. a = np.array([(0, 0), (dims[0], 0), (dims[0], dims[1]), (0, dims[1])])
  149. if not self.workspace_line:
  150. self.workspace_line = Line(pos=np.array((a[0], a[1], a[2], a[3], a[0])), color=(0.70, 0.3, 0.3, 0.7),
  151. antialias=True, method='agg', parent=self.view.scene)
  152. else:
  153. self.workspace_line.parent = self.view.scene
  154. def delete_workspace(self):
  155. try:
  156. self.workspace_line.parent = None
  157. except Exception:
  158. pass
  159. # redraw the workspace lines on the plot by re adding them to the parent view.scene
  160. def restore_workspace(self):
  161. try:
  162. self.workspace_line.parent = self.view.scene
  163. except Exception:
  164. pass
  165. def graph_event_connect(self, event_name, callback):
  166. return getattr(self.events, event_name).connect(callback)
  167. def graph_event_disconnect(self, event_name, callback=None):
  168. if callback is None:
  169. getattr(self.events, event_name).disconnect()
  170. else:
  171. getattr(self.events, event_name).disconnect(callback)
  172. def zoom(self, factor, center=None):
  173. """
  174. Zooms the plot by factor around a given
  175. center point. Takes care of re-drawing.
  176. :param factor: Number by which to scale the plot.
  177. :type factor: float
  178. :param center: Coordinates [x, y] of the point around which to scale the plot.
  179. :type center: list
  180. :return: None
  181. """
  182. self.view.camera.zoom(factor, center)
  183. def new_shape_group(self, shape_collection=None):
  184. if shape_collection:
  185. return ShapeGroup(shape_collection)
  186. return ShapeGroup(self.shape_collection)
  187. def new_shape_collection(self, **kwargs):
  188. # sc = ShapeCollection(parent=self.view.scene, pool=self.app.pool, **kwargs)
  189. # self.shape_collections.append(sc)
  190. # return sc
  191. return ShapeCollection(parent=self.view.scene, pool=self.fcapp.pool, **kwargs)
  192. def new_cursor(self, big=None):
  193. """
  194. Will create a mouse cursor pointer on canvas
  195. :param big: if True will create a mouse cursor made out of infinite lines
  196. :return: the mouse cursor object
  197. """
  198. if big is True:
  199. self.big_cursor = True
  200. self.c = CursorBig(app=self.fcapp)
  201. # in case there are multiple new_cursor calls, best to disconnect first the signals
  202. try:
  203. self.c.mouse_state_updated.disconnect(self.on_mouse_state)
  204. except (TypeError, AttributeError):
  205. pass
  206. try:
  207. self.c.mouse_position_updated.disconnect(self.on_mouse_position)
  208. except (TypeError, AttributeError):
  209. pass
  210. self.c.mouse_state_updated.connect(self.on_mouse_state)
  211. self.c.mouse_position_updated.connect(self.on_mouse_position)
  212. else:
  213. self.big_cursor = False
  214. self.c = Cursor(pos=np.empty((0, 2)), parent=self.view.scene)
  215. self.c.antialias = 0
  216. return self.c
  217. def on_mouse_state(self, state):
  218. if state:
  219. self.cursor_h_line.parent = self.view.scene
  220. self.cursor_v_line.parent = self.view.scene
  221. else:
  222. self.cursor_h_line.parent = None
  223. self.cursor_v_line.parent = None
  224. def on_mouse_position(self, pos):
  225. if self.fcapp.defaults['global_cursor_color_enabled']:
  226. color = Color(self.fcapp.defaults['global_cursor_color']).rgba
  227. else:
  228. color = self.line_color
  229. self.cursor_h_line.set_data(pos=pos[1], color=color)
  230. self.cursor_v_line.set_data(pos=pos[0], color=color)
  231. self.view.scene.update()
  232. def on_mouse_scroll(self, event):
  233. # key modifiers
  234. modifiers = event.modifiers
  235. pan_delta_x = self.fcapp.defaults["global_gridx"]
  236. pan_delta_y = self.fcapp.defaults["global_gridy"]
  237. curr_pos = event.pos
  238. # Controlled pan by mouse wheel
  239. if 'Shift' in modifiers:
  240. p1 = np.array(curr_pos)[:2]
  241. if event.delta[1] > 0:
  242. curr_pos[0] -= pan_delta_x
  243. else:
  244. curr_pos[0] += pan_delta_x
  245. p2 = np.array(curr_pos)[:2]
  246. self.view.camera.pan(p2 - p1)
  247. elif 'Control' in modifiers:
  248. p1 = np.array(curr_pos)[:2]
  249. if event.delta[1] > 0:
  250. curr_pos[1] += pan_delta_y
  251. else:
  252. curr_pos[1] -= pan_delta_y
  253. p2 = np.array(curr_pos)[:2]
  254. self.view.camera.pan(p2 - p1)
  255. if self.fcapp.grid_status():
  256. pos_canvas = self.translate_coords(curr_pos)
  257. pos = self.fcapp.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  258. # Update cursor
  259. self.fcapp.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  260. symbol='++', edge_color=self.fcapp.cursor_color_3D,
  261. edge_width=self.fcapp.defaults["global_cursor_width"],
  262. size=self.fcapp.defaults["global_cursor_size"])
  263. def new_text_group(self, collection=None):
  264. if collection:
  265. return TextGroup(collection)
  266. else:
  267. return TextGroup(self.text_collection)
  268. def new_text_collection(self, **kwargs):
  269. return TextCollection(parent=self.view.scene, **kwargs)
  270. def fit_view(self, rect=None):
  271. # Lock updates in other threads
  272. self.shape_collection.lock_updates()
  273. if not rect:
  274. rect = Rect(-1, -1, 20, 20)
  275. try:
  276. rect.left, rect.right = self.shape_collection.bounds(axis=0)
  277. rect.bottom, rect.top = self.shape_collection.bounds(axis=1)
  278. except TypeError:
  279. pass
  280. # adjust the view camera to be slightly bigger than the bounds so the shape collection can be seen clearly
  281. # otherwise the shape collection boundary will have no border
  282. dx = rect.right - rect.left
  283. dy = rect.top - rect.bottom
  284. x_factor = dx * 0.02
  285. y_factor = dy * 0.02
  286. rect.left -= x_factor
  287. rect.bottom -= y_factor
  288. rect.right += x_factor
  289. rect.top += y_factor
  290. # rect.left *= 0.96
  291. # rect.bottom *= 0.96
  292. # rect.right *= 1.04
  293. # rect.top *= 1.04
  294. # units = self.fcapp.defaults['units'].upper()
  295. # if units == 'MM':
  296. # compensation = 0.5
  297. # else:
  298. # compensation = 0.5 / 25.4
  299. # rect.left -= compensation
  300. # rect.bottom -= compensation
  301. # rect.right += compensation
  302. # rect.top += compensation
  303. self.view.camera.rect = rect
  304. self.shape_collection.unlock_updates()
  305. def fit_center(self, loc, rect=None):
  306. # Lock updates in other threads
  307. self.shape_collection.lock_updates()
  308. if not rect:
  309. try:
  310. rect = Rect(loc[0]-20, loc[1]-20, 40, 40)
  311. except TypeError:
  312. pass
  313. self.view.camera.rect = rect
  314. self.shape_collection.unlock_updates()
  315. def clear(self):
  316. pass
  317. def redraw(self):
  318. self.shape_collection.redraw([])
  319. self.text_collection.redraw()
  320. def on_pool_recreated(self, pool):
  321. self.shape_collection.pool = pool
  322. class CursorBig(QtCore.QObject):
  323. """
  324. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  325. This way I don't have to chane (disable) things related to the cursor all over when
  326. using the low performance Matplotlib 2D graphic engine.
  327. """
  328. mouse_state_updated = QtCore.pyqtSignal(bool)
  329. mouse_position_updated = QtCore.pyqtSignal(list)
  330. def __init__(self, app):
  331. super().__init__()
  332. self.app = app
  333. self._enabled = None
  334. @property
  335. def enabled(self):
  336. return True if self._enabled else False
  337. @enabled.setter
  338. def enabled(self, value):
  339. self._enabled = value
  340. self.mouse_state_updated.emit(value)
  341. def set_data(self, pos, **kwargs):
  342. """Internal event handler to draw the cursor when the mouse moves."""
  343. if 'edge_color' in kwargs:
  344. color = kwargs['edge_color']
  345. else:
  346. if self.app.defaults['global_theme'] == 'white':
  347. color = '#000000FF'
  348. else:
  349. color = '#FFFFFFFF'
  350. position = [pos[0][0], pos[0][1]]
  351. self.mouse_position_updated.emit(position)