ToolCutOut.py 75 KB

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