FlatCAMDraw.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. from PyQt4 import QtGui, QtCore, Qt
  2. import FlatCAMApp
  3. from camlib import *
  4. from shapely.geometry import Polygon, LineString, Point, LinearRing
  5. from shapely.geometry import MultiPoint, MultiPolygon
  6. from shapely.geometry import box as shply_box
  7. from shapely.ops import cascaded_union, unary_union
  8. import shapely.affinity as affinity
  9. from shapely.wkt import loads as sloads
  10. from shapely.wkt import dumps as sdumps
  11. from shapely.geometry.base import BaseGeometry
  12. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, sign, dot
  13. from numpy.linalg import solve
  14. #from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea
  15. from rtree import index as rtindex
  16. class DrawToolShape(object):
  17. """
  18. Encapsulates "shapes" under a common class.
  19. """
  20. @staticmethod
  21. def get_pts(o):
  22. """
  23. Returns a list of all points in the object, where
  24. the object can be a Polygon, Not a polygon, or a list
  25. of such. Search is done recursively.
  26. :param: geometric object
  27. :return: List of points
  28. :rtype: list
  29. """
  30. pts = []
  31. ## Iterable: descend into each item.
  32. try:
  33. for subo in o:
  34. pts += DrawToolShape.get_pts(subo)
  35. ## Non-iterable
  36. except TypeError:
  37. ## DrawToolShape: descend into .geo.
  38. if isinstance(o, DrawToolShape):
  39. pts += DrawToolShape.get_pts(o.geo)
  40. ## Descend into .exerior and .interiors
  41. elif type(o) == Polygon:
  42. pts += DrawToolShape.get_pts(o.exterior)
  43. for i in o.interiors:
  44. pts += DrawToolShape.get_pts(i)
  45. ## Has .coords: list them.
  46. else:
  47. pts += list(o.coords)
  48. return pts
  49. def __init__(self, geo=[]):
  50. # Shapely type or list of such
  51. self.geo = geo
  52. self.utility = False
  53. def get_all_points(self):
  54. return DrawToolShape.get_pts(self)
  55. class DrawToolUtilityShape(DrawToolShape):
  56. """
  57. Utility shapes are temporary geometry in the editor
  58. to assist in the creation of shapes. For example it
  59. will show the outline of a rectangle from the first
  60. point to the current mouse pointer before the second
  61. point is clicked and the final geometry is created.
  62. """
  63. def __init__(self, geo=[]):
  64. super(DrawToolUtilityShape, self).__init__(geo=geo)
  65. self.utility = True
  66. class DrawTool(object):
  67. """
  68. Abstract Class representing a tool in the drawing
  69. program. Can generate geometry, including temporary
  70. utility geometry that is updated on user clicks
  71. and mouse motion.
  72. """
  73. def __init__(self, draw_app):
  74. self.draw_app = draw_app
  75. self.complete = False
  76. self.start_msg = "Click on 1st point..."
  77. self.points = []
  78. self.geometry = None # DrawToolShape or None
  79. def click(self, point):
  80. """
  81. :param point: [x, y] Coordinate pair.
  82. """
  83. return ""
  84. def on_key(self, key):
  85. return None
  86. def utility_geometry(self, data=None):
  87. return None
  88. class FCShapeTool(DrawTool):
  89. """
  90. Abstarct class for tools that create a shape.
  91. """
  92. def __init__(self, draw_app):
  93. DrawTool.__init__(self, draw_app)
  94. def make(self):
  95. pass
  96. class FCCircle(FCShapeTool):
  97. """
  98. Resulting type: Polygon
  99. """
  100. def __init__(self, draw_app):
  101. DrawTool.__init__(self, draw_app)
  102. self.start_msg = "Click on CENTER ..."
  103. def click(self, point):
  104. self.points.append(point)
  105. if len(self.points) == 1:
  106. return "Click on perimeter to complete ..."
  107. if len(self.points) == 2:
  108. self.make()
  109. return "Done."
  110. return ""
  111. def utility_geometry(self, data=None):
  112. if len(self.points) == 1:
  113. p1 = self.points[0]
  114. p2 = data
  115. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  116. return DrawToolUtilityShape(Point(p1).buffer(radius))
  117. return None
  118. def make(self):
  119. p1 = self.points[0]
  120. p2 = self.points[1]
  121. radius = distance(p1, p2)
  122. self.geometry = DrawToolShape(Point(p1).buffer(radius))
  123. self.complete = True
  124. class FCArc(FCShapeTool):
  125. def __init__(self, draw_app):
  126. DrawTool.__init__(self, draw_app)
  127. self.start_msg = "Click on CENTER ..."
  128. # Direction of rotation between point 1 and 2.
  129. # 'cw' or 'ccw'. Switch direction by hitting the
  130. # 'o' key.
  131. self.direction = "cw"
  132. # Mode
  133. # C12 = Center, p1, p2
  134. # 12C = p1, p2, Center
  135. # 132 = p1, p3, p2
  136. self.mode = "c12" # Center, p1, p2
  137. self.steps_per_circ = 55
  138. def click(self, point):
  139. self.points.append(point)
  140. if len(self.points) == 1:
  141. return "Click on 1st point ..."
  142. if len(self.points) == 2:
  143. return "Click on 2nd point to complete ..."
  144. if len(self.points) == 3:
  145. self.make()
  146. return "Done."
  147. return ""
  148. def on_key(self, key):
  149. if key == 'o':
  150. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  151. return 'Direction: ' + self.direction.upper()
  152. if key == 'p':
  153. if self.mode == 'c12':
  154. self.mode = '12c'
  155. elif self.mode == '12c':
  156. self.mode = '132'
  157. else:
  158. self.mode = 'c12'
  159. return 'Mode: ' + self.mode
  160. def utility_geometry(self, data=None):
  161. if len(self.points) == 1: # Show the radius
  162. center = self.points[0]
  163. p1 = data
  164. return DrawToolUtilityShape(LineString([center, p1]))
  165. if len(self.points) == 2: # Show the arc
  166. if self.mode == 'c12':
  167. center = self.points[0]
  168. p1 = self.points[1]
  169. p2 = data
  170. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  171. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  172. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  173. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  174. self.direction, self.steps_per_circ)),
  175. Point(center)])
  176. elif self.mode == '132':
  177. p1 = array(self.points[0])
  178. p3 = array(self.points[1])
  179. p2 = array(data)
  180. center, radius, t = three_point_circle(p1, p2, p3)
  181. direction = 'cw' if sign(t) > 0 else 'ccw'
  182. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  183. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  184. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  185. direction, self.steps_per_circ)),
  186. Point(center), Point(p1), Point(p3)])
  187. else: # '12c'
  188. p1 = array(self.points[0])
  189. p2 = array(self.points[1])
  190. # Midpoint
  191. a = (p1 + p2) / 2.0
  192. # Parallel vector
  193. c = p2 - p1
  194. # Perpendicular vector
  195. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  196. b /= norm(b)
  197. # Distance
  198. t = distance(data, a)
  199. # Which side? Cross product with c.
  200. # cross(M-A, B-A), where line is AB and M is test point.
  201. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  202. t *= sign(side)
  203. # Center = a + bt
  204. center = a + b * t
  205. radius = norm(center - p1)
  206. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  207. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  208. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  209. self.direction, self.steps_per_circ)),
  210. Point(center)])
  211. return None
  212. def make(self):
  213. if self.mode == 'c12':
  214. center = self.points[0]
  215. p1 = self.points[1]
  216. p2 = self.points[2]
  217. radius = distance(center, p1)
  218. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  219. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  220. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  221. self.direction, self.steps_per_circ)))
  222. elif self.mode == '132':
  223. p1 = array(self.points[0])
  224. p3 = array(self.points[1])
  225. p2 = array(self.points[2])
  226. center, radius, t = three_point_circle(p1, p2, p3)
  227. direction = 'cw' if sign(t) > 0 else 'ccw'
  228. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  229. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  230. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  231. direction, self.steps_per_circ)))
  232. else: # self.mode == '12c'
  233. p1 = array(self.points[0])
  234. p2 = array(self.points[1])
  235. pc = array(self.points[2])
  236. # Midpoint
  237. a = (p1 + p2) / 2.0
  238. # Parallel vector
  239. c = p2 - p1
  240. # Perpendicular vector
  241. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  242. b /= norm(b)
  243. # Distance
  244. t = distance(pc, a)
  245. # Which side? Cross product with c.
  246. # cross(M-A, B-A), where line is AB and M is test point.
  247. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  248. t *= sign(side)
  249. # Center = a + bt
  250. center = a + b * t
  251. radius = norm(center - p1)
  252. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  253. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  254. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  255. self.direction, self.steps_per_circ)))
  256. self.complete = True
  257. class FCRectangle(FCShapeTool):
  258. """
  259. Resulting type: Polygon
  260. """
  261. def __init__(self, draw_app):
  262. DrawTool.__init__(self, draw_app)
  263. self.start_msg = "Click on 1st corner ..."
  264. def click(self, point):
  265. self.points.append(point)
  266. if len(self.points) == 1:
  267. return "Click on opposite corner to complete ..."
  268. if len(self.points) == 2:
  269. self.make()
  270. return "Done."
  271. return ""
  272. def utility_geometry(self, data=None):
  273. if len(self.points) == 1:
  274. p1 = self.points[0]
  275. p2 = data
  276. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  277. return None
  278. def make(self):
  279. p1 = self.points[0]
  280. p2 = self.points[1]
  281. #self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  282. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  283. self.complete = True
  284. class FCPolygon(FCShapeTool):
  285. """
  286. Resulting type: Polygon
  287. """
  288. def __init__(self, draw_app):
  289. DrawTool.__init__(self, draw_app)
  290. self.start_msg = "Click on 1st point ..."
  291. def click(self, point):
  292. self.points.append(point)
  293. if len(self.points) > 0:
  294. return "Click on next point or hit SPACE to complete ..."
  295. return ""
  296. def utility_geometry(self, data=None):
  297. if len(self.points) == 1:
  298. temp_points = [x for x in self.points]
  299. temp_points.append(data)
  300. return DrawToolUtilityShape(LineString(temp_points))
  301. if len(self.points) > 1:
  302. temp_points = [x for x in self.points]
  303. temp_points.append(data)
  304. return DrawToolUtilityShape(LinearRing(temp_points))
  305. return None
  306. def make(self):
  307. # self.geometry = LinearRing(self.points)
  308. self.geometry = DrawToolShape(Polygon(self.points))
  309. self.complete = True
  310. class FCPath(FCPolygon):
  311. """
  312. Resulting type: LineString
  313. """
  314. def make(self):
  315. self.geometry = DrawToolShape(LineString(self.points))
  316. self.complete = True
  317. def utility_geometry(self, data=None):
  318. if len(self.points) > 1:
  319. temp_points = [x for x in self.points]
  320. temp_points.append(data)
  321. return DrawToolUtilityShape(LineString(temp_points))
  322. return None
  323. class FCSelect(DrawTool):
  324. def __init__(self, draw_app):
  325. DrawTool.__init__(self, draw_app)
  326. self.storage = self.draw_app.storage
  327. #self.shape_buffer = self.draw_app.shape_buffer
  328. self.selected = self.draw_app.selected
  329. self.start_msg = "Click on geometry to select"
  330. def click(self, point):
  331. _, closest_shape = self.storage.nearest(point)
  332. if self.draw_app.key != 'control':
  333. self.draw_app.selected = []
  334. self.draw_app.set_selected(closest_shape)
  335. self.draw_app.app.log.debug("Selected shape containing: " + str(closest_shape.geo))
  336. return ""
  337. class FCMove(FCShapeTool):
  338. def __init__(self, draw_app):
  339. FCShapeTool.__init__(self, draw_app)
  340. #self.shape_buffer = self.draw_app.shape_buffer
  341. self.origin = None
  342. self.destination = None
  343. self.start_msg = "Click on reference point."
  344. def set_origin(self, origin):
  345. self.origin = origin
  346. def click(self, point):
  347. if len(self.draw_app.get_selected()) == 0:
  348. return "Nothing to move."
  349. if self.origin is None:
  350. self.set_origin(point)
  351. return "Click on final location."
  352. else:
  353. self.destination = point
  354. self.make()
  355. return "Done."
  356. def make(self):
  357. # Create new geometry
  358. dx = self.destination[0] - self.origin[0]
  359. dy = self.destination[1] - self.origin[1]
  360. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  361. for geom in self.draw_app.get_selected()]
  362. # Delete old
  363. self.draw_app.delete_selected()
  364. # # Select the new
  365. # for g in self.geometry:
  366. # # Note that g is not in the app's buffer yet!
  367. # self.draw_app.set_selected(g)
  368. self.complete = True
  369. def utility_geometry(self, data=None):
  370. """
  371. Temporary geometry on screen while using this tool.
  372. :param data:
  373. :return:
  374. """
  375. if self.origin is None:
  376. return None
  377. if len(self.draw_app.get_selected()) == 0:
  378. return None
  379. dx = data[0] - self.origin[0]
  380. dy = data[1] - self.origin[1]
  381. return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  382. for geom in self.draw_app.get_selected()])
  383. class FCCopy(FCMove):
  384. def make(self):
  385. # Create new geometry
  386. dx = self.destination[0] - self.origin[0]
  387. dy = self.destination[1] - self.origin[1]
  388. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  389. for geom in self.draw_app.get_selected()]
  390. self.complete = True
  391. ########################
  392. ### Main Application ###
  393. ########################
  394. class FlatCAMDraw(QtCore.QObject):
  395. def __init__(self, app, disabled=False):
  396. assert isinstance(app, FlatCAMApp.App)
  397. super(FlatCAMDraw, self).__init__()
  398. self.app = app
  399. self.canvas = app.plotcanvas
  400. self.axes = self.canvas.new_axes("draw")
  401. ### Drawing Toolbar ###
  402. self.drawing_toolbar = QtGui.QToolBar()
  403. self.drawing_toolbar.setDisabled(disabled)
  404. self.app.ui.addToolBar(self.drawing_toolbar)
  405. self.select_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/pointer32.png'), "Select 'Esc'")
  406. self.add_circle_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/circle32.png'), 'Add Circle')
  407. self.add_arc_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/arc32.png'), 'Add Arc')
  408. self.add_rectangle_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/rectangle32.png'), 'Add Rectangle')
  409. self.add_polygon_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/polygon32.png'), 'Add Polygon')
  410. self.add_path_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/path32.png'), 'Add Path')
  411. self.union_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/union32.png'), 'Polygon Union')
  412. self.intersection_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/intersection32.png'), 'Polygon Intersection')
  413. self.subtract_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/subtract32.png'), 'Polygon Subtraction')
  414. self.cutpath_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/cutpath32.png'), 'Cut Path')
  415. self.move_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/move32.png'), "Move Objects 'm'")
  416. self.copy_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/copy32.png'), "Copy Objects 'c'")
  417. self.delete_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/deleteshape32.png'), "Delete Shape '-'")
  418. ### Snap Toolbar ###
  419. self.snap_toolbar = QtGui.QToolBar()
  420. self.grid_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/grid32.png'), 'Snap to grid')
  421. self.grid_gap_x_entry = QtGui.QLineEdit()
  422. self.grid_gap_x_entry.setMaximumWidth(70)
  423. self.grid_gap_x_entry.setToolTip("Grid X distance")
  424. self.snap_toolbar.addWidget(self.grid_gap_x_entry)
  425. self.grid_gap_y_entry = QtGui.QLineEdit()
  426. self.grid_gap_y_entry.setMaximumWidth(70)
  427. self.grid_gap_y_entry.setToolTip("Grid Y distante")
  428. self.snap_toolbar.addWidget(self.grid_gap_y_entry)
  429. self.corner_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/corner32.png'), 'Snap to corner')
  430. self.snap_max_dist_entry = QtGui.QLineEdit()
  431. self.snap_max_dist_entry.setMaximumWidth(70)
  432. self.snap_max_dist_entry.setToolTip("Max. magnet distance")
  433. self.snap_toolbar.addWidget(self.snap_max_dist_entry)
  434. self.snap_toolbar.setDisabled(disabled)
  435. self.app.ui.addToolBar(self.snap_toolbar)
  436. ### Event handlers ###
  437. ## Canvas events
  438. self.canvas.mpl_connect('button_press_event', self.on_canvas_click)
  439. self.canvas.mpl_connect('motion_notify_event', self.on_canvas_move)
  440. self.canvas.mpl_connect('key_press_event', self.on_canvas_key)
  441. self.canvas.mpl_connect('key_release_event', self.on_canvas_key_release)
  442. self.union_btn.triggered.connect(self.union)
  443. self.intersection_btn.triggered.connect(self.intersection)
  444. self.subtract_btn.triggered.connect(self.subtract)
  445. self.cutpath_btn.triggered.connect(self.cutpath)
  446. self.delete_btn.triggered.connect(self.on_delete_btn)
  447. ## Toolbar events and properties
  448. self.tools = {
  449. "select": {"button": self.select_btn,
  450. "constructor": FCSelect},
  451. "circle": {"button": self.add_circle_btn,
  452. "constructor": FCCircle},
  453. "arc": {"button": self.add_arc_btn,
  454. "constructor": FCArc},
  455. "rectangle": {"button": self.add_rectangle_btn,
  456. "constructor": FCRectangle},
  457. "polygon": {"button": self.add_polygon_btn,
  458. "constructor": FCPolygon},
  459. "path": {"button": self.add_path_btn,
  460. "constructor": FCPath},
  461. "move": {"button": self.move_btn,
  462. "constructor": FCMove},
  463. "copy": {"button": self.copy_btn,
  464. "constructor": FCCopy}
  465. }
  466. ### Data
  467. self.active_tool = None
  468. self.storage = FlatCAMDraw.make_storage()
  469. self.utility = []
  470. ## List of selected shapes.
  471. self.selected = []
  472. self.move_timer = QtCore.QTimer()
  473. self.move_timer.setSingleShot(True)
  474. self.key = None # Currently pressed key
  475. def make_callback(thetool):
  476. def f():
  477. self.on_tool_select(thetool)
  478. return f
  479. for tool in self.tools:
  480. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  481. self.tools[tool]["button"].setCheckable(True) # Checkable
  482. # for snap_tool in [self.grid_snap_btn, self.corner_snap_btn]:
  483. # snap_tool.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  484. # snap_tool.setCheckable(True)
  485. self.grid_snap_btn.setCheckable(True)
  486. self.grid_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  487. self.corner_snap_btn.setCheckable(True)
  488. self.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  489. self.options = {
  490. "snap-x": 0.1,
  491. "snap-y": 0.1,
  492. "snap_max": 0.05,
  493. "grid_snap": False,
  494. "corner_snap": False,
  495. }
  496. self.grid_gap_x_entry.setText(str(self.options["snap-x"]))
  497. self.grid_gap_y_entry.setText(str(self.options["snap-y"]))
  498. self.snap_max_dist_entry.setText(str(self.options["snap_max"]))
  499. self.rtree_index = rtindex.Index()
  500. def entry2option(option, entry):
  501. self.options[option] = float(entry.text())
  502. self.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  503. self.grid_gap_x_entry.editingFinished.connect(lambda: entry2option("snap-x", self.grid_gap_x_entry))
  504. self.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  505. self.grid_gap_y_entry.editingFinished.connect(lambda: entry2option("snap-y", self.grid_gap_y_entry))
  506. self.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  507. self.snap_max_dist_entry.editingFinished.connect(lambda: entry2option("snap_max", self.snap_max_dist_entry))
  508. def activate(self):
  509. pass
  510. def add_shape(self, shape):
  511. """
  512. Adds a shape to the shape storage.
  513. :param shape: Shape to be added.
  514. :type shape: DrawToolShape
  515. :return: None
  516. """
  517. # List of DrawToolShape?
  518. if isinstance(shape, list):
  519. for subshape in shape:
  520. self.add_shape(subshape)
  521. return
  522. assert isinstance(shape, DrawToolShape)
  523. assert shape.geo is not None
  524. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list)
  525. if isinstance(shape, DrawToolUtilityShape):
  526. self.utility.append(shape)
  527. else:
  528. self.storage.insert(shape)
  529. def deactivate(self):
  530. self.clear()
  531. self.drawing_toolbar.setDisabled(True)
  532. self.snap_toolbar.setDisabled(True) # TODO: Combine and move into tool
  533. def delete_utility_geometry(self):
  534. #for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  535. #for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  536. for_deletion = [shape for shape in self.utility]
  537. for shape in for_deletion:
  538. self.delete_shape(shape)
  539. def cutpath(self):
  540. selected = self.get_selected()
  541. tools = selected[1:]
  542. toolgeo = cascaded_union([shp.geo for shp in tools])
  543. target = selected[0]
  544. if type(target.geo) == Polygon:
  545. for ring in poly2rings(target.geo):
  546. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  547. self.delete_shape(target)
  548. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  549. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  550. self.delete_shape(target)
  551. else:
  552. self.app.log.warning("Not implemented.")
  553. self.replot()
  554. def toolbar_tool_toggle(self, key):
  555. self.options[key] = self.sender().isChecked()
  556. def clear(self):
  557. self.active_tool = None
  558. #self.shape_buffer = []
  559. self.selected = []
  560. self.storage = FlatCAMDraw.make_storage()
  561. self.replot()
  562. def edit_fcgeometry(self, fcgeometry):
  563. """
  564. Imports the geometry from the given FlatCAM Geometry object
  565. into the editor.
  566. :param fcgeometry: FlatCAMGeometry
  567. :return: None
  568. """
  569. assert isinstance(fcgeometry, Geometry)
  570. self.clear()
  571. self.select_tool("select")
  572. # Link shapes into editor.
  573. for shape in fcgeometry.flatten():
  574. if shape is not None: # TODO: Make flatten never create a None
  575. self.add_shape(DrawToolShape(shape))
  576. self.replot()
  577. self.drawing_toolbar.setDisabled(False)
  578. self.snap_toolbar.setDisabled(False)
  579. def on_tool_select(self, tool):
  580. """
  581. Behavior of the toolbar. Tool initialization.
  582. :rtype : None
  583. """
  584. self.app.log.debug("on_tool_select('%s')" % tool)
  585. # This is to make the group behave as radio group
  586. if tool in self.tools:
  587. if self.tools[tool]["button"].isChecked():
  588. self.app.log.debug("%s is checked." % tool)
  589. for t in self.tools:
  590. if t != tool:
  591. self.tools[t]["button"].setChecked(False)
  592. self.active_tool = self.tools[tool]["constructor"](self)
  593. self.app.info(self.active_tool.start_msg)
  594. else:
  595. self.app.log.debug("%s is NOT checked." % tool)
  596. for t in self.tools:
  597. self.tools[t]["button"].setChecked(False)
  598. self.active_tool = None
  599. def on_canvas_click(self, event):
  600. """
  601. event.x and .y have canvas coordinates
  602. event.xdaya and .ydata have plot coordinates
  603. :param event: Event object dispatched by Matplotlib
  604. :return: None
  605. """
  606. if self.active_tool is not None:
  607. # Dispatch event to active_tool
  608. msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  609. self.app.info(msg)
  610. # If it is a shape generating tool
  611. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  612. self.on_shape_complete()
  613. return
  614. if isinstance(self.active_tool, FCSelect):
  615. self.app.log.debug("Replotting after click.")
  616. self.replot()
  617. else:
  618. self.app.log.debug("No active tool to respond to click!")
  619. def on_canvas_move(self, event):
  620. """
  621. event.x and .y have canvas coordinates
  622. event.xdaya and .ydata have plot coordinates
  623. :param event: Event object dispatched by Matplotlib
  624. :return:
  625. """
  626. self.on_canvas_move_effective(event)
  627. return None
  628. # self.move_timer.stop()
  629. #
  630. # if self.active_tool is None:
  631. # return
  632. #
  633. # # Make a function to avoid late evaluation
  634. # def make_callback():
  635. # def f():
  636. # self.on_canvas_move_effective(event)
  637. # return f
  638. # callback = make_callback()
  639. #
  640. # self.move_timer.timeout.connect(callback)
  641. # self.move_timer.start(500) # Stops if aready running
  642. def on_canvas_move_effective(self, event):
  643. """
  644. Is called after timeout on timer set in on_canvas_move.
  645. For details on animating on MPL see:
  646. http://wiki.scipy.org/Cookbook/Matplotlib/Animations
  647. event.x and .y have canvas coordinates
  648. event.xdaya and .ydata have plot coordinates
  649. :param event: Event object dispatched by Matplotlib
  650. :return: None
  651. """
  652. try:
  653. x = float(event.xdata)
  654. y = float(event.ydata)
  655. except TypeError:
  656. return
  657. if self.active_tool is None:
  658. return
  659. ### Snap coordinates
  660. x, y = self.snap(x, y)
  661. ### Utility geometry (animated)
  662. self.canvas.canvas.restore_region(self.canvas.background)
  663. geo = self.active_tool.utility_geometry(data=(x, y))
  664. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  665. # Remove any previous utility shape
  666. self.delete_utility_geometry()
  667. # Add the new utility shape
  668. self.add_shape(geo)
  669. # Efficient plotting for fast animation
  670. #self.canvas.canvas.restore_region(self.canvas.background)
  671. elements = self.plot_shape(geometry=geo.geo,
  672. linespec="b--",
  673. linewidth=1,
  674. animated=True)
  675. for el in elements:
  676. self.axes.draw_artist(el)
  677. #self.canvas.canvas.blit(self.axes.bbox)
  678. # Pointer (snapped)
  679. elements = self.axes.plot(x, y, 'bo', animated=True)
  680. for el in elements:
  681. self.axes.draw_artist(el)
  682. self.canvas.canvas.blit(self.axes.bbox)
  683. def on_canvas_key(self, event):
  684. """
  685. event.key has the key.
  686. :param event:
  687. :return:
  688. """
  689. self.key = event.key
  690. ### Finish the current action. Use with tools that do not
  691. ### complete automatically, like a polygon or path.
  692. if event.key == ' ':
  693. if isinstance(self.active_tool, FCShapeTool):
  694. self.active_tool.click(self.snap(event.xdata, event.ydata))
  695. self.active_tool.make()
  696. if self.active_tool.complete:
  697. self.on_shape_complete()
  698. return
  699. ### Abort the current action
  700. if event.key == 'escape':
  701. # TODO: ...?
  702. #self.on_tool_select("select")
  703. self.app.info("Cancelled.")
  704. self.delete_utility_geometry()
  705. self.replot()
  706. # self.select_btn.setChecked(True)
  707. # self.on_tool_select('select')
  708. self.select_tool('select')
  709. return
  710. ### Delete selected object
  711. if event.key == '-':
  712. self.delete_selected()
  713. self.replot()
  714. ### Move
  715. if event.key == 'm':
  716. self.move_btn.setChecked(True)
  717. self.on_tool_select('move')
  718. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  719. ### Copy
  720. if event.key == 'c':
  721. self.copy_btn.setChecked(True)
  722. self.on_tool_select('copy')
  723. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  724. ### Snap
  725. if event.key == 'g':
  726. self.grid_snap_btn.trigger()
  727. if event.key == 'k':
  728. self.corner_snap_btn.trigger()
  729. ### Propagate to tool
  730. response = None
  731. if self.active_tool is not None:
  732. response = self.active_tool.on_key(event.key)
  733. if response is not None:
  734. self.app.info(response)
  735. def on_canvas_key_release(self, event):
  736. self.key = None
  737. def on_delete_btn(self):
  738. self.delete_selected()
  739. self.replot()
  740. def get_selected(self):
  741. """
  742. Returns list of shapes that are selected in the editor.
  743. :return: List of shapes.
  744. """
  745. #return [shape for shape in self.shape_buffer if shape["selected"]]
  746. return self.selected
  747. def delete_selected(self):
  748. tempref = [s for s in self.selected]
  749. for shape in tempref:
  750. self.delete_shape(shape)
  751. self.selected = []
  752. def plot_shape(self, geometry=None, linespec='b-', linewidth=1, animated=False):
  753. """
  754. Plots a geometric object or list of objects without rendering. Plotted objects
  755. are returned as a list. This allows for efficient/animated rendering.
  756. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  757. :param linespec: Matplotlib linespec string.
  758. :param linewidth: Width of lines in # of pixels.
  759. :param animated: If geometry is to be animated. (See MPL plot())
  760. :return: List of plotted elements.
  761. """
  762. plot_elements = []
  763. if geometry is None:
  764. geometry = self.active_tool.geometry
  765. try:
  766. for geo in geometry:
  767. plot_elements += self.plot_shape(geometry=geo,
  768. linespec=linespec,
  769. linewidth=linewidth,
  770. animated=animated)
  771. ## Non-iterable
  772. except TypeError:
  773. ## DrawToolShape
  774. if isinstance(geometry, DrawToolShape):
  775. plot_elements += self.plot_shape(geometry=geometry.geo,
  776. linespec=linespec,
  777. linewidth=linewidth,
  778. animated=animated)
  779. ## Polygon: Dscend into exterior and each interior.
  780. if type(geometry) == Polygon:
  781. plot_elements += self.plot_shape(geometry=geometry.exterior,
  782. linespec=linespec,
  783. linewidth=linewidth,
  784. animated=animated)
  785. plot_elements += self.plot_shape(geometry=geometry.interiors,
  786. linespec=linespec,
  787. linewidth=linewidth,
  788. animated=animated)
  789. if type(geometry) == LineString or type(geometry) == LinearRing:
  790. x, y = geometry.coords.xy
  791. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  792. plot_elements.append(element)
  793. if type(geometry) == Point:
  794. x, y = geometry.coords.xy
  795. element, = self.axes.plot(x, y, 'bo', linewidth=linewidth, animated=animated)
  796. plot_elements.append(element)
  797. return plot_elements
  798. def plot_all(self):
  799. """
  800. Plots all shapes in the editor.
  801. Clears the axes, plots, and call self.canvas.auto_adjust_axes.
  802. :return: None
  803. :rtype: None
  804. """
  805. self.app.log.debug("plot_all()")
  806. self.axes.cla()
  807. for shape in self.storage.get_objects():
  808. if shape.geo is None: # TODO: This shouldn't have happened
  809. continue
  810. if shape in self.selected:
  811. self.plot_shape(geometry=shape.geo, linespec='k-', linewidth=2)
  812. continue
  813. self.plot_shape(geometry=shape.geo)
  814. for shape in self.utility:
  815. self.plot_shape(geometry=shape.geo, linespec='k--', linewidth=1)
  816. continue
  817. self.canvas.auto_adjust_axes()
  818. def on_shape_complete(self):
  819. self.app.log.debug("on_shape_complete()")
  820. # Add shape
  821. self.add_shape(self.active_tool.geometry)
  822. # Remove any utility shapes
  823. self.delete_utility_geometry()
  824. # Replot and reset tool.
  825. self.replot()
  826. self.active_tool = type(self.active_tool)(self)
  827. def delete_shape(self, shape):
  828. if shape in self.utility:
  829. self.utility.remove(shape)
  830. return
  831. self.storage.remove(shape)
  832. if shape in self.selected:
  833. self.selected.remove(shape)
  834. def replot(self):
  835. self.axes = self.canvas.new_axes("draw")
  836. self.plot_all()
  837. @staticmethod
  838. def make_storage():
  839. ## Shape storage.
  840. storage = FlatCAMRTreeStorage()
  841. storage.get_points = DrawToolShape.get_pts
  842. return storage
  843. def select_tool(self, toolname):
  844. """
  845. Selects a drawing tool. Impacts the object and GUI.
  846. :param toolname: Name of the tool.
  847. :return: None
  848. """
  849. self.tools[toolname]["button"].setChecked(True)
  850. self.on_tool_select(toolname)
  851. def set_selected(self, shape):
  852. # Remove and add to the end.
  853. if shape in self.selected:
  854. self.selected.remove(shape)
  855. self.selected.append(shape)
  856. def set_unselected(self, shape):
  857. if shape in self.selected:
  858. self.selected.remove(shape)
  859. def snap(self, x, y):
  860. """
  861. Adjusts coordinates to snap settings.
  862. :param x: Input coordinate X
  863. :param y: Input coordinate Y
  864. :return: Snapped (x, y)
  865. """
  866. snap_x, snap_y = (x, y)
  867. snap_distance = Inf
  868. ### Object (corner?) snap
  869. ### No need for the objects, just the coordinates
  870. ### in the index.
  871. if self.options["corner_snap"]:
  872. try:
  873. nearest_pt, shape = self.storage.nearest((x, y))
  874. nearest_pt_distance = distance((x, y), nearest_pt)
  875. if nearest_pt_distance <= self.options["snap_max"]:
  876. snap_distance = nearest_pt_distance
  877. snap_x, snap_y = nearest_pt
  878. except (StopIteration, AssertionError):
  879. pass
  880. ### Grid snap
  881. if self.options["grid_snap"]:
  882. if self.options["snap-x"] != 0:
  883. snap_x_ = round(x / self.options["snap-x"]) * self.options['snap-x']
  884. else:
  885. snap_x_ = x
  886. if self.options["snap-y"] != 0:
  887. snap_y_ = round(y / self.options["snap-y"]) * self.options['snap-y']
  888. else:
  889. snap_y_ = y
  890. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  891. if nearest_grid_distance < snap_distance:
  892. snap_x, snap_y = (snap_x_, snap_y_)
  893. return snap_x, snap_y
  894. def update_fcgeometry(self, fcgeometry):
  895. """
  896. Transfers the drawing tool shape buffer to the selected geometry
  897. object. The geometry already in the object are removed.
  898. :param fcgeometry: FlatCAMGeometry
  899. :return: None
  900. """
  901. fcgeometry.solid_geometry = []
  902. #for shape in self.shape_buffer:
  903. for shape in self.storage.get_objects():
  904. fcgeometry.solid_geometry.append(shape.geo)
  905. def union(self):
  906. """
  907. Makes union of selected polygons. Original polygons
  908. are deleted.
  909. :return: None.
  910. """
  911. results = cascaded_union([t.geo for t in self.get_selected()])
  912. # Delete originals.
  913. for_deletion = [s for s in self.get_selected()]
  914. for shape in for_deletion:
  915. self.delete_shape(shape)
  916. # Selected geometry is now gone!
  917. self.selected = []
  918. self.add_shape(DrawToolShape(results))
  919. self.replot()
  920. def intersection(self):
  921. """
  922. Makes intersectino of selected polygons. Original polygons are deleted.
  923. :return: None
  924. """
  925. shapes = self.get_selected()
  926. results = shapes[0].geo
  927. for shape in shapes[1:]:
  928. results = results.intersection(shape.geo)
  929. # Delete originals.
  930. for_deletion = [s for s in self.get_selected()]
  931. for shape in for_deletion:
  932. self.delete_shape(shape)
  933. # Selected geometry is now gone!
  934. self.selected = []
  935. self.add_shape(DrawToolShape(results))
  936. self.replot()
  937. def subtract(self):
  938. selected = self.get_selected()
  939. tools = selected[1:]
  940. toolgeo = cascaded_union([shp.geo for shp in tools])
  941. result = selected[0].geo.difference(toolgeo)
  942. self.delete_shape(selected[0])
  943. self.add_shape(DrawToolShape(result))
  944. self.replot()
  945. def distance(pt1, pt2):
  946. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  947. def mag(vec):
  948. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  949. def poly2rings(poly):
  950. return [poly.exterior] + [interior for interior in poly.interiors]