PlotCanvas.py 14 KB

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