ToolCutOut.py 73 KB

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