FlatCAMDraw.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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.subtract_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/subtract32.png'), 'Polygon Subtraction')
  413. self.cutpath_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/cutpath32.png'), 'Cut Path')
  414. self.move_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/move32.png'), "Move Objects 'm'")
  415. self.copy_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/copy32.png'), "Copy Objects 'c'")
  416. self.delete_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/deleteshape32.png'), "Delete Shape '-'")
  417. ### Snap Toolbar ###
  418. self.snap_toolbar = QtGui.QToolBar()
  419. self.grid_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/grid32.png'), 'Snap to grid')
  420. self.grid_gap_x_entry = QtGui.QLineEdit()
  421. self.grid_gap_x_entry.setMaximumWidth(70)
  422. self.grid_gap_x_entry.setToolTip("Grid X distance")
  423. self.snap_toolbar.addWidget(self.grid_gap_x_entry)
  424. self.grid_gap_y_entry = QtGui.QLineEdit()
  425. self.grid_gap_y_entry.setMaximumWidth(70)
  426. self.grid_gap_y_entry.setToolTip("Grid Y distante")
  427. self.snap_toolbar.addWidget(self.grid_gap_y_entry)
  428. self.corner_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/corner32.png'), 'Snap to corner')
  429. self.snap_max_dist_entry = QtGui.QLineEdit()
  430. self.snap_max_dist_entry.setMaximumWidth(70)
  431. self.snap_max_dist_entry.setToolTip("Max. magnet distance")
  432. self.snap_toolbar.addWidget(self.snap_max_dist_entry)
  433. self.snap_toolbar.setDisabled(disabled)
  434. self.app.ui.addToolBar(self.snap_toolbar)
  435. ### Event handlers ###
  436. ## Canvas events
  437. self.canvas.mpl_connect('button_press_event', self.on_canvas_click)
  438. self.canvas.mpl_connect('motion_notify_event', self.on_canvas_move)
  439. self.canvas.mpl_connect('key_press_event', self.on_canvas_key)
  440. self.canvas.mpl_connect('key_release_event', self.on_canvas_key_release)
  441. self.union_btn.triggered.connect(self.union)
  442. self.subtract_btn.triggered.connect(self.subtract)
  443. self.cutpath_btn.triggered.connect(self.cutpath)
  444. self.delete_btn.triggered.connect(self.on_delete_btn)
  445. ## Toolbar events and properties
  446. self.tools = {
  447. "select": {"button": self.select_btn,
  448. "constructor": FCSelect},
  449. "circle": {"button": self.add_circle_btn,
  450. "constructor": FCCircle},
  451. "arc": {"button": self.add_arc_btn,
  452. "constructor": FCArc},
  453. "rectangle": {"button": self.add_rectangle_btn,
  454. "constructor": FCRectangle},
  455. "polygon": {"button": self.add_polygon_btn,
  456. "constructor": FCPolygon},
  457. "path": {"button": self.add_path_btn,
  458. "constructor": FCPath},
  459. "move": {"button": self.move_btn,
  460. "constructor": FCMove},
  461. "copy": {"button": self.copy_btn,
  462. "constructor": FCCopy}
  463. }
  464. ### Data
  465. self.active_tool = None
  466. self.storage = FlatCAMDraw.make_storage()
  467. self.utility = []
  468. ## List of selected shapes.
  469. self.selected = []
  470. self.move_timer = QtCore.QTimer()
  471. self.move_timer.setSingleShot(True)
  472. self.key = None # Currently pressed key
  473. def make_callback(thetool):
  474. def f():
  475. self.on_tool_select(thetool)
  476. return f
  477. for tool in self.tools:
  478. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  479. self.tools[tool]["button"].setCheckable(True) # Checkable
  480. # for snap_tool in [self.grid_snap_btn, self.corner_snap_btn]:
  481. # snap_tool.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  482. # snap_tool.setCheckable(True)
  483. self.grid_snap_btn.setCheckable(True)
  484. self.grid_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  485. self.corner_snap_btn.setCheckable(True)
  486. self.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  487. self.options = {
  488. "snap-x": 0.1,
  489. "snap-y": 0.1,
  490. "snap_max": 0.05,
  491. "grid_snap": False,
  492. "corner_snap": False,
  493. }
  494. self.grid_gap_x_entry.setText(str(self.options["snap-x"]))
  495. self.grid_gap_y_entry.setText(str(self.options["snap-y"]))
  496. self.snap_max_dist_entry.setText(str(self.options["snap_max"]))
  497. self.rtree_index = rtindex.Index()
  498. def entry2option(option, entry):
  499. self.options[option] = float(entry.text())
  500. self.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  501. self.grid_gap_x_entry.editingFinished.connect(lambda: entry2option("snap-x", self.grid_gap_x_entry))
  502. self.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  503. self.grid_gap_y_entry.editingFinished.connect(lambda: entry2option("snap-y", self.grid_gap_y_entry))
  504. self.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  505. self.snap_max_dist_entry.editingFinished.connect(lambda: entry2option("snap_max", self.snap_max_dist_entry))
  506. def activate(self):
  507. pass
  508. def add_shape(self, shape):
  509. """
  510. Adds a shape to the shape storage.
  511. :param shape: Shape to be added.
  512. :type shape: DrawToolShape
  513. :return: None
  514. """
  515. # List of DrawToolShape?
  516. if isinstance(shape, list):
  517. for subshape in shape:
  518. self.add_shape(subshape)
  519. return
  520. assert isinstance(shape, DrawToolShape)
  521. assert shape.geo is not None
  522. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list)
  523. if isinstance(shape, DrawToolUtilityShape):
  524. self.utility.append(shape)
  525. else:
  526. self.storage.insert(shape)
  527. def deactivate(self):
  528. self.clear()
  529. self.drawing_toolbar.setDisabled(True)
  530. self.snap_toolbar.setDisabled(True) # TODO: Combine and move into tool
  531. def delete_utility_geometry(self):
  532. #for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  533. #for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  534. for_deletion = [shape for shape in self.utility]
  535. for shape in for_deletion:
  536. self.delete_shape(shape)
  537. def cutpath(self):
  538. selected = self.get_selected()
  539. tools = selected[1:]
  540. toolgeo = cascaded_union([shp.geo for shp in tools])
  541. target = selected[0]
  542. if type(target.geo) == Polygon:
  543. for ring in poly2rings(target.geo):
  544. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  545. self.delete_shape(target)
  546. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  547. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  548. self.delete_shape(target)
  549. else:
  550. self.app.log.warning("Not implemented.")
  551. self.replot()
  552. def toolbar_tool_toggle(self, key):
  553. self.options[key] = self.sender().isChecked()
  554. def clear(self):
  555. self.active_tool = None
  556. #self.shape_buffer = []
  557. self.selected = []
  558. self.storage = FlatCAMDraw.make_storage()
  559. self.replot()
  560. def edit_fcgeometry(self, fcgeometry):
  561. """
  562. Imports the geometry from the given FlatCAM Geometry object
  563. into the editor.
  564. :param fcgeometry: FlatCAMGeometry
  565. :return: None
  566. """
  567. assert isinstance(fcgeometry, Geometry)
  568. self.clear()
  569. # Link shapes into editor.
  570. for shape in fcgeometry.flatten():
  571. if shape is not None: # TODO: Make flatten never create a None
  572. self.add_shape(DrawToolShape(shape))
  573. self.replot()
  574. self.drawing_toolbar.setDisabled(False)
  575. self.snap_toolbar.setDisabled(False)
  576. def on_tool_select(self, tool):
  577. """
  578. Behavior of the toolbar. Tool initialization.
  579. :rtype : None
  580. """
  581. self.app.log.debug("on_tool_select('%s')" % tool)
  582. # This is to make the group behave as radio group
  583. if tool in self.tools:
  584. if self.tools[tool]["button"].isChecked():
  585. self.app.log.debug("%s is checked." % tool)
  586. for t in self.tools:
  587. if t != tool:
  588. self.tools[t]["button"].setChecked(False)
  589. self.active_tool = self.tools[tool]["constructor"](self)
  590. self.app.info(self.active_tool.start_msg)
  591. else:
  592. self.app.log.debug("%s is NOT checked." % tool)
  593. for t in self.tools:
  594. self.tools[t]["button"].setChecked(False)
  595. self.active_tool = None
  596. def on_canvas_click(self, event):
  597. """
  598. event.x and .y have canvas coordinates
  599. event.xdaya and .ydata have plot coordinates
  600. :param event: Event object dispatched by Matplotlib
  601. :return: None
  602. """
  603. if self.active_tool is not None:
  604. # Dispatch event to active_tool
  605. msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  606. self.app.info(msg)
  607. # If it is a shape generating tool
  608. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  609. self.on_shape_complete()
  610. return
  611. if isinstance(self.active_tool, FCSelect):
  612. self.app.log.debug("Replotting after click.")
  613. self.replot()
  614. else:
  615. self.app.log.debug("No active tool to respond to click!")
  616. def on_canvas_move(self, event):
  617. """
  618. event.x and .y have canvas coordinates
  619. event.xdaya and .ydata have plot coordinates
  620. :param event: Event object dispatched by Matplotlib
  621. :return:
  622. """
  623. self.on_canvas_move_effective(event)
  624. return None
  625. # self.move_timer.stop()
  626. #
  627. # if self.active_tool is None:
  628. # return
  629. #
  630. # # Make a function to avoid late evaluation
  631. # def make_callback():
  632. # def f():
  633. # self.on_canvas_move_effective(event)
  634. # return f
  635. # callback = make_callback()
  636. #
  637. # self.move_timer.timeout.connect(callback)
  638. # self.move_timer.start(500) # Stops if aready running
  639. def on_canvas_move_effective(self, event):
  640. """
  641. Is called after timeout on timer set in on_canvas_move.
  642. For details on animating on MPL see:
  643. http://wiki.scipy.org/Cookbook/Matplotlib/Animations
  644. event.x and .y have canvas coordinates
  645. event.xdaya and .ydata have plot coordinates
  646. :param event: Event object dispatched by Matplotlib
  647. :return: None
  648. """
  649. try:
  650. x = float(event.xdata)
  651. y = float(event.ydata)
  652. except TypeError:
  653. return
  654. if self.active_tool is None:
  655. return
  656. ### Snap coordinates
  657. x, y = self.snap(x, y)
  658. ### Utility geometry (animated)
  659. self.canvas.canvas.restore_region(self.canvas.background)
  660. geo = self.active_tool.utility_geometry(data=(x, y))
  661. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  662. # Remove any previous utility shape
  663. self.delete_utility_geometry()
  664. # Add the new utility shape
  665. self.add_shape(geo)
  666. # Efficient plotting for fast animation
  667. #self.canvas.canvas.restore_region(self.canvas.background)
  668. elements = self.plot_shape(geometry=geo.geo,
  669. linespec="b--",
  670. linewidth=1,
  671. animated=True)
  672. for el in elements:
  673. self.axes.draw_artist(el)
  674. #self.canvas.canvas.blit(self.axes.bbox)
  675. # Pointer (snapped)
  676. elements = self.axes.plot(x, y, 'bo', animated=True)
  677. for el in elements:
  678. self.axes.draw_artist(el)
  679. self.canvas.canvas.blit(self.axes.bbox)
  680. def on_canvas_key(self, event):
  681. """
  682. event.key has the key.
  683. :param event:
  684. :return:
  685. """
  686. self.key = event.key
  687. ### Finish the current action. Use with tools that do not
  688. ### complete automatically, like a polygon or path.
  689. if event.key == ' ':
  690. if isinstance(self.active_tool, FCShapeTool):
  691. self.active_tool.click(self.snap(event.xdata, event.ydata))
  692. self.active_tool.make()
  693. if self.active_tool.complete:
  694. self.on_shape_complete()
  695. return
  696. ### Abort the current action
  697. if event.key == 'escape':
  698. # TODO: ...?
  699. self.on_tool_select("select")
  700. self.app.info("Cancelled.")
  701. self.delete_utility_geometry()
  702. self.replot()
  703. self.select_btn.setChecked(True)
  704. self.on_tool_select('select')
  705. return
  706. ### Delete selected object
  707. if event.key == '-':
  708. self.delete_selected()
  709. self.replot()
  710. ### Move
  711. if event.key == 'm':
  712. self.move_btn.setChecked(True)
  713. self.on_tool_select('move')
  714. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  715. ### Copy
  716. if event.key == 'c':
  717. self.copy_btn.setChecked(True)
  718. self.on_tool_select('copy')
  719. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  720. ### Snap
  721. if event.key == 'g':
  722. self.grid_snap_btn.trigger()
  723. if event.key == 'k':
  724. self.corner_snap_btn.trigger()
  725. ### Propagate to tool
  726. response = self.active_tool.on_key(event.key)
  727. if response is not None:
  728. self.app.info(response)
  729. def on_canvas_key_release(self, event):
  730. self.key = None
  731. def on_delete_btn(self):
  732. self.delete_selected()
  733. self.replot()
  734. def get_selected(self):
  735. """
  736. Returns list of shapes that are selected in the editor.
  737. :return: List of shapes.
  738. """
  739. #return [shape for shape in self.shape_buffer if shape["selected"]]
  740. return self.selected
  741. def delete_selected(self):
  742. tempref = [s for s in self.selected]
  743. for shape in tempref:
  744. self.delete_shape(shape)
  745. self.selected = []
  746. def plot_shape(self, geometry=None, linespec='b-', linewidth=1, animated=False):
  747. """
  748. Plots a geometric object or list of objects without rendering. Plotted objects
  749. are returned as a list. This allows for efficient/animated rendering.
  750. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  751. :param linespec: Matplotlib linespec string.
  752. :param linewidth: Width of lines in # of pixels.
  753. :param animated: If geometry is to be animated. (See MPL plot())
  754. :return: List of plotted elements.
  755. """
  756. plot_elements = []
  757. if geometry is None:
  758. geometry = self.active_tool.geometry
  759. try:
  760. for geo in geometry:
  761. plot_elements += self.plot_shape(geometry=geo,
  762. linespec=linespec,
  763. linewidth=linewidth,
  764. animated=animated)
  765. ## Non-iterable
  766. except TypeError:
  767. ## DrawToolShape
  768. if isinstance(geometry, DrawToolShape):
  769. plot_elements += self.plot_shape(geometry=geometry.geo,
  770. linespec=linespec,
  771. linewidth=linewidth,
  772. animated=animated)
  773. ## Polygon: Dscend into exterior and each interior.
  774. if type(geometry) == Polygon:
  775. plot_elements += self.plot_shape(geometry=geometry.exterior,
  776. linespec=linespec,
  777. linewidth=linewidth,
  778. animated=animated)
  779. plot_elements += self.plot_shape(geometry=geometry.interiors,
  780. linespec=linespec,
  781. linewidth=linewidth,
  782. animated=animated)
  783. if type(geometry) == LineString or type(geometry) == LinearRing:
  784. x, y = geometry.coords.xy
  785. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  786. plot_elements.append(element)
  787. if type(geometry) == Point:
  788. x, y = geometry.coords.xy
  789. element, = self.axes.plot(x, y, 'bo', linewidth=linewidth, animated=animated)
  790. plot_elements.append(element)
  791. return plot_elements
  792. def plot_all(self):
  793. """
  794. Plots all shapes in the editor.
  795. Clears the axes, plots, and call self.canvas.auto_adjust_axes.
  796. :return: None
  797. :rtype: None
  798. """
  799. self.app.log.debug("plot_all()")
  800. self.axes.cla()
  801. for shape in self.storage.get_objects():
  802. if shape.geo is None: # TODO: This shouldn't have happened
  803. continue
  804. if shape in self.selected:
  805. self.plot_shape(geometry=shape.geo, linespec='k-', linewidth=2)
  806. continue
  807. self.plot_shape(geometry=shape.geo)
  808. for shape in self.utility:
  809. self.plot_shape(geometry=shape.geo, linespec='k--', linewidth=1)
  810. continue
  811. self.canvas.auto_adjust_axes()
  812. def on_shape_complete(self):
  813. self.app.log.debug("on_shape_complete()")
  814. # Add shape
  815. self.add_shape(self.active_tool.geometry)
  816. # Remove any utility shapes
  817. self.delete_utility_geometry()
  818. # Replot and reset tool.
  819. self.replot()
  820. self.active_tool = type(self.active_tool)(self)
  821. def delete_shape(self, shape):
  822. if shape in self.utility:
  823. self.utility.remove(shape)
  824. return
  825. self.storage.remove(shape)
  826. if shape in self.selected:
  827. self.selected.remove(shape)
  828. def replot(self):
  829. self.axes = self.canvas.new_axes("draw")
  830. self.plot_all()
  831. @staticmethod
  832. def make_storage():
  833. ## Shape storage.
  834. storage = FlatCAMRTreeStorage()
  835. storage.get_points = DrawToolShape.get_pts
  836. return storage
  837. def set_selected(self, shape):
  838. # Remove and add to the end.
  839. if shape in self.selected:
  840. self.selected.remove(shape)
  841. self.selected.append(shape)
  842. def set_unselected(self, shape):
  843. if shape in self.selected:
  844. self.selected.remove(shape)
  845. def snap(self, x, y):
  846. """
  847. Adjusts coordinates to snap settings.
  848. :param x: Input coordinate X
  849. :param y: Input coordinate Y
  850. :return: Snapped (x, y)
  851. """
  852. snap_x, snap_y = (x, y)
  853. snap_distance = Inf
  854. ### Object (corner?) snap
  855. ### No need for the objects, just the coordinates
  856. ### in the index.
  857. if self.options["corner_snap"]:
  858. try:
  859. nearest_pt, shape = self.storage.nearest((x, y))
  860. nearest_pt_distance = distance((x, y), nearest_pt)
  861. if nearest_pt_distance <= self.options["snap_max"]:
  862. snap_distance = nearest_pt_distance
  863. snap_x, snap_y = nearest_pt
  864. except (StopIteration, AssertionError):
  865. pass
  866. ### Grid snap
  867. if self.options["grid_snap"]:
  868. if self.options["snap-x"] != 0:
  869. snap_x_ = round(x / self.options["snap-x"]) * self.options['snap-x']
  870. else:
  871. snap_x_ = x
  872. if self.options["snap-y"] != 0:
  873. snap_y_ = round(y / self.options["snap-y"]) * self.options['snap-y']
  874. else:
  875. snap_y_ = y
  876. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  877. if nearest_grid_distance < snap_distance:
  878. snap_x, snap_y = (snap_x_, snap_y_)
  879. return snap_x, snap_y
  880. def update_fcgeometry(self, fcgeometry):
  881. """
  882. Transfers the drawing tool shape buffer to the selected geometry
  883. object. The geometry already in the object are removed.
  884. :param fcgeometry: FlatCAMGeometry
  885. :return: None
  886. """
  887. fcgeometry.solid_geometry = []
  888. #for shape in self.shape_buffer:
  889. for shape in self.storage.get_objects():
  890. fcgeometry.solid_geometry.append(shape.geo)
  891. def union(self):
  892. """
  893. Makes union of selected polygons. Original polygons
  894. are deleted.
  895. :return: None.
  896. """
  897. results = cascaded_union([t.geo for t in self.get_selected()])
  898. # Delete originals.
  899. for_deletion = [s for s in self.get_selected()]
  900. for shape in for_deletion:
  901. self.delete_shape(shape)
  902. # Selected geometry is now gone!
  903. self.selected = []
  904. self.add_shape(DrawToolShape(results))
  905. self.replot()
  906. def subtract(self):
  907. selected = self.get_selected()
  908. tools = selected[1:]
  909. toolgeo = cascaded_union([shp.geo for shp in tools])
  910. result = selected[0].geo.difference(toolgeo)
  911. self.delete_shape(selected[0])
  912. self.add_shape(DrawToolShape(result))
  913. self.replot()
  914. def distance(pt1, pt2):
  915. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  916. def mag(vec):
  917. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  918. def poly2rings(poly):
  919. return [poly.exterior] + [interior for interior in poly.interiors]