FlatCAMCommon.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File Modified (major mod): Marius Adrian Stanciu #
  10. # Date: 11/4/2019 #
  11. # ##########################################################
  12. from shapely.geometry import Polygon, MultiPolygon
  13. from flatcamGUI.VisPyVisuals import ShapeCollection
  14. from FlatCAMTool import FlatCAMTool
  15. import numpy as np
  16. import re
  17. import gettext
  18. import FlatCAMTranslation as fcTranslate
  19. import builtins
  20. fcTranslate.apply_language('strings')
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. class GracefulException(Exception):
  24. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  25. def __init__(self):
  26. super().__init__()
  27. def __str__(self):
  28. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  29. class LoudDict(dict):
  30. """
  31. A Dictionary with a callback for item changes.
  32. """
  33. def __init__(self, *args, **kwargs):
  34. dict.__init__(self, *args, **kwargs)
  35. self.callback = lambda x: None
  36. def __setitem__(self, key, value):
  37. """
  38. Overridden __setitem__ method. Will emit 'changed(QString)' if the item was changed, with key as parameter.
  39. """
  40. if key in self and self.__getitem__(key) == value:
  41. return
  42. dict.__setitem__(self, key, value)
  43. self.callback(key)
  44. def update(self, *args, **kwargs):
  45. if len(args) > 1:
  46. raise TypeError("update expected at most 1 arguments, got %d" % len(args))
  47. other = dict(*args, **kwargs)
  48. for key in other:
  49. self[key] = other[key]
  50. def set_change_callback(self, callback):
  51. """
  52. Assigns a function as callback on item change. The callback
  53. will receive the key of the object that was changed.
  54. :param callback: Function to call on item change.
  55. :type callback: func
  56. :return: None
  57. """
  58. self.callback = callback
  59. class FCSignal:
  60. """
  61. Taken from here: https://blog.abstractfactory.io/dynamic-signals-in-pyqt/
  62. """
  63. def __init__(self):
  64. self.__subscribers = []
  65. def emit(self, *args, **kwargs):
  66. for subs in self.__subscribers:
  67. subs(*args, **kwargs)
  68. def connect(self, func):
  69. self.__subscribers.append(func)
  70. def disconnect(self, func):
  71. try:
  72. self.__subscribers.remove(func)
  73. except ValueError:
  74. print('Warning: function %s not removed '
  75. 'from signal %s' % (func, self))
  76. def color_variant(hex_color, bright_factor=1):
  77. """
  78. Takes a color in HEX format #FF00FF and produces a lighter or darker variant
  79. :param hex_color: color to change
  80. :param bright_factor: factor to change the color brightness [0 ... 1]
  81. :return: modified color
  82. """
  83. if len(hex_color) != 7:
  84. print("Color is %s, but needs to be in #FF00FF format. Returning original color." % hex_color)
  85. return hex_color
  86. if bright_factor > 1.0:
  87. bright_factor = 1.0
  88. if bright_factor < 0.0:
  89. bright_factor = 0.0
  90. rgb_hex = [hex_color[x:x + 2] for x in [1, 3, 5]]
  91. new_rgb = []
  92. for hex_value in rgb_hex:
  93. # adjust each color channel and turn it into a INT suitable as argument for hex()
  94. mod_color = round(int(hex_value, 16) * bright_factor)
  95. # make sure that each color channel has two digits without the 0x prefix
  96. mod_color_hex = str(hex(mod_color)[2:]).zfill(2)
  97. new_rgb.append(mod_color_hex)
  98. return "#" + "".join([i for i in new_rgb])
  99. class ExclusionAreas:
  100. def __init__(self, app):
  101. self.app = app
  102. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  103. # VisPy visuals
  104. if self.app.is_legacy is False:
  105. try:
  106. self.exclusion_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1)
  107. except AttributeError:
  108. self.exclusion_shapes = None
  109. else:
  110. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  111. self.exclusion_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name="exclusion")
  112. # Event signals disconnect id holders
  113. self.mr = None
  114. self.mm = None
  115. self.kp = None
  116. # variables to be used in area exclusion
  117. self.cursor_pos = (0, 0)
  118. self.first_click = False
  119. self.points = []
  120. self.poly_drawn = False
  121. '''
  122. Here we store the exclusion shapes and some other information's
  123. Each list element is a dictionary with the format:
  124. {
  125. "obj_type": string ("excellon" or "geometry") <- self.obj_type
  126. "shape": Shapely polygon
  127. "strategy": string ("over" or "around") <- self.strategy
  128. "overz": float <- self.over_z
  129. }
  130. '''
  131. self.exclusion_areas_storage = []
  132. self.mouse_is_dragging = False
  133. self.solid_geometry = []
  134. self.obj_type = None
  135. self.shape_type = 'square' # TODO use the self.app.defaults when made general (not in Geo object Pref UI)
  136. self.over_z = 0.1
  137. self.strategy = None
  138. self.cnc_button = None
  139. def on_add_area_click(self, shape_button, overz_button, strategy_radio, cnc_button, solid_geo, obj_type):
  140. """
  141. :param shape_button: a FCButton that has the value for the shape
  142. :param overz_button: a FCDoubleSpinner that holds the Over Z value
  143. :param strategy_radio: a RadioSet button with the strategy value
  144. :param cnc_button: a FCButton in Object UI that when clicked the CNCJob is created
  145. We have a reference here so we can change the color signifying that exclusion areas are
  146. available.
  147. :param solid_geo: reference to the object solid geometry for which we add exclusion areas
  148. :param obj_type: Type of FlatCAM object that called this method
  149. :type obj_type: String: "excellon" or "geometry"
  150. :return:
  151. """
  152. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  153. self.app.call_source = 'geometry'
  154. self.shape_type = shape_button.get_value()
  155. self.over_z = overz_button.get_value()
  156. self.strategy = strategy_radio.get_value()
  157. self.cnc_button = cnc_button
  158. self.solid_geometry = solid_geo
  159. self.obj_type = obj_type
  160. if self.app.is_legacy is False:
  161. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  162. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  163. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  164. else:
  165. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  166. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  167. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  168. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  169. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  170. # self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  171. # To be called after clicking on the plot.
  172. def on_mouse_release(self, event):
  173. if self.app.is_legacy is False:
  174. event_pos = event.pos
  175. # event_is_dragging = event.is_dragging
  176. right_button = 2
  177. else:
  178. event_pos = (event.xdata, event.ydata)
  179. # event_is_dragging = self.app.plotcanvas.is_dragging
  180. right_button = 3
  181. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  182. if self.app.grid_status():
  183. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  184. else:
  185. curr_pos = (event_pos[0], event_pos[1])
  186. x1, y1 = curr_pos[0], curr_pos[1]
  187. # shape_type = self.ui.area_shape_radio.get_value()
  188. # do clear area only for left mouse clicks
  189. if event.button == 1:
  190. if self.shape_type == "square":
  191. if self.first_click is False:
  192. self.first_click = True
  193. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  194. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  195. if self.app.grid_status():
  196. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  197. else:
  198. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  199. self.app.delete_selection_shape()
  200. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  201. pt1 = (x0, y0)
  202. pt2 = (x1, y0)
  203. pt3 = (x1, y1)
  204. pt4 = (x0, y1)
  205. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  206. # {
  207. # "obj_type": string("excellon" or "geometry") < - self.obj_type
  208. # "shape": Shapely polygon
  209. # "strategy": string("over" or "around") < - self.strategy
  210. # "overz": float < - self.over_z
  211. # }
  212. new_el = {
  213. "obj_type": self.obj_type,
  214. "shape": new_rectangle,
  215. "strategy": self.strategy,
  216. "overz": self.over_z
  217. }
  218. self.exclusion_areas_storage.append(new_el)
  219. # add a temporary shape on canvas
  220. FlatCAMTool.draw_tool_selection_shape(
  221. self, old_coords=(x0, y0), coords=(x1, y1),
  222. color="#FF7400",
  223. face_color="#FF7400BF",
  224. shapes_storage=self.exclusion_shapes)
  225. self.first_click = False
  226. return
  227. else:
  228. self.points.append((x1, y1))
  229. if len(self.points) > 1:
  230. self.poly_drawn = True
  231. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  232. return ""
  233. elif event.button == right_button and self.mouse_is_dragging is False:
  234. shape_type = self.shape_type
  235. if shape_type == "square":
  236. self.first_click = False
  237. else:
  238. # if we finish to add a polygon
  239. if self.poly_drawn is True:
  240. try:
  241. # try to add the point where we last clicked if it is not already in the self.points
  242. last_pt = (x1, y1)
  243. if last_pt != self.points[-1]:
  244. self.points.append(last_pt)
  245. except IndexError:
  246. pass
  247. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  248. if len(self.points) > 2:
  249. FlatCAMTool.delete_moving_selection_shape(self)
  250. pol = Polygon(self.points)
  251. # do not add invalid polygons even if they are drawn by utility geometry
  252. if pol.is_valid:
  253. # {
  254. # "obj_type": string("excellon" or "geometry") < - self.obj_type
  255. # "shape": Shapely polygon
  256. # "strategy": string("over" or "around") < - self.strategy
  257. # "overz": float < - self.over_z
  258. # }
  259. new_el = {
  260. "obj_type": self.obj_type,
  261. "shape": pol,
  262. "strategy": self.strategy,
  263. "overz": self.over_z
  264. }
  265. self.exclusion_areas_storage.append(new_el)
  266. FlatCAMTool.draw_selection_shape_polygon(
  267. self, points=self.points,
  268. color="#FF7400",
  269. face_color="#FF7400BF",
  270. shapes_storage=self.exclusion_shapes)
  271. self.app.inform.emit(
  272. _("Zone added. Click to start adding next zone or right click to finish."))
  273. self.points = []
  274. self.poly_drawn = False
  275. return
  276. # FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  277. if self.app.is_legacy is False:
  278. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  279. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  280. # self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  281. else:
  282. self.app.plotcanvas.graph_event_disconnect(self.mr)
  283. self.app.plotcanvas.graph_event_disconnect(self.mm)
  284. # self.app.plotcanvas.graph_event_disconnect(self.kp)
  285. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  286. self.app.on_mouse_click_over_plot)
  287. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  288. self.app.on_mouse_move_over_plot)
  289. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  290. self.app.on_mouse_click_release_over_plot)
  291. self.app.call_source = 'app'
  292. if len(self.exclusion_areas_storage) == 0:
  293. return
  294. self.app.inform.emit(
  295. "[success] %s" % _("Exclusion areas added. Checking overlap with the object geometry ..."))
  296. for el in self.exclusion_areas_storage:
  297. if el["shape"].intersects(MultiPolygon(self.solid_geometry)):
  298. self.on_clear_area_click()
  299. self.app.inform.emit(
  300. "[ERROR_NOTCL] %s" % _("Failed. Exclusion areas intersects the object geometry ..."))
  301. return
  302. self.app.inform.emit(
  303. "[success] %s" % _("Exclusion areas added."))
  304. self.cnc_button.setStyleSheet("""
  305. QPushButton
  306. {
  307. font-weight: bold;
  308. color: orange;
  309. }
  310. """)
  311. self.cnc_button.setToolTip(
  312. '%s %s' % (_("Generate the CNC Job object."), _("With Exclusion areas."))
  313. )
  314. for k in self.exclusion_areas_storage:
  315. print(k)
  316. def area_disconnect(self):
  317. if self.app.is_legacy is False:
  318. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  319. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  320. else:
  321. self.app.plotcanvas.graph_event_disconnect(self.mr)
  322. self.app.plotcanvas.graph_event_disconnect(self.mm)
  323. self.app.plotcanvas.graph_event_disconnect(self.kp)
  324. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  325. self.app.on_mouse_click_over_plot)
  326. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  327. self.app.on_mouse_move_over_plot)
  328. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  329. self.app.on_mouse_click_release_over_plot)
  330. self.points = []
  331. self.poly_drawn = False
  332. self.exclusion_areas_storage = []
  333. FlatCAMTool.delete_moving_selection_shape(self)
  334. # FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  335. self.app.call_source = "app"
  336. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Cancelled. Area exclusion drawing was interrupted."))
  337. # called on mouse move
  338. def on_mouse_move(self, event):
  339. shape_type = self.shape_type
  340. if self.app.is_legacy is False:
  341. event_pos = event.pos
  342. event_is_dragging = event.is_dragging
  343. # right_button = 2
  344. else:
  345. event_pos = (event.xdata, event.ydata)
  346. event_is_dragging = self.app.plotcanvas.is_dragging
  347. # right_button = 3
  348. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  349. # detect mouse dragging motion
  350. if event_is_dragging is True:
  351. self.mouse_is_dragging = True
  352. else:
  353. self.mouse_is_dragging = False
  354. # update the cursor position
  355. if self.app.grid_status():
  356. # Update cursor
  357. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  358. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  359. symbol='++', edge_color=self.app.cursor_color_3D,
  360. edge_width=self.app.defaults["global_cursor_width"],
  361. size=self.app.defaults["global_cursor_size"])
  362. # update the positions on status bar
  363. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  364. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  365. if self.cursor_pos is None:
  366. self.cursor_pos = (0, 0)
  367. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  368. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  369. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  370. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  371. # draw the utility geometry
  372. if shape_type == "square":
  373. if self.first_click:
  374. self.app.delete_selection_shape()
  375. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  376. color="#FF7400",
  377. face_color="#FF7400BF",
  378. coords=(curr_pos[0], curr_pos[1]))
  379. else:
  380. FlatCAMTool.delete_moving_selection_shape(self)
  381. FlatCAMTool.draw_moving_selection_shape_poly(
  382. self, points=self.points,
  383. color="#FF7400",
  384. face_color="#FF7400BF",
  385. data=(curr_pos[0], curr_pos[1]))
  386. def on_clear_area_click(self):
  387. self.clear_shapes()
  388. # restore the default StyleSheet
  389. self.cnc_button.setStyleSheet("")
  390. # update the StyleSheet
  391. self.cnc_button.setStyleSheet("""
  392. QPushButton
  393. {
  394. font-weight: bold;
  395. }
  396. """)
  397. self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object."))
  398. def clear_shapes(self):
  399. self.exclusion_areas_storage.clear()
  400. FlatCAMTool.delete_moving_selection_shape(self)
  401. self.app.delete_selection_shape()
  402. FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)