ToolCutOut.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCDoubleSpinner, FCCheckBox, RadioSet, FCComboBox, OptionalInputSection, FCButton, \
  10. FCLabel
  11. from shapely.geometry import box, MultiPolygon, Polygon, LineString, LinearRing, MultiLineString
  12. from shapely.ops import cascaded_union, unary_union, linemerge
  13. import shapely.affinity as affinity
  14. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  15. from numpy import Inf
  16. from copy import deepcopy
  17. import math
  18. import logging
  19. import gettext
  20. import appTranslation as fcTranslate
  21. import builtins
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. settings = QtCore.QSettings("Open Source", "FlatCAM")
  27. if settings.contains("machinist"):
  28. machinist_setting = settings.value('machinist', type=int)
  29. else:
  30. machinist_setting = 0
  31. class CutOut(AppTool):
  32. def __init__(self, app):
  33. AppTool.__init__(self, app)
  34. self.app = app
  35. self.canvas = app.plotcanvas
  36. self.decimals = self.app.decimals
  37. # #############################################################################
  38. # ######################### Tool GUI ##########################################
  39. # #############################################################################
  40. self.ui = CutoutUI(layout=self.layout, app=self.app)
  41. self.toolName = self.ui.toolName
  42. self.cutting_gapsize = 0.0
  43. self.cutting_dia = 0.0
  44. # true if we want to repeat the gap without clicking again on the button
  45. self.repeat_gap = False
  46. self.flat_geometry = []
  47. # this is the Geometry object generated in this class to be used for adding manual gaps
  48. self.man_cutout_obj = None
  49. # if mouse is dragging set the object True
  50. self.mouse_is_dragging = False
  51. # if mouse events are bound to local methods
  52. self.mouse_events_connected = False
  53. # event handlers references
  54. self.kp = None
  55. self.mm = None
  56. self.mr = None
  57. # hold the mouse position here
  58. self.x_pos = None
  59. self.y_pos = None
  60. # store the default data for the resulting Geometry Object
  61. self.default_data = {}
  62. # store the current cursor type to be restored after manual geo
  63. self.old_cursor_type = self.app.defaults["global_cursor_type"]
  64. # store the current selection shape status to be restored after manual geo
  65. self.old_selection_state = self.app.defaults['global_selection_shape']
  66. # store original geometry for manual cutout
  67. self.manual_solid_geo = None
  68. # Signals
  69. self.ui.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  70. self.ui.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  71. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  72. self.ui.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  73. self.ui.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  74. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  75. def on_type_obj_changed(self, val):
  76. obj_type = {'grb': 0, 'geo': 2}[val]
  77. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  78. self.ui.obj_combo.setCurrentIndex(0)
  79. self.ui.obj_combo.obj_type = {"grb": "Gerber", "geo": "Geometry"}[val]
  80. if val == 'grb':
  81. self.ui.convex_box_label.setDisabled(False)
  82. self.ui.convex_box_cb.setDisabled(False)
  83. else:
  84. self.ui.convex_box_label.setDisabled(True)
  85. self.ui.convex_box_cb.setDisabled(True)
  86. def run(self, toggle=True):
  87. self.app.defaults.report_usage("ToolCutOut()")
  88. if toggle:
  89. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  90. if self.app.ui.splitter.sizes()[0] == 0:
  91. self.app.ui.splitter.setSizes([1, 1])
  92. else:
  93. try:
  94. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  95. # if tab is populated with the tool but it does not have the focus, focus on it
  96. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  97. # focus on Tool Tab
  98. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  99. else:
  100. self.app.ui.splitter.setSizes([0, 1])
  101. except AttributeError:
  102. pass
  103. else:
  104. if self.app.ui.splitter.sizes()[0] == 0:
  105. self.app.ui.splitter.setSizes([1, 1])
  106. AppTool.run(self)
  107. self.set_tool_ui()
  108. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  109. def install(self, icon=None, separator=None, **kwargs):
  110. AppTool.install(self, icon, separator, shortcut='Alt+X', **kwargs)
  111. def set_tool_ui(self):
  112. self.reset_fields()
  113. self.ui.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  114. self.ui.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  115. self.ui.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  116. self.ui.cutz_entry.set_value(float(self.app.defaults["tools_cutout_z"]))
  117. self.ui.mpass_cb.set_value(float(self.app.defaults["tools_cutout_mdepth"]))
  118. self.ui.maxdepth_entry.set_value(float(self.app.defaults["tools_cutout_depthperpass"]))
  119. self.ui.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  120. self.ui.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  121. self.ui.convex_box_cb.set_value(self.app.defaults['tools_cutout_convexshape'])
  122. self.ui.big_cursor_cb.set_value(self.app.defaults['tools_cutout_big_cursor'])
  123. self.ui.gaptype_radio.set_value('b')
  124. # use the current selected object and make it visible in the object combobox
  125. sel_list = self.app.collection.get_selected()
  126. if len(sel_list) == 1:
  127. active = self.app.collection.get_active()
  128. kind = active.kind
  129. if kind == 'gerber':
  130. self.ui.type_obj_radio.set_value('grb')
  131. else:
  132. self.ui.type_obj_radio.set_value('geo')
  133. # run those once so the obj_type attribute is updated for the FCComboboxes
  134. # so the last loaded object is displayed
  135. if kind == 'gerber':
  136. self.on_type_obj_changed(val='grb')
  137. else:
  138. self.on_type_obj_changed(val='geo')
  139. self.ui.obj_combo.set_value(active.options['name'])
  140. else:
  141. kind = 'gerber'
  142. self.ui.type_obj_radio.set_value('grb')
  143. # run those once so the obj_type attribute is updated for the FCComboboxes
  144. # so the last loaded object is displayed
  145. if kind == 'gerber':
  146. self.on_type_obj_changed(val='grb')
  147. else:
  148. self.on_type_obj_changed(val='geo')
  149. # self.type_obj_radio.set_value('grb')
  150. self.default_data.update({
  151. "plot": True,
  152. "cutz": float(self.app.defaults["geometry_cutz"]),
  153. "multidepth": self.app.defaults["geometry_multidepth"],
  154. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  155. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  156. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  157. "travelz": float(self.app.defaults["geometry_travelz"]),
  158. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  159. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  160. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  161. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  162. "dwell": self.app.defaults["geometry_dwell"],
  163. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  164. "spindledir": self.app.defaults["geometry_spindledir"],
  165. "ppname_g": self.app.defaults["geometry_ppname_g"],
  166. "extracut": self.app.defaults["geometry_extracut"],
  167. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  168. "toolchange": self.app.defaults["geometry_toolchange"],
  169. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  170. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  171. "startz": self.app.defaults["geometry_startz"],
  172. "endz": float(self.app.defaults["geometry_endz"]),
  173. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  174. "area_shape": self.app.defaults["geometry_area_shape"],
  175. "area_strategy": self.app.defaults["geometry_area_strategy"],
  176. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  177. "optimization_type": self.app.defaults["geometry_optimization_type"],
  178. # NCC
  179. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  180. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"],
  181. "tools_nccoverlap": float(self.app.defaults["tools_nccoverlap"]),
  182. "tools_nccmargin": float(self.app.defaults["tools_nccmargin"]),
  183. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  184. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  185. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  186. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  187. "tools_ncc_offset_value": float(self.app.defaults["tools_ncc_offset_value"]),
  188. # Paint
  189. "tools_paintoverlap": float(self.app.defaults["tools_paintoverlap"]),
  190. "tools_paintoffset": float(self.app.defaults["tools_paintoffset"]),
  191. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  192. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  193. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  194. # Isolation Tool
  195. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  196. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  197. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  198. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  199. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  200. })
  201. def on_freeform_cutout(self):
  202. log.debug("Cutout.on_freeform_cutout() was launched ...")
  203. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  204. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  205. # obj_.subtract_polygon(pts)
  206. name = self.ui.obj_combo.currentText()
  207. # Get source object.
  208. try:
  209. cutout_obj = self.app.collection.get_by_name(str(name))
  210. except Exception as e:
  211. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  212. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  213. return "Could not retrieve object: %s" % name
  214. if cutout_obj is None:
  215. self.app.inform.emit('[ERROR_NOTCL] %s' %
  216. _("There is no object selected for Cutout.\nSelect one and try again."))
  217. return
  218. dia = float(self.ui.dia.get_value())
  219. if 0 in {dia}:
  220. self.app.inform.emit('[WARNING_NOTCL] %s' %
  221. _("Tool Diameter is zero value. Change it to a positive real number."))
  222. return "Tool Diameter is zero value. Change it to a positive real number."
  223. try:
  224. kind = self.ui.obj_kind_combo.get_value()
  225. except ValueError:
  226. return
  227. margin = float(self.ui.margin.get_value())
  228. gapsize = float(self.ui.gapsize.get_value())
  229. try:
  230. gaps = self.ui.gaps.get_value()
  231. except TypeError:
  232. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  233. return
  234. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  235. self.app.inform.emit('[WARNING_NOTCL] %s' %
  236. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  237. "Fill in a correct value and retry. "))
  238. return
  239. if cutout_obj.multigeo is True:
  240. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  241. "Optionally, this Multi-geo Geometry can be converted to "
  242. "Single-geo Geometry,\n"
  243. "and after that perform Cutout."))
  244. return
  245. convex_box = self.ui.convex_box_cb.get_value()
  246. gapsize = gapsize / 2 + (dia / 2)
  247. def geo_init(geo_obj, app_obj):
  248. solid_geo = []
  249. gaps_solid_geo = None
  250. if cutout_obj.kind == 'gerber':
  251. if isinstance(cutout_obj.solid_geometry, list):
  252. cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
  253. try:
  254. if convex_box:
  255. object_geo = cutout_obj.solid_geometry.convex_hull
  256. else:
  257. object_geo = cutout_obj.solid_geometry
  258. except Exception as err:
  259. log.debug("CutOut.on_freeform_cutout().geo_init() --> %s" % str(err))
  260. object_geo = cutout_obj.solid_geometry
  261. else:
  262. object_geo = cutout_obj.solid_geometry
  263. def cutout_handler(geom):
  264. proc_geometry = []
  265. rest_geometry = []
  266. r_temp_geo = []
  267. initial_geo = deepcopy(geom)
  268. # Get min and max data for each object as we just cut rectangles across X or Y
  269. xxmin, yymin, xxmax, yymax = CutOut.recursive_bounds(geom)
  270. px = 0.5 * (xxmin + xxmax) + margin
  271. py = 0.5 * (yymin + yymax) + margin
  272. lenx = (xxmax - xxmin) + (margin * 2)
  273. leny = (yymax - yymin) + (margin * 2)
  274. if gaps == 'None':
  275. pass
  276. else:
  277. if gaps == '8' or gaps == '2LR':
  278. points = (
  279. xxmin - gapsize, # botleft_x
  280. py - gapsize + leny / 4, # botleft_y
  281. xxmax + gapsize, # topright_x
  282. py + gapsize + leny / 4 # topright_y
  283. )
  284. geom = self.subtract_poly_from_geo(geom, points)
  285. r_temp_geo.append(
  286. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  287. )
  288. points = (
  289. xxmin - gapsize,
  290. py - gapsize - leny / 4,
  291. xxmax + gapsize,
  292. py + gapsize - leny / 4
  293. )
  294. geom = self.subtract_poly_from_geo(geom, points)
  295. r_temp_geo.append(
  296. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  297. )
  298. if gaps == '8' or gaps == '2TB':
  299. points = (
  300. px - gapsize + lenx / 4,
  301. yymin - gapsize,
  302. px + gapsize + lenx / 4,
  303. yymax + gapsize
  304. )
  305. geom = self.subtract_poly_from_geo(geom, points)
  306. r_temp_geo.append(
  307. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  308. )
  309. points = (
  310. px - gapsize - lenx / 4,
  311. yymin - gapsize,
  312. px + gapsize - lenx / 4,
  313. yymax + gapsize
  314. )
  315. geom = self.subtract_poly_from_geo(geom, points)
  316. r_temp_geo.append(
  317. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  318. )
  319. if gaps == '4' or gaps == 'LR':
  320. points = (
  321. xxmin - gapsize,
  322. py - gapsize,
  323. xxmax + gapsize,
  324. py + gapsize
  325. )
  326. geom = self.subtract_poly_from_geo(geom, points)
  327. r_temp_geo.append(
  328. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  329. )
  330. if gaps == '4' or gaps == 'TB':
  331. points = (
  332. px - gapsize,
  333. yymin - gapsize,
  334. px + gapsize,
  335. yymax + gapsize
  336. )
  337. geom = self.subtract_poly_from_geo(geom, points)
  338. r_temp_geo.append(
  339. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  340. )
  341. try:
  342. for g in geom:
  343. if g and not g.is_empty:
  344. proc_geometry.append(g)
  345. except TypeError:
  346. if geom and not geom.is_empty:
  347. proc_geometry.append(geom)
  348. r_temp_geo = CutOut.flatten(r_temp_geo)
  349. for g in r_temp_geo:
  350. if g and not g.is_empty:
  351. rest_geometry.append(g)
  352. return proc_geometry, rest_geometry
  353. if kind == 'single':
  354. object_geo = unary_union(object_geo)
  355. # for geo in object_geo:
  356. if cutout_obj.kind == 'gerber':
  357. if isinstance(object_geo, MultiPolygon):
  358. x0, y0, x1, y1 = object_geo.bounds
  359. object_geo = box(x0, y0, x1, y1)
  360. if margin >= 0:
  361. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  362. else:
  363. geo_buf = object_geo.buffer(margin - abs(dia / 2))
  364. geo = geo_buf.exterior
  365. else:
  366. geo = object_geo
  367. solid_geo, rest_geo = cutout_handler(geom=geo)
  368. if self.ui.gaptype_radio.get_value() == 'bt' and self.ui.thin_depth_entry.get_value() > 0:
  369. gaps_solid_geo = rest_geo
  370. else:
  371. try:
  372. __ = iter(object_geo)
  373. except TypeError:
  374. object_geo = [object_geo]
  375. for geom_struct in object_geo:
  376. if cutout_obj.kind == 'gerber':
  377. if margin >= 0:
  378. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  379. else:
  380. geom_struct_buff = geom_struct.buffer(-margin + abs(dia / 2))
  381. geom_struct = geom_struct_buff.interiors
  382. c_geo, r_geo = cutout_handler(geom=geom_struct)
  383. solid_geo += c_geo
  384. if self.ui.gaptype_radio.get_value() == 'bt' and self.ui.thin_depth_entry.get_value() > 0:
  385. gaps_solid_geo += r_geo
  386. if not solid_geo:
  387. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  388. return "fail"
  389. solid_geo = linemerge(solid_geo)
  390. geo_obj.solid_geometry = deepcopy(solid_geo)
  391. xmin, ymin, xmax, ymax = CutOut.recursive_bounds(geo_obj.solid_geometry)
  392. geo_obj.options['xmin'] = xmin
  393. geo_obj.options['ymin'] = ymin
  394. geo_obj.options['xmax'] = xmax
  395. geo_obj.options['ymax'] = ymax
  396. geo_obj.options['cnctooldia'] = str(dia)
  397. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  398. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  399. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  400. geo_obj.tools.update({
  401. 1: {
  402. 'tooldia': str(dia),
  403. 'offset': 'Path',
  404. 'offset_value': 0.0,
  405. 'type': _('Rough'),
  406. 'tool_type': 'C1',
  407. 'data': deepcopy(self.default_data),
  408. 'solid_geometry': geo_obj.solid_geometry
  409. }
  410. })
  411. geo_obj.multigeo = True
  412. geo_obj.tools[1]['data']['name'] = outname
  413. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  414. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  415. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  416. if gaps_solid_geo is not None:
  417. geo_obj.tools.update({
  418. 9999: {
  419. 'tooldia': str(dia),
  420. 'offset': 'Path',
  421. 'offset_value': 0.0,
  422. 'type': _('Rough'),
  423. 'tool_type': 'C1',
  424. 'data': deepcopy(self.default_data),
  425. 'solid_geometry': gaps_solid_geo
  426. }
  427. })
  428. geo_obj.tools[9999]['data']['name'] = outname
  429. geo_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  430. geo_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  431. geo_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  432. # plot this tool in a different color
  433. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  434. outname = cutout_obj.options["name"] + "_cutout"
  435. ret = self.app.app_obj.new_object('geometry', outname, geo_init)
  436. if ret == 'fail':
  437. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  438. return
  439. # cutout_obj.plot(plot_tool=1)
  440. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  441. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  442. self.app.should_we_save = True
  443. def on_rectangular_cutout(self):
  444. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  445. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  446. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  447. # obj_.subtract_polygon(pts)
  448. name = self.ui.obj_combo.currentText()
  449. # Get source object.
  450. try:
  451. cutout_obj = self.app.collection.get_by_name(str(name))
  452. except Exception as e:
  453. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  454. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  455. return "Could not retrieve object: %s" % name
  456. if cutout_obj is None:
  457. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  458. dia = float(self.ui.dia.get_value())
  459. if 0 in {dia}:
  460. self.app.inform.emit('[ERROR_NOTCL] %s' %
  461. _("Tool Diameter is zero value. Change it to a positive real number."))
  462. return "Tool Diameter is zero value. Change it to a positive real number."
  463. try:
  464. kind = self.ui.obj_kind_combo.get_value()
  465. except ValueError:
  466. return
  467. margin = float(self.ui.margin.get_value())
  468. gapsize = float(self.ui.gapsize.get_value())
  469. try:
  470. gaps = self.ui.gaps.get_value()
  471. except TypeError:
  472. self.app.inform.emit('[WARNING_NOTCL] %s' %
  473. _("Number of gaps value is missing. Add it and retry."))
  474. return
  475. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  476. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  477. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  478. "Fill in a correct value and retry. "))
  479. return
  480. if cutout_obj.multigeo is True:
  481. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  482. "Optionally, this Multi-geo Geometry can be converted to "
  483. "Single-geo Geometry,\n"
  484. "and after that perform Cutout."))
  485. return
  486. # Get min and max data for each object as we just cut rectangles across X or Y
  487. gapsize = gapsize / 2 + (dia / 2)
  488. def geo_init(geo_obj, app_obj):
  489. solid_geo = []
  490. gaps_solid_geo = None
  491. object_geo = cutout_obj.solid_geometry
  492. def cutout_rect_handler(geom):
  493. proc_geometry = []
  494. px = 0.5 * (xmin + xmax) + margin
  495. py = 0.5 * (ymin + ymax) + margin
  496. lenx = (xmax - xmin) + (margin * 2)
  497. leny = (ymax - ymin) + (margin * 2)
  498. if gaps == 'None':
  499. pass
  500. else:
  501. if gaps == '8' or gaps == '2LR':
  502. points = (
  503. xmin - gapsize, # botleft_x
  504. py - gapsize + leny / 4, # botleft_y
  505. xmax + gapsize, # topright_x
  506. py + gapsize + leny / 4 # topright_y
  507. )
  508. geom = self.subtract_poly_from_geo(geom, points)
  509. points = (
  510. xmin - gapsize,
  511. py - gapsize - leny / 4,
  512. xmax + gapsize,
  513. py + gapsize - leny / 4
  514. )
  515. geom = self.subtract_poly_from_geo(geom, points)
  516. if gaps == '8' or gaps == '2TB':
  517. points = (
  518. px - gapsize + lenx / 4,
  519. ymin - gapsize,
  520. px + gapsize + lenx / 4,
  521. ymax + gapsize
  522. )
  523. geom = self.subtract_poly_from_geo(geom, points)
  524. points = (
  525. px - gapsize - lenx / 4,
  526. ymin - gapsize,
  527. px + gapsize - lenx / 4,
  528. ymax + gapsize
  529. )
  530. geom = self.subtract_poly_from_geo(geom, points)
  531. if gaps == '4' or gaps == 'LR':
  532. points = (
  533. xmin - gapsize,
  534. py - gapsize,
  535. xmax + gapsize,
  536. py + gapsize
  537. )
  538. geom = self.subtract_poly_from_geo(geom, points)
  539. if gaps == '4' or gaps == 'TB':
  540. points = (
  541. px - gapsize,
  542. ymin - gapsize,
  543. px + gapsize,
  544. ymax + gapsize
  545. )
  546. geom = self.subtract_poly_from_geo(geom, points)
  547. try:
  548. for g in geom:
  549. proc_geometry.append(g)
  550. except TypeError:
  551. proc_geometry.append(geom)
  552. return proc_geometry
  553. if kind == 'single':
  554. # fuse the lines
  555. object_geo = unary_union(object_geo)
  556. xmin, ymin, xmax, ymax = object_geo.bounds
  557. geo = box(xmin, ymin, xmax, ymax)
  558. # if Gerber create a buffer at a distance
  559. # if Geometry then cut through the geometry
  560. if cutout_obj.kind == 'gerber':
  561. if margin >= 0:
  562. geo = geo.buffer(margin + abs(dia / 2))
  563. else:
  564. geo = geo.buffer(margin - abs(dia / 2))
  565. solid_geo = cutout_rect_handler(geom=geo)
  566. if self.ui.gaptype_radio.get_value() == 'bt' and self.ui.thin_depth_entry.get_value() > 0:
  567. gaps_solid_geo = self.subtract_geo(geo, solid_geo)
  568. else:
  569. if cutout_obj.kind == 'geometry':
  570. try:
  571. __ = iter(object_geo)
  572. except TypeError:
  573. object_geo = [object_geo]
  574. for geom_struct in object_geo:
  575. geom_struct = unary_union(geom_struct)
  576. xmin, ymin, xmax, ymax = geom_struct.bounds
  577. geom_struct = box(xmin, ymin, xmax, ymax)
  578. c_geo = cutout_rect_handler(geom=geom_struct)
  579. solid_geo += c_geo
  580. if self.ui.gaptype_radio.get_value() == 'bt' and self.ui.thin_depth_entry.get_value() > 0:
  581. try:
  582. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  583. except TypeError:
  584. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  585. elif cutout_obj.kind == 'gerber' and margin >= 0:
  586. try:
  587. __ = iter(object_geo)
  588. except TypeError:
  589. object_geo = [object_geo]
  590. for geom_struct in object_geo:
  591. geom_struct = unary_union(geom_struct)
  592. xmin, ymin, xmax, ymax = geom_struct.bounds
  593. geom_struct = box(xmin, ymin, xmax, ymax)
  594. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  595. c_geo = cutout_rect_handler(geom=geom_struct)
  596. solid_geo += c_geo
  597. if self.ui.gaptype_radio.get_value() == 'bt' and self.ui.thin_depth_entry.get_value() > 0:
  598. try:
  599. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  600. except TypeError:
  601. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  602. elif cutout_obj.kind == 'gerber' and margin < 0:
  603. app_obj.inform.emit(
  604. '[WARNING_NOTCL] %s' % _("Rectangular cutout with negative margin is not possible."))
  605. return "fail"
  606. geo_obj.options['cnctooldia'] = str(dia)
  607. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  608. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  609. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  610. if not solid_geo:
  611. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  612. return "fail"
  613. solid_geo = linemerge(solid_geo)
  614. geo_obj.solid_geometry = deepcopy(solid_geo)
  615. geo_obj.tools.update({
  616. 1: {
  617. 'tooldia': str(dia),
  618. 'offset': 'Path',
  619. 'offset_value': 0.0,
  620. 'type': _('Rough'),
  621. 'tool_type': 'C1',
  622. 'data': deepcopy(self.default_data),
  623. 'solid_geometry': geo_obj.solid_geometry
  624. }
  625. })
  626. geo_obj.multigeo = True
  627. geo_obj.tools[1]['data']['name'] = outname
  628. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  629. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  630. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  631. if gaps_solid_geo is not None:
  632. geo_obj.tools.update({
  633. 9999: {
  634. 'tooldia': str(dia),
  635. 'offset': 'Path',
  636. 'offset_value': 0.0,
  637. 'type': _('Rough'),
  638. 'tool_type': 'C1',
  639. 'data': deepcopy(self.default_data),
  640. 'solid_geometry': gaps_solid_geo
  641. }
  642. })
  643. geo_obj.tools[9999]['data']['name'] = outname
  644. geo_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  645. geo_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  646. geo_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  647. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  648. outname = cutout_obj.options["name"] + "_cutout"
  649. ret = self.app.app_obj.new_object('geometry', outname, geo_init)
  650. if ret != 'fail':
  651. # cutout_obj.plot()
  652. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  653. else:
  654. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  655. return
  656. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  657. self.app.should_we_save = True
  658. def on_manual_gap_click(self):
  659. name = self.ui.man_object_combo.currentText()
  660. # Get source object.
  661. try:
  662. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  663. except Exception as e:
  664. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  665. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  666. return
  667. if self.man_cutout_obj is None:
  668. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  669. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  670. return
  671. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  672. self.app.geo_editor.tool_shape.enabled = True
  673. self.manual_solid_geo = deepcopy(self.flatten(self.man_cutout_obj.solid_geometry))
  674. self.cutting_dia = float(self.ui.dia.get_value())
  675. if 0 in {self.cutting_dia}:
  676. self.app.inform.emit('[ERROR_NOTCL] %s' %
  677. _("Tool Diameter is zero value. Change it to a positive real number."))
  678. return
  679. self.cutting_gapsize = float(self.ui.gapsize.get_value())
  680. name = self.ui.man_object_combo.currentText()
  681. # Get Geometry source object to be used as target for Manual adding Gaps
  682. try:
  683. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  684. except Exception as e:
  685. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  686. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  687. return
  688. if self.app.is_legacy is False:
  689. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  690. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  691. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  692. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  693. else:
  694. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  695. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  696. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  697. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  698. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  699. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  700. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  701. self.mouse_events_connected = True
  702. if self.ui.big_cursor_cb.get_value():
  703. self.old_cursor_type = self.app.defaults["global_cursor_type"]
  704. self.app.on_cursor_type(val="big")
  705. self.app.defaults['global_selection_shape'] = False
  706. def on_manual_cutout(self, click_pos):
  707. if self.man_cutout_obj is None:
  708. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  709. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  710. return
  711. # use the snapped position as reference
  712. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  713. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  714. gaps_solid_geo = None
  715. if self.ui.gaptype_radio.get_value() == 'bt' and self.ui.thin_depth_entry.get_value() > 0:
  716. gaps_solid_geo = self.intersect_geo(self.manual_solid_geo, cut_poly)
  717. # first subtract geometry for the total solid_geometry
  718. new_solid_geometry = CutOut.subtract_geo(self.man_cutout_obj.solid_geometry, cut_poly)
  719. new_solid_geometry = linemerge(new_solid_geometry)
  720. self.man_cutout_obj.solid_geometry = new_solid_geometry
  721. # then do it or each tool in the manual cutout Geometry object
  722. try:
  723. self.man_cutout_obj.tools[1]['solid_geometry'] = new_solid_geometry
  724. self.man_cutout_obj.multigeo = True
  725. self.man_cutout_obj.tools[1]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  726. self.man_cutout_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  727. self.man_cutout_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  728. self.man_cutout_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  729. except KeyError:
  730. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No tool in the Geometry object."))
  731. return
  732. dia = float(self.ui.dia.get_value())
  733. if gaps_solid_geo:
  734. if 9999 not in self.man_cutout_obj.tools:
  735. self.man_cutout_obj.tools.update({
  736. 9999: {
  737. 'tooldia': str(dia),
  738. 'offset': 'Path',
  739. 'offset_value': 0.0,
  740. 'type': _('Rough'),
  741. 'tool_type': 'C1',
  742. 'data': deepcopy(self.default_data),
  743. 'solid_geometry': [gaps_solid_geo]
  744. }
  745. })
  746. self.man_cutout_obj.tools[9999]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  747. self.man_cutout_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  748. self.man_cutout_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  749. self.man_cutout_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  750. self.man_cutout_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  751. else:
  752. self.man_cutout_obj.tools[9999]['solid_geometry'].append(gaps_solid_geo)
  753. self.man_cutout_obj.plot(plot_tool=1)
  754. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  755. self.app.should_we_save = True
  756. def on_manual_geo(self):
  757. name = self.ui.obj_combo.currentText()
  758. # Get source object.
  759. try:
  760. cutout_obj = self.app.collection.get_by_name(str(name))
  761. except Exception as e:
  762. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  763. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  764. return "Could not retrieve object: %s" % name
  765. if cutout_obj is None:
  766. self.app.inform.emit('[ERROR_NOTCL] %s' %
  767. _("There is no Gerber object selected for Cutout.\n"
  768. "Select one and try again."))
  769. return
  770. if cutout_obj.kind != 'gerber':
  771. self.app.inform.emit('[ERROR_NOTCL] %s' %
  772. _("The selected object has to be of Gerber type.\n"
  773. "Select a Gerber file and try again."))
  774. return
  775. dia = float(self.ui.dia.get_value())
  776. if 0 in {dia}:
  777. self.app.inform.emit('[ERROR_NOTCL] %s' %
  778. _("Tool Diameter is zero value. Change it to a positive real number."))
  779. return
  780. try:
  781. kind = self.ui.obj_kind_combo.get_value()
  782. except ValueError:
  783. return
  784. margin = float(self.ui.margin.get_value())
  785. convex_box = self.ui.convex_box_cb.get_value()
  786. def geo_init(geo_obj, app_obj):
  787. geo_union = unary_union(cutout_obj.solid_geometry)
  788. if convex_box:
  789. geo = geo_union.convex_hull
  790. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  791. elif kind == 'single':
  792. if isinstance(geo_union, Polygon) or \
  793. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  794. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  795. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  796. elif isinstance(geo_union, MultiPolygon):
  797. x0, y0, x1, y1 = geo_union.bounds
  798. geo = box(x0, y0, x1, y1)
  799. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  800. else:
  801. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  802. _("Geometry not supported for cutout"), type(geo_union)))
  803. return 'fail'
  804. else:
  805. geo = geo_union
  806. geo = geo.buffer(margin + abs(dia / 2))
  807. if isinstance(geo, Polygon):
  808. geo_obj.solid_geometry = geo.exterior
  809. elif isinstance(geo, MultiPolygon):
  810. solid_geo = []
  811. for poly in geo:
  812. solid_geo.append(poly.exterior)
  813. geo_obj.solid_geometry = deepcopy(solid_geo)
  814. geo_obj.options['cnctooldia'] = str(dia)
  815. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  816. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  817. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  818. geo_obj.tools.update({
  819. 1: {
  820. 'tooldia': str(dia),
  821. 'offset': 'Path',
  822. 'offset_value': 0.0,
  823. 'type': _('Rough'),
  824. 'tool_type': 'C1',
  825. 'data': self.default_data,
  826. 'solid_geometry': geo_obj.solid_geometry
  827. }
  828. })
  829. geo_obj.multigeo = True
  830. geo_obj.tools[1]['data']['name'] = outname
  831. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  832. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  833. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  834. outname = cutout_obj.options["name"] + "_cutout"
  835. self.app.app_obj.new_object('geometry', outname, geo_init)
  836. def cutting_geo(self, pos):
  837. self.cutting_dia = float(self.ui.dia.get_value())
  838. self.cutting_gapsize = float(self.ui.gapsize.get_value())
  839. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  840. # cutting area definition
  841. orig_x = pos[0]
  842. orig_y = pos[1]
  843. xmin = orig_x - offset
  844. ymin = orig_y - offset
  845. xmax = orig_x + offset
  846. ymax = orig_y + offset
  847. cut_poly = box(xmin, ymin, xmax, ymax)
  848. return cut_poly
  849. # To be called after clicking on the plot.
  850. def on_mouse_click_release(self, event):
  851. if self.app.is_legacy is False:
  852. event_pos = event.pos
  853. # event_is_dragging = event.is_dragging
  854. right_button = 2
  855. else:
  856. event_pos = (event.xdata, event.ydata)
  857. # event_is_dragging = self.app.plotcanvas.is_dragging
  858. right_button = 3
  859. try:
  860. x = float(event_pos[0])
  861. y = float(event_pos[1])
  862. except TypeError:
  863. return
  864. event_pos = (x, y)
  865. # do paint single only for left mouse clicks
  866. if event.button == 1:
  867. self.app.inform.emit(_("Making manual bridge gap..."))
  868. pos = self.app.plotcanvas.translate_coords(event_pos)
  869. self.on_manual_cutout(click_pos=pos)
  870. # if RMB then we exit
  871. elif event.button == right_button and self.mouse_is_dragging is False:
  872. if self.app.is_legacy is False:
  873. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  874. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  875. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  876. else:
  877. self.app.plotcanvas.graph_event_disconnect(self.kp)
  878. self.app.plotcanvas.graph_event_disconnect(self.mm)
  879. self.app.plotcanvas.graph_event_disconnect(self.mr)
  880. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  881. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  882. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  883. self.app.on_mouse_click_release_over_plot)
  884. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  885. # Remove any previous utility shape
  886. self.app.geo_editor.tool_shape.clear(update=True)
  887. self.app.geo_editor.tool_shape.enabled = False
  888. # signal that the mouse events are disconnected from local methods
  889. self.mouse_events_connected = False
  890. if self.ui.big_cursor_cb.get_value():
  891. # restore cursor
  892. self.app.on_cursor_type(val=self.old_cursor_type)
  893. # restore selection
  894. self.app.defaults['global_selection_shape'] = self.old_selection_state
  895. # rebuild the manual Geometry object
  896. self.man_cutout_obj.build_ui()
  897. # plot the final object
  898. self.man_cutout_obj.plot()
  899. def on_mouse_move(self, event):
  900. self.app.on_mouse_move_over_plot(event=event)
  901. if self.app.is_legacy is False:
  902. event_pos = event.pos
  903. event_is_dragging = event.is_dragging
  904. # right_button = 2
  905. else:
  906. event_pos = (event.xdata, event.ydata)
  907. event_is_dragging = self.app.plotcanvas.is_dragging
  908. # right_button = 3
  909. try:
  910. x = float(event_pos[0])
  911. y = float(event_pos[1])
  912. except TypeError:
  913. return
  914. event_pos = (x, y)
  915. pos = self.canvas.translate_coords(event_pos)
  916. event.xdata, event.ydata = pos[0], pos[1]
  917. if event_is_dragging is True:
  918. self.mouse_is_dragging = True
  919. else:
  920. self.mouse_is_dragging = False
  921. try:
  922. x = float(event.xdata)
  923. y = float(event.ydata)
  924. except TypeError:
  925. return
  926. if self.app.grid_status():
  927. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  928. else:
  929. snap_x, snap_y = x, y
  930. self.x_pos, self.y_pos = snap_x, snap_y
  931. # #################################################
  932. # ### This section makes the cutting geo to #######
  933. # ### rotate if it intersects the target geo ######
  934. # #################################################
  935. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  936. man_geo = self.man_cutout_obj.solid_geometry
  937. def get_angle(geo):
  938. line = cut_geo.intersection(geo)
  939. try:
  940. pt1_x = line.coords[0][0]
  941. pt1_y = line.coords[0][1]
  942. pt2_x = line.coords[1][0]
  943. pt2_y = line.coords[1][1]
  944. dx = pt1_x - pt2_x
  945. dy = pt1_y - pt2_y
  946. if dx == 0 or dy == 0:
  947. angle = 0
  948. else:
  949. radian = math.atan(dx / dy)
  950. angle = radian * 180 / math.pi
  951. except Exception:
  952. angle = 0
  953. return angle
  954. try:
  955. rot_angle = 0
  956. for geo_el in man_geo:
  957. if isinstance(geo_el, Polygon):
  958. work_geo = geo_el.exterior
  959. if cut_geo.intersects(work_geo):
  960. rot_angle = get_angle(geo=work_geo)
  961. else:
  962. rot_angle = 0
  963. else:
  964. rot_angle = 0
  965. if cut_geo.intersects(geo_el):
  966. rot_angle = get_angle(geo=geo_el)
  967. if rot_angle != 0:
  968. break
  969. except TypeError:
  970. if isinstance(man_geo, Polygon):
  971. work_geo = man_geo.exterior
  972. if cut_geo.intersects(work_geo):
  973. rot_angle = get_angle(geo=work_geo)
  974. else:
  975. rot_angle = 0
  976. else:
  977. rot_angle = 0
  978. if cut_geo.intersects(man_geo):
  979. rot_angle = get_angle(geo=man_geo)
  980. # rotate only if there is an angle to rotate to
  981. if rot_angle != 0:
  982. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  983. # Remove any previous utility shape
  984. self.app.geo_editor.tool_shape.clear(update=True)
  985. self.draw_utility_geometry(geo=cut_geo)
  986. def draw_utility_geometry(self, geo):
  987. self.app.geo_editor.tool_shape.add(
  988. shape=geo,
  989. color=(self.app.defaults["global_draw_color"] + '80'),
  990. update=False,
  991. layer=0,
  992. tolerance=None)
  993. self.app.geo_editor.tool_shape.redraw()
  994. def on_key_press(self, event):
  995. # events out of the self.app.collection view (it's about Project Tab) are of type int
  996. if type(event) is int:
  997. key = event
  998. # events from the GUI are of type QKeyEvent
  999. elif type(event) == QtGui.QKeyEvent:
  1000. key = event.key()
  1001. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1002. key = event.key
  1003. key = QtGui.QKeySequence(key)
  1004. # check for modifiers
  1005. key_string = key.toString().lower()
  1006. if '+' in key_string:
  1007. mod, __, key_text = key_string.rpartition('+')
  1008. if mod.lower() == 'ctrl':
  1009. # modifiers = QtCore.Qt.ControlModifier
  1010. pass
  1011. elif mod.lower() == 'alt':
  1012. # modifiers = QtCore.Qt.AltModifier
  1013. pass
  1014. elif mod.lower() == 'shift':
  1015. # modifiers = QtCore.Qt.ShiftModifier
  1016. pass
  1017. else:
  1018. # modifiers = QtCore.Qt.NoModifier
  1019. pass
  1020. key = QtGui.QKeySequence(key_text)
  1021. # events from Vispy are of type KeyEvent
  1022. else:
  1023. key = event.key
  1024. # Escape = Deselect All
  1025. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1026. if self.mouse_events_connected is True:
  1027. self.mouse_events_connected = False
  1028. if self.app.is_legacy is False:
  1029. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1030. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1031. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1032. else:
  1033. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1034. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1035. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1036. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1037. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1038. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1039. self.app.on_mouse_click_release_over_plot)
  1040. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1041. if self.ui.big_cursor_cb.get_value():
  1042. # restore cursor
  1043. self.app.on_cursor_type(val=self.old_cursor_type)
  1044. # restore selection
  1045. self.app.defaults['global_selection_shape'] = self.old_selection_state
  1046. # Remove any previous utility shape
  1047. self.app.geo_editor.tool_shape.clear(update=True)
  1048. self.app.geo_editor.tool_shape.enabled = False
  1049. # Grid toggle
  1050. if key == QtCore.Qt.Key_G or key == 'G':
  1051. self.app.ui.grid_snap_btn.trigger()
  1052. # Jump to coords
  1053. if key == QtCore.Qt.Key_J or key == 'J':
  1054. l_x, l_y = self.app.on_jump_to()
  1055. self.app.geo_editor.tool_shape.clear(update=True)
  1056. geo = self.cutting_geo(pos=(l_x, l_y))
  1057. self.draw_utility_geometry(geo=geo)
  1058. @staticmethod
  1059. def subtract_poly_from_geo(solid_geo, pts):
  1060. """
  1061. Subtract polygon made from points from the given object.
  1062. This only operates on the paths in the original geometry,
  1063. i.e. it converts polygons into paths.
  1064. :param solid_geo: Geometry from which to subtract.
  1065. :param pts: a tuple of coordinates in format (x0, y0, x1, y1)
  1066. :type pts: tuple
  1067. x0: x coord for lower left vertex of the polygon.
  1068. y0: y coord for lower left vertex of the polygon.
  1069. x1: x coord for upper right vertex of the polygon.
  1070. y1: y coord for upper right vertex of the polygon.
  1071. :return: none
  1072. """
  1073. x0 = pts[0]
  1074. y0 = pts[1]
  1075. x1 = pts[2]
  1076. y1 = pts[3]
  1077. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1078. # pathonly should be always True, otherwise polygons are not subtracted
  1079. flat_geometry = CutOut.flatten(geometry=solid_geo)
  1080. log.debug("%d paths" % len(flat_geometry))
  1081. polygon = Polygon(points)
  1082. toolgeo = cascaded_union(polygon)
  1083. diffs = []
  1084. for target in flat_geometry:
  1085. if type(target) == LineString or type(target) == LinearRing:
  1086. diffs.append(target.difference(toolgeo))
  1087. else:
  1088. log.warning("Not implemented.")
  1089. return unary_union(diffs)
  1090. @staticmethod
  1091. def flatten(geometry):
  1092. """
  1093. Creates a list of non-iterable linear geometry objects.
  1094. Polygons are expanded into its exterior and interiors.
  1095. Results are placed in self.flat_geometry
  1096. :param geometry: Shapely type or list or list of list of such.
  1097. """
  1098. flat_geo = []
  1099. try:
  1100. for geo in geometry:
  1101. if geo:
  1102. flat_geo += CutOut.flatten(geometry=geo)
  1103. except TypeError:
  1104. if isinstance(geometry, Polygon) and not geometry.is_empty:
  1105. flat_geo.append(geometry.exterior)
  1106. CutOut.flatten(geometry=geometry.interiors)
  1107. elif not geometry.is_empty:
  1108. flat_geo.append(geometry)
  1109. return flat_geo
  1110. @staticmethod
  1111. def recursive_bounds(geometry):
  1112. """
  1113. Return the bounds of the biggest bounding box in geometry, one that include all.
  1114. :param geometry: a iterable object that holds geometry
  1115. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1116. """
  1117. # now it can get bounds for nested lists of objects
  1118. def bounds_rec(obj):
  1119. try:
  1120. minx = Inf
  1121. miny = Inf
  1122. maxx = -Inf
  1123. maxy = -Inf
  1124. for k in obj:
  1125. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1126. minx = min(minx, minx_)
  1127. miny = min(miny, miny_)
  1128. maxx = max(maxx, maxx_)
  1129. maxy = max(maxy, maxy_)
  1130. return minx, miny, maxx, maxy
  1131. except TypeError:
  1132. # it's a Shapely object, return it's bounds
  1133. if obj:
  1134. return obj.bounds
  1135. return bounds_rec(geometry)
  1136. @staticmethod
  1137. def subtract_geo(target_geo, subtractor):
  1138. """
  1139. Subtract subtractor polygon from the target_geo. This only operates on the paths in the target_geo,
  1140. i.e. it converts polygons into paths.
  1141. :param target_geo: geometry from which to subtract
  1142. :param subtractor: a list of Points, a LinearRing or a Polygon that will be subtracted from target_geo
  1143. :return: a cascaded union of the resulting geometry
  1144. """
  1145. if target_geo is None:
  1146. target_geo = []
  1147. # flatten() takes care of possible empty geometry making sure that is filtered
  1148. flat_geometry = CutOut.flatten(target_geo)
  1149. log.debug("%d paths" % len(flat_geometry))
  1150. toolgeo = unary_union(subtractor)
  1151. diffs = []
  1152. for target in flat_geometry:
  1153. if isinstance(target, LineString) or isinstance(target, LinearRing) or isinstance(target, MultiLineString):
  1154. diffs.append(target.difference(toolgeo))
  1155. else:
  1156. log.warning("Not implemented.")
  1157. return unary_union(diffs)
  1158. @staticmethod
  1159. def intersect_geo(target_geo, second_geo):
  1160. """
  1161. :param target_geo:
  1162. :type target_geo:
  1163. :param second_geo:
  1164. :type second_geo:
  1165. :return:
  1166. :rtype:
  1167. """
  1168. results = []
  1169. try:
  1170. __ = iter(target_geo)
  1171. except TypeError:
  1172. target_geo = [target_geo]
  1173. for geo in target_geo:
  1174. if second_geo.intersects(geo):
  1175. results.append(second_geo.intersection(geo))
  1176. return CutOut.flatten(results)
  1177. def reset_fields(self):
  1178. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1179. class CutoutUI:
  1180. toolName = _("Cutout PCB")
  1181. def __init__(self, layout, app):
  1182. self.app = app
  1183. self.decimals = self.app.decimals
  1184. self.layout = layout
  1185. # Title
  1186. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1187. title_label.setStyleSheet("""
  1188. QLabel
  1189. {
  1190. font-size: 16px;
  1191. font-weight: bold;
  1192. }
  1193. """)
  1194. self.layout.addWidget(title_label)
  1195. self.layout.addWidget(QtWidgets.QLabel(''))
  1196. # Form Layout
  1197. grid0 = QtWidgets.QGridLayout()
  1198. grid0.setColumnStretch(0, 0)
  1199. grid0.setColumnStretch(1, 1)
  1200. self.layout.addLayout(grid0)
  1201. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  1202. self.object_label.setToolTip('%s.' % _("Object to be cutout"))
  1203. grid0.addWidget(self.object_label, 0, 0, 1, 2)
  1204. # Object kind
  1205. self.kindlabel = QtWidgets.QLabel('%s:' % _('Kind'))
  1206. self.kindlabel.setToolTip(
  1207. _("Choice of what kind the object we want to cutout is.<BR>"
  1208. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  1209. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  1210. "out of many individual PCB outlines.")
  1211. )
  1212. self.obj_kind_combo = RadioSet([
  1213. {"label": _("Single"), "value": "single"},
  1214. {"label": _("Panel"), "value": "panel"},
  1215. ])
  1216. grid0.addWidget(self.kindlabel, 2, 0)
  1217. grid0.addWidget(self.obj_kind_combo, 2, 1)
  1218. # Type of object to be cutout
  1219. self.type_obj_radio = RadioSet([
  1220. {"label": _("Gerber"), "value": "grb"},
  1221. {"label": _("Geometry"), "value": "geo"},
  1222. ])
  1223. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Type"))
  1224. self.type_obj_combo_label.setToolTip(
  1225. _("Specify the type of object to be cutout.\n"
  1226. "It can be of type: Gerber or Geometry.\n"
  1227. "What is selected here will dictate the kind\n"
  1228. "of objects that will populate the 'Object' combobox.")
  1229. )
  1230. grid0.addWidget(self.type_obj_combo_label, 4, 0)
  1231. grid0.addWidget(self.type_obj_radio, 4, 1)
  1232. # Object to be cutout
  1233. self.obj_combo = FCComboBox()
  1234. self.obj_combo.setModel(self.app.collection)
  1235. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1236. self.obj_combo.is_last = True
  1237. grid0.addWidget(self.obj_combo, 6, 0, 1, 2)
  1238. # Convex Shape
  1239. # Surrounding convex box shape
  1240. self.convex_box_label = QtWidgets.QLabel('%s:' % _("Convex Shape"))
  1241. self.convex_box_label.setToolTip(
  1242. _("Create a convex shape surrounding the entire PCB.\n"
  1243. "Used only if the source object type is Gerber.")
  1244. )
  1245. self.convex_box_cb = FCCheckBox()
  1246. self.convex_box_cb.setToolTip(
  1247. _("Create a convex shape surrounding the entire PCB.\n"
  1248. "Used only if the source object type is Gerber.")
  1249. )
  1250. grid0.addWidget(self.convex_box_label, 8, 0)
  1251. grid0.addWidget(self.convex_box_cb, 8, 1)
  1252. separator_line = QtWidgets.QFrame()
  1253. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1254. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1255. grid0.addWidget(separator_line, 10, 0, 1, 2)
  1256. grid0.addWidget(QtWidgets.QLabel(''), 12, 0, 1, 2)
  1257. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _("Tool Parameters"))
  1258. grid0.addWidget(self.param_label, 14, 0, 1, 2)
  1259. # Tool Diameter
  1260. self.dia = FCDoubleSpinner(callback=self.confirmation_message)
  1261. self.dia.set_precision(self.decimals)
  1262. self.dia.set_range(0.0000, 9999.9999)
  1263. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool Diameter"))
  1264. self.dia_label.setToolTip(
  1265. _("Diameter of the tool used to cutout\n"
  1266. "the PCB shape out of the surrounding material.")
  1267. )
  1268. grid0.addWidget(self.dia_label, 16, 0)
  1269. grid0.addWidget(self.dia, 16, 1)
  1270. # Cut Z
  1271. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1272. cutzlabel.setToolTip(
  1273. _(
  1274. "Cutting depth (negative)\n"
  1275. "below the copper surface."
  1276. )
  1277. )
  1278. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1279. self.cutz_entry.set_precision(self.decimals)
  1280. if machinist_setting == 0:
  1281. self.cutz_entry.setRange(-9999.9999, -0.00001)
  1282. else:
  1283. self.cutz_entry.setRange(-9999.9999, 9999.9999)
  1284. self.cutz_entry.setSingleStep(0.1)
  1285. grid0.addWidget(cutzlabel, 18, 0)
  1286. grid0.addWidget(self.cutz_entry, 18, 1)
  1287. # Multi-pass
  1288. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  1289. self.mpass_cb.setToolTip(
  1290. _(
  1291. "Use multiple passes to limit\n"
  1292. "the cut depth in each pass. Will\n"
  1293. "cut multiple times until Cut Z is\n"
  1294. "reached."
  1295. )
  1296. )
  1297. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1298. self.maxdepth_entry.set_precision(self.decimals)
  1299. self.maxdepth_entry.setRange(0, 9999.9999)
  1300. self.maxdepth_entry.setSingleStep(0.1)
  1301. self.maxdepth_entry.setToolTip(
  1302. _(
  1303. "Depth of each pass (positive)."
  1304. )
  1305. )
  1306. grid0.addWidget(self.mpass_cb, 20, 0)
  1307. grid0.addWidget(self.maxdepth_entry, 20, 1)
  1308. self.ois_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  1309. # Margin
  1310. self.margin = FCDoubleSpinner(callback=self.confirmation_message)
  1311. self.margin.set_range(-9999.9999, 9999.9999)
  1312. self.margin.setSingleStep(0.1)
  1313. self.margin.set_precision(self.decimals)
  1314. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  1315. self.margin_label.setToolTip(
  1316. _("Margin over bounds. A positive value here\n"
  1317. "will make the cutout of the PCB further from\n"
  1318. "the actual PCB border")
  1319. )
  1320. grid0.addWidget(self.margin_label, 22, 0)
  1321. grid0.addWidget(self.margin, 22, 1)
  1322. # Gapsize
  1323. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size"))
  1324. self.gapsize_label.setToolTip(
  1325. _("The size of the bridge gaps in the cutout\n"
  1326. "used to keep the board connected to\n"
  1327. "the surrounding material (the one \n"
  1328. "from which the PCB is cutout).")
  1329. )
  1330. self.gapsize = FCDoubleSpinner(callback=self.confirmation_message)
  1331. self.gapsize.set_precision(self.decimals)
  1332. grid0.addWidget(self.gapsize_label, 24, 0)
  1333. grid0.addWidget(self.gapsize, 24, 1)
  1334. # Gapsize
  1335. self.gaptype_label = FCLabel('%s:' % _("Gap type"))
  1336. self.gaptype_label.setToolTip(
  1337. _("The type of gap:\n"
  1338. "- Bridge -> the cutout will be interrupted by bridges\n"
  1339. "- Thin -> same as 'bridge' but it will be thinner by partially milling the gap\n"
  1340. "- M-Bites -> 'Mouse Bites' - same as 'bridge' but covered with drill holes")
  1341. )
  1342. self.gaptype_radio = RadioSet(
  1343. [
  1344. {'label': _('Bridge'), 'value': 'b'},
  1345. {'label': _('Thin'), 'value': 'bt'},
  1346. {'label': "M-Bites", 'value': 'mb'}
  1347. ],
  1348. stretch=True
  1349. )
  1350. grid0.addWidget(self.gaptype_label, 26, 0)
  1351. grid0.addWidget(self.gaptype_radio, 26, 1)
  1352. # Thin gaps Depth
  1353. self.thin_depth_label = FCLabel('%s:' % _("Depth"))
  1354. self.thin_depth_label.setToolTip(
  1355. _("The depth until the milling is done\n"
  1356. "in order to thin the gaps.")
  1357. )
  1358. self.thin_depth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1359. self.thin_depth_entry.set_precision(self.decimals)
  1360. if machinist_setting == 0:
  1361. self.thin_depth_entry.setRange(-9999.9999, -0.00001)
  1362. else:
  1363. self.thin_depth_entry.setRange(-9999.9999, 9999.9999)
  1364. self.thin_depth_entry.setSingleStep(0.1)
  1365. grid0.addWidget(self.thin_depth_label, 28, 0)
  1366. grid0.addWidget(self.thin_depth_entry, 28, 1)
  1367. # Mouse Bites Tool Diameter
  1368. self.mb_dia_label = FCLabel('%s:' % _("Tool Diameter"))
  1369. self.mb_dia_label.setToolTip(
  1370. _("The drill hole diameter when doing mpuse bites.")
  1371. )
  1372. self.mb_dia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1373. self.mb_dia_entry.set_precision(self.decimals)
  1374. self.mb_dia_entry.setRange(0, 100.0000)
  1375. grid0.addWidget(self.mb_dia_label, 30, 0)
  1376. grid0.addWidget(self.mb_dia_entry, 30, 1)
  1377. # Mouse Bites Holes Spacing
  1378. self.mb_spacing_label = FCLabel('%s:' % _("Spacing"))
  1379. self.mb_spacing_label.setToolTip(
  1380. _("The spacing between drill holes when doing mouse bites.")
  1381. )
  1382. self.mb_spacing_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1383. self.mb_spacing_entry.set_precision(self.decimals)
  1384. self.mb_spacing_entry.setRange(0, 100.0000)
  1385. grid0.addWidget(self.mb_spacing_label, 32, 0)
  1386. grid0.addWidget(self.mb_spacing_entry, 32, 1)
  1387. separator_line = QtWidgets.QFrame()
  1388. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1389. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1390. grid0.addWidget(separator_line, 34, 0, 1, 2)
  1391. grid0.addWidget(QtWidgets.QLabel(''), 36, 0, 1, 2)
  1392. # Title2
  1393. title_param_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Automatic'), _("Bridge Gaps")))
  1394. title_param_label.setToolTip(
  1395. _("This section handle creation of automatic bridge gaps.")
  1396. )
  1397. grid0.addWidget(title_param_label, 38, 0, 1, 2)
  1398. # Gaps
  1399. # How gaps wil be rendered:
  1400. # lr - left + right
  1401. # tb - top + bottom
  1402. # 4 - left + right +top + bottom
  1403. # 2lr - 2*left + 2*right
  1404. # 2tb - 2*top + 2*bottom
  1405. # 8 - 2*left + 2*right +2*top + 2*bottom
  1406. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  1407. gaps_label.setToolTip(
  1408. _("Number of gaps used for the Automatic cutout.\n"
  1409. "There can be maximum 8 bridges/gaps.\n"
  1410. "The choices are:\n"
  1411. "- None - no gaps\n"
  1412. "- lr - left + right\n"
  1413. "- tb - top + bottom\n"
  1414. "- 4 - left + right +top + bottom\n"
  1415. "- 2lr - 2*left + 2*right\n"
  1416. "- 2tb - 2*top + 2*bottom\n"
  1417. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  1418. )
  1419. # gaps_label.setMinimumWidth(60)
  1420. self.gaps = FCComboBox()
  1421. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  1422. for it in gaps_items:
  1423. self.gaps.addItem(it)
  1424. # self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  1425. grid0.addWidget(gaps_label, 40, 0)
  1426. grid0.addWidget(self.gaps, 40, 1)
  1427. # Buttons
  1428. self.ff_cutout_object_btn = FCButton(_("Generate Geometry"))
  1429. self.ff_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/irregular32.png'))
  1430. self.ff_cutout_object_btn.setToolTip(
  1431. _("Cutout the selected object.\n"
  1432. "The cutout shape can be of any shape.\n"
  1433. "Useful when the PCB has a non-rectangular shape.")
  1434. )
  1435. self.ff_cutout_object_btn.setStyleSheet("""
  1436. QPushButton
  1437. {
  1438. font-weight: bold;
  1439. }
  1440. """)
  1441. grid0.addWidget(self.ff_cutout_object_btn, 42, 0, 1, 2)
  1442. self.rect_cutout_object_btn = FCButton(_("Generate Geometry"))
  1443. self.rect_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1444. self.rect_cutout_object_btn.setToolTip(
  1445. _("Cutout the selected object.\n"
  1446. "The resulting cutout shape is\n"
  1447. "always a rectangle shape and it will be\n"
  1448. "the bounding box of the Object.")
  1449. )
  1450. self.rect_cutout_object_btn.setStyleSheet("""
  1451. QPushButton
  1452. {
  1453. font-weight: bold;
  1454. }
  1455. """)
  1456. grid0.addWidget(self.rect_cutout_object_btn, 44, 0, 1, 2)
  1457. separator_line = QtWidgets.QFrame()
  1458. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1459. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1460. grid0.addWidget(separator_line, 46, 0, 1, 2)
  1461. grid0.addWidget(QtWidgets.QLabel(''), 48, 0, 1, 2)
  1462. # MANUAL BRIDGE GAPS
  1463. title_manual_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Manual'), _("Bridge Gaps")))
  1464. title_manual_label.setToolTip(
  1465. _("This section handle creation of manual bridge gaps.\n"
  1466. "This is done by mouse clicking on the perimeter of the\n"
  1467. "Geometry object that is used as a cutout object. ")
  1468. )
  1469. grid0.addWidget(title_manual_label, 50, 0, 1, 2)
  1470. # Big Cursor
  1471. big_cursor_label = QtWidgets.QLabel('%s:' % _("Big cursor"))
  1472. big_cursor_label.setToolTip(
  1473. _("Use a big cursor when adding manual gaps."))
  1474. self.big_cursor_cb = FCCheckBox()
  1475. grid0.addWidget(big_cursor_label, 52, 0)
  1476. grid0.addWidget(self.big_cursor_cb, 52, 1)
  1477. # Generate a surrounding Geometry object
  1478. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  1479. self.man_geo_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1480. self.man_geo_creation_btn.setToolTip(
  1481. _("If the object to be cutout is a Gerber\n"
  1482. "first create a Geometry that surrounds it,\n"
  1483. "to be used as the cutout, if one doesn't exist yet.\n"
  1484. "Select the source Gerber file in the top object combobox.")
  1485. )
  1486. # self.man_geo_creation_btn.setStyleSheet("""
  1487. # QPushButton
  1488. # {
  1489. # font-weight: bold;
  1490. # }
  1491. # """)
  1492. grid0.addWidget(self.man_geo_creation_btn, 54, 0, 1, 2)
  1493. # Manual Geo Object
  1494. self.man_object_combo = FCComboBox()
  1495. self.man_object_combo.setModel(self.app.collection)
  1496. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1497. self.man_object_combo.is_last = True
  1498. self.man_object_combo.obj_type = "Geometry"
  1499. self.man_object_label = QtWidgets.QLabel('%s:' % _("Manual cutout Geometry"))
  1500. self.man_object_label.setToolTip(
  1501. _("Geometry object used to create the manual cutout.")
  1502. )
  1503. # self.man_object_label.setMinimumWidth(60)
  1504. grid0.addWidget(self.man_object_label, 56, 0, 1, 2)
  1505. grid0.addWidget(self.man_object_combo, 56, 0, 1, 2)
  1506. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  1507. self.man_gaps_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/gaps32.png'))
  1508. self.man_gaps_creation_btn.setToolTip(
  1509. _("Use the left mouse button (LMB) click\n"
  1510. "to create a bridge gap to separate the PCB from\n"
  1511. "the surrounding material.\n"
  1512. "The LMB click has to be done on the perimeter of\n"
  1513. "the Geometry object used as a cutout geometry.")
  1514. )
  1515. self.man_gaps_creation_btn.setStyleSheet("""
  1516. QPushButton
  1517. {
  1518. font-weight: bold;
  1519. }
  1520. """)
  1521. grid0.addWidget(self.man_gaps_creation_btn, 58, 0, 1, 2)
  1522. self.layout.addStretch()
  1523. # ## Reset Tool
  1524. self.reset_button = FCButton(_("Reset Tool"))
  1525. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  1526. self.reset_button.setToolTip(
  1527. _("Will reset the tool parameters.")
  1528. )
  1529. self.reset_button.setStyleSheet("""
  1530. QPushButton
  1531. {
  1532. font-weight: bold;
  1533. }
  1534. """)
  1535. self.layout.addWidget(self.reset_button)
  1536. self.gaptype_radio.activated_custom.connect(self.on_gap_type_radio)
  1537. # ############################ FINSIHED GUI ###################################
  1538. # #############################################################################
  1539. def on_gap_type_radio(self, val):
  1540. if val == 'b':
  1541. self.thin_depth_label.hide()
  1542. self.thin_depth_entry.hide()
  1543. self.mb_dia_label.hide()
  1544. self.mb_dia_entry.hide()
  1545. self.mb_spacing_label.hide()
  1546. self.mb_spacing_entry.hide()
  1547. elif val == 'bt':
  1548. self.thin_depth_label.show()
  1549. self.thin_depth_entry.show()
  1550. self.mb_dia_label.hide()
  1551. self.mb_dia_entry.hide()
  1552. self.mb_spacing_label.hide()
  1553. self.mb_spacing_entry.hide()
  1554. elif val == 'mb':
  1555. self.thin_depth_label.hide()
  1556. self.thin_depth_entry.hide()
  1557. self.mb_dia_label.show()
  1558. self.mb_dia_entry.show()
  1559. self.mb_spacing_label.show()
  1560. self.mb_spacing_entry.show()
  1561. def confirmation_message(self, accepted, minval, maxval):
  1562. if accepted is False:
  1563. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1564. self.decimals,
  1565. minval,
  1566. self.decimals,
  1567. maxval), False)
  1568. else:
  1569. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1570. def confirmation_message_int(self, accepted, minval, maxval):
  1571. if accepted is False:
  1572. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1573. (_("Edited value is out of range"), minval, maxval), False)
  1574. else:
  1575. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)