PlotCanvas.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. # ########################################################## ##
  8. from PyQt5 import QtCore
  9. import logging
  10. from flatcamGUI.VisPyCanvas import VisPyCanvas, time, Color
  11. from flatcamGUI.VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor
  12. from vispy.scene.visuals import InfiniteLine, Line
  13. import numpy as np
  14. from vispy.geometry import Rect
  15. log = logging.getLogger('base')
  16. class PlotCanvas(QtCore.QObject, VisPyCanvas):
  17. """
  18. Class handling the plotting area in the application.
  19. """
  20. def __init__(self, container, fcapp):
  21. """
  22. The constructor configures the VisPy figure that
  23. will contain all plots, creates the base axes and connects
  24. events to the plotting area.
  25. :param container: The parent container in which to draw plots.
  26. :rtype: PlotCanvas
  27. """
  28. super(PlotCanvas, self).__init__()
  29. # VisPyCanvas.__init__(self)
  30. # VisPyCanvas does not allow new attributes. Override.
  31. self.unfreeze()
  32. self.fcapp = fcapp
  33. # Parent container
  34. self.container = container
  35. settings = QtCore.QSettings("Open Source", "FlatCAM")
  36. if settings.contains("theme"):
  37. theme = settings.value('theme', type=str)
  38. else:
  39. theme = 'white'
  40. if theme == 'white':
  41. self.line_color = (0.3, 0.0, 0.0, 1.0)
  42. else:
  43. self.line_color = (0.4, 0.4, 0.4, 1.0)
  44. # workspace lines; I didn't use the rectangle because I didn't want to add another VisPy Node,
  45. # which might decrease performance
  46. self.b_line, self.r_line, self.t_line, self.l_line = None, None, None, None
  47. # <VisPyCanvas>
  48. self.create_native()
  49. self.native.setParent(self.fcapp.ui)
  50. # <QtCore.QObject>
  51. self.container.addWidget(self.native)
  52. # ## AXIS # ##
  53. self.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  54. parent=self.view.scene)
  55. self.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  56. parent=self.view.scene)
  57. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  58. # all CNC have a limited workspace
  59. self.draw_workspace()
  60. self.line_parent = None
  61. self.cursor_v_line = InfiniteLine(pos=None, color=self.line_color, vertical=True,
  62. parent=self.line_parent)
  63. self.cursor_h_line = InfiniteLine(pos=None, color=self.line_color, vertical=False,
  64. parent=self.line_parent)
  65. # if self.app.defaults['global_workspace'] is True:
  66. # if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  67. # self.wkspace_t = Line(pos=)
  68. self.shape_collections = []
  69. self.shape_collection = self.new_shape_collection()
  70. self.fcapp.pool_recreated.connect(self.on_pool_recreated)
  71. self.text_collection = self.new_text_collection()
  72. # TODO: Should be setting to show/hide CNC job annotations (global or per object)
  73. self.text_collection.enabled = True
  74. self.c = None
  75. self.big_cursor = None
  76. # Keep VisPy canvas happy by letting it be "frozen" again.
  77. self.freeze()
  78. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  79. # all CNC have a limited workspace
  80. def draw_workspace(self):
  81. a = np.empty((0, 0))
  82. a4p_in = np.array([(0, 0), (8.3, 0), (8.3, 11.7), (0, 11.7)])
  83. a4l_in = np.array([(0, 0), (11.7, 0), (11.7, 8.3), (0, 8.3)])
  84. a3p_in = np.array([(0, 0), (11.7, 0), (11.7, 16.5), (0, 16.5)])
  85. a3l_in = np.array([(0, 0), (16.5, 0), (16.5, 11.7), (0, 11.7)])
  86. a4p_mm = np.array([(0, 0), (210, 0), (210, 297), (0, 297)])
  87. a4l_mm = np.array([(0, 0), (297, 0), (297, 210), (0, 210)])
  88. a3p_mm = np.array([(0, 0), (297, 0), (297, 420), (0, 420)])
  89. a3l_mm = np.array([(0, 0), (420, 0), (420, 297), (0, 297)])
  90. if self.fcapp.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  91. if self.fcapp.defaults['global_workspaceT'] == 'A4P':
  92. a = a4p_mm
  93. elif self.fcapp.defaults['global_workspaceT'] == 'A4L':
  94. a = a4l_mm
  95. elif self.fcapp.defaults['global_workspaceT'] == 'A3P':
  96. a = a3p_mm
  97. elif self.fcapp.defaults['global_workspaceT'] == 'A3L':
  98. a = a3l_mm
  99. else:
  100. if self.fcapp.defaults['global_workspaceT'] == 'A4P':
  101. a = a4p_in
  102. elif self.fcapp.defaults['global_workspaceT'] == 'A4L':
  103. a = a4l_in
  104. elif self.fcapp.defaults['global_workspaceT'] == 'A3P':
  105. a = a3p_in
  106. elif self.fcapp.defaults['global_workspaceT'] == 'A3L':
  107. a = a3l_in
  108. self.delete_workspace()
  109. self.b_line = Line(pos=a[0:2], color=(0.70, 0.3, 0.3, 1.0),
  110. antialias=True, method='agg', parent=self.view.scene)
  111. self.r_line = Line(pos=a[1:3], color=(0.70, 0.3, 0.3, 1.0),
  112. antialias=True, method='agg', parent=self.view.scene)
  113. self.t_line = Line(pos=a[2:4], color=(0.70, 0.3, 0.3, 1.0),
  114. antialias=True, method='agg', parent=self.view.scene)
  115. self.l_line = Line(pos=np.array((a[0], a[3])), color=(0.70, 0.3, 0.3, 1.0),
  116. antialias=True, method='agg', parent=self.view.scene)
  117. if self.fcapp.defaults['global_workspace'] is False:
  118. self.delete_workspace()
  119. # delete the workspace lines from the plot by removing the parent
  120. def delete_workspace(self):
  121. try:
  122. self.b_line.parent = None
  123. self.r_line.parent = None
  124. self.t_line.parent = None
  125. self.l_line.parent = None
  126. except Exception as e:
  127. pass
  128. # redraw the workspace lines on the plot by readding them to the parent view.scene
  129. def restore_workspace(self):
  130. try:
  131. self.b_line.parent = self.view.scene
  132. self.r_line.parent = self.view.scene
  133. self.t_line.parent = self.view.scene
  134. self.l_line.parent = self.view.scene
  135. except Exception as e:
  136. pass
  137. def graph_event_connect(self, event_name, callback):
  138. return getattr(self.events, event_name).connect(callback)
  139. def graph_event_disconnect(self, event_name, callback=None):
  140. if callback is None:
  141. getattr(self.events, event_name).disconnect()
  142. else:
  143. getattr(self.events, event_name).disconnect(callback)
  144. def zoom(self, factor, center=None):
  145. """
  146. Zooms the plot by factor around a given
  147. center point. Takes care of re-drawing.
  148. :param factor: Number by which to scale the plot.
  149. :type factor: float
  150. :param center: Coordinates [x, y] of the point around which to scale the plot.
  151. :type center: list
  152. :return: None
  153. """
  154. self.view.camera.zoom(factor, center)
  155. def new_shape_group(self, shape_collection=None):
  156. if shape_collection:
  157. return ShapeGroup(shape_collection)
  158. return ShapeGroup(self.shape_collection)
  159. def new_shape_collection(self, **kwargs):
  160. # sc = ShapeCollection(parent=self.view.scene, pool=self.app.pool, **kwargs)
  161. # self.shape_collections.append(sc)
  162. # return sc
  163. return ShapeCollection(parent=self.view.scene, pool=self.fcapp.pool, **kwargs)
  164. def new_cursor(self, big=None):
  165. """
  166. Will create a mouse cursor pointer on canvas
  167. :param big: if True will create a mouse cursor made out of infinite lines
  168. :return: the mouse cursor object
  169. """
  170. if big is True:
  171. self.big_cursor = True
  172. self.c = CursorBig()
  173. # in case there are multiple new_cursor calls, best to disconnect first the signals
  174. try:
  175. self.c.mouse_state_updated.disconnect(self.on_mouse_state)
  176. except (TypeError, AttributeError):
  177. pass
  178. try:
  179. self.c.mouse_position_updated.disconnect(self.on_mouse_position)
  180. except (TypeError, AttributeError):
  181. pass
  182. self.c.mouse_state_updated.connect(self.on_mouse_state)
  183. self.c.mouse_position_updated.connect(self.on_mouse_position)
  184. else:
  185. self.big_cursor = False
  186. self.c = Cursor(pos=np.empty((0, 2)), parent=self.view.scene)
  187. self.c.antialias = 0
  188. return self.c
  189. def on_mouse_state(self, state):
  190. if state:
  191. self.cursor_h_line.parent = self.view.scene
  192. self.cursor_v_line.parent = self.view.scene
  193. else:
  194. self.cursor_h_line.parent = None
  195. self.cursor_v_line.parent = None
  196. def on_mouse_position(self, pos):
  197. # self.line_color = color
  198. self.cursor_h_line.set_data(pos=pos[1], color=self.line_color)
  199. self.cursor_v_line.set_data(pos=pos[0], color=self.line_color)
  200. self.view.scene.update()
  201. def new_text_group(self, collection=None):
  202. if collection:
  203. return TextGroup(collection)
  204. else:
  205. return TextGroup(self.text_collection)
  206. def new_text_collection(self, **kwargs):
  207. return TextCollection(parent=self.view.scene, **kwargs)
  208. def fit_view(self, rect=None):
  209. # Lock updates in other threads
  210. self.shape_collection.lock_updates()
  211. if not rect:
  212. rect = Rect(-1, -1, 20, 20)
  213. try:
  214. rect.left, rect.right = self.shape_collection.bounds(axis=0)
  215. rect.bottom, rect.top = self.shape_collection.bounds(axis=1)
  216. except TypeError:
  217. pass
  218. # adjust the view camera to be slightly bigger than the bounds so the shape colleaction can be seen clearly
  219. # otherwise the shape collection boundary will have no border
  220. rect.left *= 0.96
  221. rect.bottom *= 0.96
  222. rect.right *= 1.01
  223. rect.top *= 1.01
  224. self.view.camera.rect = rect
  225. self.shape_collection.unlock_updates()
  226. def fit_center(self, loc, rect=None):
  227. # Lock updates in other threads
  228. self.shape_collection.lock_updates()
  229. if not rect:
  230. try:
  231. rect = Rect(loc[0]-20, loc[1]-20, 40, 40)
  232. except TypeError:
  233. pass
  234. self.view.camera.rect = rect
  235. self.shape_collection.unlock_updates()
  236. def clear(self):
  237. pass
  238. def redraw(self):
  239. self.shape_collection.redraw([])
  240. self.text_collection.redraw()
  241. def on_pool_recreated(self, pool):
  242. self.shape_collection.pool = pool
  243. class CursorBig(QtCore.QObject):
  244. """
  245. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  246. This way I don't have to chane (disable) things related to the cursor all over when
  247. using the low performance Matplotlib 2D graphic engine.
  248. """
  249. mouse_state_updated = QtCore.pyqtSignal(bool)
  250. mouse_position_updated = QtCore.pyqtSignal(list)
  251. def __init__(self):
  252. super().__init__()
  253. self._enabled = None
  254. @property
  255. def enabled(self):
  256. return True if self._enabled else False
  257. @enabled.setter
  258. def enabled(self, value):
  259. self._enabled = value
  260. self.mouse_state_updated.emit(value)
  261. def set_data(self, pos, **kwargs):
  262. """Internal event handler to draw the cursor when the mouse moves."""
  263. if 'edge_color' in kwargs:
  264. color = kwargs['edge_color']
  265. else:
  266. if self.app.defaults['global_theme'] == 'white':
  267. color = '#000000FF'
  268. else:
  269. color = '#FFFFFFFF'
  270. position = [pos[0][0], pos[0][1]]
  271. self.mouse_position_updated.emit(position)