ToolCutOut.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  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() and self.ui.thin_depth_entry.get_value() > 0:
  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() and self.ui.thin_depth_entry.get_value() > 0:
  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. # plot this tool in a different color
  425. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  426. outname = cutout_obj.options["name"] + "_cutout"
  427. ret = self.app.app_obj.new_object('geometry', outname, geo_init)
  428. if ret == 'fail':
  429. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  430. return
  431. # cutout_obj.plot(plot_tool=1)
  432. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  433. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  434. self.app.should_we_save = True
  435. def on_rectangular_cutout(self):
  436. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  437. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  438. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  439. # obj_.subtract_polygon(pts)
  440. name = self.ui.obj_combo.currentText()
  441. # Get source object.
  442. try:
  443. cutout_obj = self.app.collection.get_by_name(str(name))
  444. except Exception as e:
  445. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  446. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  447. return "Could not retrieve object: %s" % name
  448. if cutout_obj is None:
  449. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  450. dia = float(self.ui.dia.get_value())
  451. if 0 in {dia}:
  452. self.app.inform.emit('[ERROR_NOTCL] %s' %
  453. _("Tool Diameter is zero value. Change it to a positive real number."))
  454. return "Tool Diameter is zero value. Change it to a positive real number."
  455. try:
  456. kind = self.ui.obj_kind_combo.get_value()
  457. except ValueError:
  458. return
  459. margin = float(self.ui.margin.get_value())
  460. gapsize = float(self.ui.gapsize.get_value())
  461. try:
  462. gaps = self.ui.gaps.get_value()
  463. except TypeError:
  464. self.app.inform.emit('[WARNING_NOTCL] %s' %
  465. _("Number of gaps value is missing. Add it and retry."))
  466. return
  467. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  468. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  469. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  470. "Fill in a correct value and retry. "))
  471. return
  472. if cutout_obj.multigeo is True:
  473. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  474. "Optionally, this Multi-geo Geometry can be converted to "
  475. "Single-geo Geometry,\n"
  476. "and after that perform Cutout."))
  477. return
  478. # Get min and max data for each object as we just cut rectangles across X or Y
  479. gapsize = gapsize / 2 + (dia / 2)
  480. def geo_init(geo_obj, app_obj):
  481. solid_geo = []
  482. gaps_solid_geo = None
  483. object_geo = cutout_obj.solid_geometry
  484. def cutout_rect_handler(geom):
  485. proc_geometry = []
  486. px = 0.5 * (xmin + xmax) + margin
  487. py = 0.5 * (ymin + ymax) + margin
  488. lenx = (xmax - xmin) + (margin * 2)
  489. leny = (ymax - ymin) + (margin * 2)
  490. if gaps == 'None':
  491. pass
  492. else:
  493. if gaps == '8' or gaps == '2LR':
  494. points = (
  495. xmin - gapsize, # botleft_x
  496. py - gapsize + leny / 4, # botleft_y
  497. xmax + gapsize, # topright_x
  498. py + gapsize + leny / 4 # topright_y
  499. )
  500. geom = self.subtract_poly_from_geo(geom, points)
  501. points = (
  502. xmin - gapsize,
  503. py - gapsize - leny / 4,
  504. xmax + gapsize,
  505. py + gapsize - leny / 4
  506. )
  507. geom = self.subtract_poly_from_geo(geom, points)
  508. if gaps == '8' or gaps == '2TB':
  509. points = (
  510. px - gapsize + lenx / 4,
  511. ymin - gapsize,
  512. px + gapsize + lenx / 4,
  513. ymax + gapsize
  514. )
  515. geom = self.subtract_poly_from_geo(geom, points)
  516. points = (
  517. px - gapsize - lenx / 4,
  518. ymin - gapsize,
  519. px + gapsize - lenx / 4,
  520. ymax + gapsize
  521. )
  522. geom = self.subtract_poly_from_geo(geom, points)
  523. if gaps == '4' or gaps == 'LR':
  524. points = (
  525. xmin - gapsize,
  526. py - gapsize,
  527. xmax + gapsize,
  528. py + gapsize
  529. )
  530. geom = self.subtract_poly_from_geo(geom, points)
  531. if gaps == '4' or gaps == 'TB':
  532. points = (
  533. px - gapsize,
  534. ymin - gapsize,
  535. px + gapsize,
  536. ymax + gapsize
  537. )
  538. geom = self.subtract_poly_from_geo(geom, points)
  539. try:
  540. for g in geom:
  541. proc_geometry.append(g)
  542. except TypeError:
  543. proc_geometry.append(geom)
  544. return proc_geometry
  545. if kind == 'single':
  546. # fuse the lines
  547. object_geo = unary_union(object_geo)
  548. xmin, ymin, xmax, ymax = object_geo.bounds
  549. geo = box(xmin, ymin, xmax, ymax)
  550. # if Gerber create a buffer at a distance
  551. # if Geometry then cut through the geometry
  552. if cutout_obj.kind == 'gerber':
  553. if margin >= 0:
  554. geo = geo.buffer(margin + abs(dia / 2))
  555. else:
  556. geo = geo.buffer(margin - abs(dia / 2))
  557. solid_geo = cutout_rect_handler(geom=geo)
  558. if self.ui.thin_cb.get_value() and self.ui.thin_depth_entry.get_value() > 0:
  559. gaps_solid_geo = self.subtract_geo(geo, solid_geo)
  560. else:
  561. if cutout_obj.kind == 'geometry':
  562. try:
  563. __ = iter(object_geo)
  564. except TypeError:
  565. object_geo = [object_geo]
  566. for geom_struct in object_geo:
  567. geom_struct = unary_union(geom_struct)
  568. xmin, ymin, xmax, ymax = geom_struct.bounds
  569. geom_struct = box(xmin, ymin, xmax, ymax)
  570. c_geo = cutout_rect_handler(geom=geom_struct)
  571. solid_geo += c_geo
  572. if self.ui.thin_cb.get_value() and self.ui.thin_depth_entry.get_value() > 0:
  573. try:
  574. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  575. except TypeError:
  576. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  577. elif cutout_obj.kind == 'gerber' and margin >= 0:
  578. try:
  579. __ = iter(object_geo)
  580. except TypeError:
  581. object_geo = [object_geo]
  582. for geom_struct in object_geo:
  583. geom_struct = unary_union(geom_struct)
  584. xmin, ymin, xmax, ymax = geom_struct.bounds
  585. geom_struct = box(xmin, ymin, xmax, ymax)
  586. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  587. c_geo = cutout_rect_handler(geom=geom_struct)
  588. solid_geo += c_geo
  589. if self.ui.thin_cb.get_value() and self.ui.thin_depth_entry.get_value() > 0:
  590. try:
  591. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  592. except TypeError:
  593. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  594. elif cutout_obj.kind == 'gerber' and margin < 0:
  595. app_obj.inform.emit(
  596. '[WARNING_NOTCL] %s' % _("Rectangular cutout with negative margin is not possible."))
  597. return "fail"
  598. geo_obj.options['cnctooldia'] = str(dia)
  599. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  600. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  601. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  602. if not solid_geo:
  603. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  604. return "fail"
  605. solid_geo = linemerge(solid_geo)
  606. geo_obj.solid_geometry = deepcopy(solid_geo)
  607. geo_obj.tools.update({
  608. 1: {
  609. 'tooldia': str(dia),
  610. 'offset': 'Path',
  611. 'offset_value': 0.0,
  612. 'type': _('Rough'),
  613. 'tool_type': 'C1',
  614. 'data': deepcopy(self.default_data),
  615. 'solid_geometry': geo_obj.solid_geometry
  616. }
  617. })
  618. geo_obj.multigeo = True
  619. geo_obj.tools[1]['data']['name'] = outname
  620. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  621. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  622. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  623. if gaps_solid_geo is not None:
  624. geo_obj.tools.update({
  625. 9999: {
  626. 'tooldia': str(dia),
  627. 'offset': 'Path',
  628. 'offset_value': 0.0,
  629. 'type': _('Rough'),
  630. 'tool_type': 'C1',
  631. 'data': deepcopy(self.default_data),
  632. 'solid_geometry': gaps_solid_geo
  633. }
  634. })
  635. geo_obj.tools[9999]['data']['name'] = outname
  636. geo_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  637. geo_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  638. geo_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  639. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  640. outname = cutout_obj.options["name"] + "_cutout"
  641. ret = self.app.app_obj.new_object('geometry', outname, geo_init)
  642. if ret != 'fail':
  643. # cutout_obj.plot()
  644. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  645. else:
  646. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  647. return
  648. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  649. self.app.should_we_save = True
  650. def on_manual_gap_click(self):
  651. name = self.ui.man_object_combo.currentText()
  652. # Get source object.
  653. try:
  654. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  655. except Exception as e:
  656. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  657. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  658. return
  659. if self.man_cutout_obj is None:
  660. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  661. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  662. return
  663. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  664. self.app.geo_editor.tool_shape.enabled = True
  665. self.manual_solid_geo = deepcopy(self.flatten(self.man_cutout_obj.solid_geometry))
  666. self.cutting_dia = float(self.ui.dia.get_value())
  667. if 0 in {self.cutting_dia}:
  668. self.app.inform.emit('[ERROR_NOTCL] %s' %
  669. _("Tool Diameter is zero value. Change it to a positive real number."))
  670. return
  671. self.cutting_gapsize = float(self.ui.gapsize.get_value())
  672. name = self.ui.man_object_combo.currentText()
  673. # Get Geometry source object to be used as target for Manual adding Gaps
  674. try:
  675. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  676. except Exception as e:
  677. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  678. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  679. return
  680. if self.app.is_legacy is False:
  681. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  682. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  683. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  684. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  685. else:
  686. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  687. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  688. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  689. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  690. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  691. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  692. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  693. self.mouse_events_connected = True
  694. if self.ui.big_cursor_cb.get_value():
  695. self.old_cursor_type = self.app.defaults["global_cursor_type"]
  696. self.app.on_cursor_type(val="big")
  697. self.app.defaults['global_selection_shape'] = False
  698. def on_manual_cutout(self, click_pos):
  699. if self.man_cutout_obj is None:
  700. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  701. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  702. return
  703. # use the snapped position as reference
  704. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  705. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  706. gaps_solid_geo = None
  707. if self.ui.thin_cb.get_value() and self.ui.thin_depth_entry.get_value() > 0:
  708. gaps_solid_geo = self.intersect_geo(self.manual_solid_geo, cut_poly)
  709. # first subtract geometry for the total solid_geometry
  710. new_solid_geometry = CutOut.subtract_geo(self.man_cutout_obj.solid_geometry, cut_poly)
  711. new_solid_geometry = linemerge(new_solid_geometry)
  712. self.man_cutout_obj.solid_geometry = new_solid_geometry
  713. # then do it or each tool in the manual cutout Geometry object
  714. try:
  715. self.man_cutout_obj.tools[1]['solid_geometry'] = new_solid_geometry
  716. self.man_cutout_obj.multigeo = True
  717. self.man_cutout_obj.tools[1]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  718. self.man_cutout_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  719. self.man_cutout_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  720. self.man_cutout_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  721. except KeyError:
  722. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No tool in the Geometry object."))
  723. return
  724. dia = float(self.ui.dia.get_value())
  725. if gaps_solid_geo:
  726. if 9999 not in self.man_cutout_obj.tools:
  727. self.man_cutout_obj.tools.update({
  728. 9999: {
  729. 'tooldia': str(dia),
  730. 'offset': 'Path',
  731. 'offset_value': 0.0,
  732. 'type': _('Rough'),
  733. 'tool_type': 'C1',
  734. 'data': deepcopy(self.default_data),
  735. 'solid_geometry': [gaps_solid_geo]
  736. }
  737. })
  738. self.man_cutout_obj.tools[9999]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  739. self.man_cutout_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  740. self.man_cutout_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  741. self.man_cutout_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  742. self.man_cutout_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  743. else:
  744. self.man_cutout_obj.tools[9999]['solid_geometry'].append(gaps_solid_geo)
  745. self.man_cutout_obj.plot(plot_tool=1)
  746. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  747. self.app.should_we_save = True
  748. def on_manual_geo(self):
  749. name = self.ui.obj_combo.currentText()
  750. # Get source object.
  751. try:
  752. cutout_obj = self.app.collection.get_by_name(str(name))
  753. except Exception as e:
  754. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  755. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  756. return "Could not retrieve object: %s" % name
  757. if cutout_obj is None:
  758. self.app.inform.emit('[ERROR_NOTCL] %s' %
  759. _("There is no Gerber object selected for Cutout.\n"
  760. "Select one and try again."))
  761. return
  762. if cutout_obj.kind != 'gerber':
  763. self.app.inform.emit('[ERROR_NOTCL] %s' %
  764. _("The selected object has to be of Gerber type.\n"
  765. "Select a Gerber file and try again."))
  766. return
  767. dia = float(self.ui.dia.get_value())
  768. if 0 in {dia}:
  769. self.app.inform.emit('[ERROR_NOTCL] %s' %
  770. _("Tool Diameter is zero value. Change it to a positive real number."))
  771. return
  772. try:
  773. kind = self.ui.obj_kind_combo.get_value()
  774. except ValueError:
  775. return
  776. margin = float(self.ui.margin.get_value())
  777. convex_box = self.ui.convex_box.get_value()
  778. def geo_init(geo_obj, app_obj):
  779. geo_union = unary_union(cutout_obj.solid_geometry)
  780. if convex_box:
  781. geo = geo_union.convex_hull
  782. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  783. elif kind == 'single':
  784. if isinstance(geo_union, Polygon) or \
  785. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  786. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  787. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  788. elif isinstance(geo_union, MultiPolygon):
  789. x0, y0, x1, y1 = geo_union.bounds
  790. geo = box(x0, y0, x1, y1)
  791. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  792. else:
  793. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  794. _("Geometry not supported for cutout"), type(geo_union)))
  795. return 'fail'
  796. else:
  797. geo = geo_union
  798. geo = geo.buffer(margin + abs(dia / 2))
  799. if isinstance(geo, Polygon):
  800. geo_obj.solid_geometry = geo.exterior
  801. elif isinstance(geo, MultiPolygon):
  802. solid_geo = []
  803. for poly in geo:
  804. solid_geo.append(poly.exterior)
  805. geo_obj.solid_geometry = deepcopy(solid_geo)
  806. geo_obj.options['cnctooldia'] = str(dia)
  807. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  808. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  809. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  810. geo_obj.tools.update({
  811. 1: {
  812. 'tooldia': str(dia),
  813. 'offset': 'Path',
  814. 'offset_value': 0.0,
  815. 'type': _('Rough'),
  816. 'tool_type': 'C1',
  817. 'data': self.default_data,
  818. 'solid_geometry': geo_obj.solid_geometry
  819. }
  820. })
  821. geo_obj.multigeo = True
  822. geo_obj.tools[1]['data']['name'] = outname
  823. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  824. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  825. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  826. outname = cutout_obj.options["name"] + "_cutout"
  827. self.app.app_obj.new_object('geometry', outname, geo_init)
  828. def cutting_geo(self, pos):
  829. self.cutting_dia = float(self.ui.dia.get_value())
  830. self.cutting_gapsize = float(self.ui.gapsize.get_value())
  831. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  832. # cutting area definition
  833. orig_x = pos[0]
  834. orig_y = pos[1]
  835. xmin = orig_x - offset
  836. ymin = orig_y - offset
  837. xmax = orig_x + offset
  838. ymax = orig_y + offset
  839. cut_poly = box(xmin, ymin, xmax, ymax)
  840. return cut_poly
  841. # To be called after clicking on the plot.
  842. def on_mouse_click_release(self, event):
  843. if self.app.is_legacy is False:
  844. event_pos = event.pos
  845. # event_is_dragging = event.is_dragging
  846. right_button = 2
  847. else:
  848. event_pos = (event.xdata, event.ydata)
  849. # event_is_dragging = self.app.plotcanvas.is_dragging
  850. right_button = 3
  851. try:
  852. x = float(event_pos[0])
  853. y = float(event_pos[1])
  854. except TypeError:
  855. return
  856. event_pos = (x, y)
  857. # do paint single only for left mouse clicks
  858. if event.button == 1:
  859. self.app.inform.emit(_("Making manual bridge gap..."))
  860. pos = self.app.plotcanvas.translate_coords(event_pos)
  861. self.on_manual_cutout(click_pos=pos)
  862. # if RMB then we exit
  863. elif event.button == right_button and self.mouse_is_dragging is False:
  864. if self.app.is_legacy is False:
  865. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  866. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  867. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  868. else:
  869. self.app.plotcanvas.graph_event_disconnect(self.kp)
  870. self.app.plotcanvas.graph_event_disconnect(self.mm)
  871. self.app.plotcanvas.graph_event_disconnect(self.mr)
  872. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  873. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  874. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  875. self.app.on_mouse_click_release_over_plot)
  876. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  877. # Remove any previous utility shape
  878. self.app.geo_editor.tool_shape.clear(update=True)
  879. self.app.geo_editor.tool_shape.enabled = False
  880. # signal that the mouse events are disconnected from local methods
  881. self.mouse_events_connected = False
  882. if self.ui.big_cursor_cb.get_value():
  883. # restore cursor
  884. self.app.on_cursor_type(val=self.old_cursor_type)
  885. # restore selection
  886. self.app.defaults['global_selection_shape'] = self.old_selection_state
  887. # rebuild the manual Geometry object
  888. self.man_cutout_obj.build_ui()
  889. # plot the final object
  890. self.man_cutout_obj.plot()
  891. def on_mouse_move(self, event):
  892. self.app.on_mouse_move_over_plot(event=event)
  893. if self.app.is_legacy is False:
  894. event_pos = event.pos
  895. event_is_dragging = event.is_dragging
  896. # right_button = 2
  897. else:
  898. event_pos = (event.xdata, event.ydata)
  899. event_is_dragging = self.app.plotcanvas.is_dragging
  900. # right_button = 3
  901. try:
  902. x = float(event_pos[0])
  903. y = float(event_pos[1])
  904. except TypeError:
  905. return
  906. event_pos = (x, y)
  907. pos = self.canvas.translate_coords(event_pos)
  908. event.xdata, event.ydata = pos[0], pos[1]
  909. if event_is_dragging is True:
  910. self.mouse_is_dragging = True
  911. else:
  912. self.mouse_is_dragging = False
  913. try:
  914. x = float(event.xdata)
  915. y = float(event.ydata)
  916. except TypeError:
  917. return
  918. if self.app.grid_status():
  919. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  920. else:
  921. snap_x, snap_y = x, y
  922. self.x_pos, self.y_pos = snap_x, snap_y
  923. # #################################################
  924. # ### This section makes the cutting geo to #######
  925. # ### rotate if it intersects the target geo ######
  926. # #################################################
  927. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  928. man_geo = self.man_cutout_obj.solid_geometry
  929. def get_angle(geo):
  930. line = cut_geo.intersection(geo)
  931. try:
  932. pt1_x = line.coords[0][0]
  933. pt1_y = line.coords[0][1]
  934. pt2_x = line.coords[1][0]
  935. pt2_y = line.coords[1][1]
  936. dx = pt1_x - pt2_x
  937. dy = pt1_y - pt2_y
  938. if dx == 0 or dy == 0:
  939. angle = 0
  940. else:
  941. radian = math.atan(dx / dy)
  942. angle = radian * 180 / math.pi
  943. except Exception:
  944. angle = 0
  945. return angle
  946. try:
  947. rot_angle = 0
  948. for geo_el in man_geo:
  949. if isinstance(geo_el, Polygon):
  950. work_geo = geo_el.exterior
  951. if cut_geo.intersects(work_geo):
  952. rot_angle = get_angle(geo=work_geo)
  953. else:
  954. rot_angle = 0
  955. else:
  956. rot_angle = 0
  957. if cut_geo.intersects(geo_el):
  958. rot_angle = get_angle(geo=geo_el)
  959. if rot_angle != 0:
  960. break
  961. except TypeError:
  962. if isinstance(man_geo, Polygon):
  963. work_geo = man_geo.exterior
  964. if cut_geo.intersects(work_geo):
  965. rot_angle = get_angle(geo=work_geo)
  966. else:
  967. rot_angle = 0
  968. else:
  969. rot_angle = 0
  970. if cut_geo.intersects(man_geo):
  971. rot_angle = get_angle(geo=man_geo)
  972. # rotate only if there is an angle to rotate to
  973. if rot_angle != 0:
  974. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  975. # Remove any previous utility shape
  976. self.app.geo_editor.tool_shape.clear(update=True)
  977. self.draw_utility_geometry(geo=cut_geo)
  978. def draw_utility_geometry(self, geo):
  979. self.app.geo_editor.tool_shape.add(
  980. shape=geo,
  981. color=(self.app.defaults["global_draw_color"] + '80'),
  982. update=False,
  983. layer=0,
  984. tolerance=None)
  985. self.app.geo_editor.tool_shape.redraw()
  986. def on_key_press(self, event):
  987. # events out of the self.app.collection view (it's about Project Tab) are of type int
  988. if type(event) is int:
  989. key = event
  990. # events from the GUI are of type QKeyEvent
  991. elif type(event) == QtGui.QKeyEvent:
  992. key = event.key()
  993. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  994. key = event.key
  995. key = QtGui.QKeySequence(key)
  996. # check for modifiers
  997. key_string = key.toString().lower()
  998. if '+' in key_string:
  999. mod, __, key_text = key_string.rpartition('+')
  1000. if mod.lower() == 'ctrl':
  1001. # modifiers = QtCore.Qt.ControlModifier
  1002. pass
  1003. elif mod.lower() == 'alt':
  1004. # modifiers = QtCore.Qt.AltModifier
  1005. pass
  1006. elif mod.lower() == 'shift':
  1007. # modifiers = QtCore.Qt.ShiftModifier
  1008. pass
  1009. else:
  1010. # modifiers = QtCore.Qt.NoModifier
  1011. pass
  1012. key = QtGui.QKeySequence(key_text)
  1013. # events from Vispy are of type KeyEvent
  1014. else:
  1015. key = event.key
  1016. # Escape = Deselect All
  1017. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1018. if self.mouse_events_connected is True:
  1019. self.mouse_events_connected = False
  1020. if self.app.is_legacy is False:
  1021. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1022. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1023. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1024. else:
  1025. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1026. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1027. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1028. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1029. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1030. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1031. self.app.on_mouse_click_release_over_plot)
  1032. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1033. if self.ui.big_cursor_cb.get_value():
  1034. # restore cursor
  1035. self.app.on_cursor_type(val=self.old_cursor_type)
  1036. # restore selection
  1037. self.app.defaults['global_selection_shape'] = self.old_selection_state
  1038. # Remove any previous utility shape
  1039. self.app.geo_editor.tool_shape.clear(update=True)
  1040. self.app.geo_editor.tool_shape.enabled = False
  1041. # Grid toggle
  1042. if key == QtCore.Qt.Key_G or key == 'G':
  1043. self.app.ui.grid_snap_btn.trigger()
  1044. # Jump to coords
  1045. if key == QtCore.Qt.Key_J or key == 'J':
  1046. l_x, l_y = self.app.on_jump_to()
  1047. self.app.geo_editor.tool_shape.clear(update=True)
  1048. geo = self.cutting_geo(pos=(l_x, l_y))
  1049. self.draw_utility_geometry(geo=geo)
  1050. @staticmethod
  1051. def subtract_poly_from_geo(solid_geo, pts):
  1052. """
  1053. Subtract polygon made from points from the given object.
  1054. This only operates on the paths in the original geometry,
  1055. i.e. it converts polygons into paths.
  1056. :param solid_geo: Geometry from which to subtract.
  1057. :param pts: a tuple of coordinates in format (x0, y0, x1, y1)
  1058. :type pts: tuple
  1059. x0: x coord for lower left vertex of the polygon.
  1060. y0: y coord for lower left vertex of the polygon.
  1061. x1: x coord for upper right vertex of the polygon.
  1062. y1: y coord for upper right vertex of the polygon.
  1063. :return: none
  1064. """
  1065. x0 = pts[0]
  1066. y0 = pts[1]
  1067. x1 = pts[2]
  1068. y1 = pts[3]
  1069. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1070. # pathonly should be always True, otherwise polygons are not subtracted
  1071. flat_geometry = CutOut.flatten(geometry=solid_geo)
  1072. log.debug("%d paths" % len(flat_geometry))
  1073. polygon = Polygon(points)
  1074. toolgeo = cascaded_union(polygon)
  1075. diffs = []
  1076. for target in flat_geometry:
  1077. if type(target) == LineString or type(target) == LinearRing:
  1078. diffs.append(target.difference(toolgeo))
  1079. else:
  1080. log.warning("Not implemented.")
  1081. return unary_union(diffs)
  1082. @staticmethod
  1083. def flatten(geometry):
  1084. """
  1085. Creates a list of non-iterable linear geometry objects.
  1086. Polygons are expanded into its exterior and interiors.
  1087. Results are placed in self.flat_geometry
  1088. :param geometry: Shapely type or list or list of list of such.
  1089. """
  1090. flat_geo = []
  1091. try:
  1092. for geo in geometry:
  1093. if geo:
  1094. flat_geo += CutOut.flatten(geometry=geo)
  1095. except TypeError:
  1096. if isinstance(geometry, Polygon) and not geometry.is_empty:
  1097. flat_geo.append(geometry.exterior)
  1098. CutOut.flatten(geometry=geometry.interiors)
  1099. elif not geometry.is_empty:
  1100. flat_geo.append(geometry)
  1101. return flat_geo
  1102. @staticmethod
  1103. def recursive_bounds(geometry):
  1104. """
  1105. Return the bounds of the biggest bounding box in geometry, one that include all.
  1106. :param geometry: a iterable object that holds geometry
  1107. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1108. """
  1109. # now it can get bounds for nested lists of objects
  1110. def bounds_rec(obj):
  1111. try:
  1112. minx = Inf
  1113. miny = Inf
  1114. maxx = -Inf
  1115. maxy = -Inf
  1116. for k in obj:
  1117. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1118. minx = min(minx, minx_)
  1119. miny = min(miny, miny_)
  1120. maxx = max(maxx, maxx_)
  1121. maxy = max(maxy, maxy_)
  1122. return minx, miny, maxx, maxy
  1123. except TypeError:
  1124. # it's a Shapely object, return it's bounds
  1125. if obj:
  1126. return obj.bounds
  1127. return bounds_rec(geometry)
  1128. @staticmethod
  1129. def subtract_geo(target_geo, subtractor):
  1130. """
  1131. Subtract subtractor polygon from the target_geo. This only operates on the paths in the target_geo,
  1132. i.e. it converts polygons into paths.
  1133. :param target_geo: geometry from which to subtract
  1134. :param subtractor: a list of Points, a LinearRing or a Polygon that will be subtracted from target_geo
  1135. :return: a cascaded union of the resulting geometry
  1136. """
  1137. if target_geo is None:
  1138. target_geo = []
  1139. # flatten() takes care of possible empty geometry making sure that is filtered
  1140. flat_geometry = CutOut.flatten(target_geo)
  1141. log.debug("%d paths" % len(flat_geometry))
  1142. toolgeo = unary_union(subtractor)
  1143. diffs = []
  1144. for target in flat_geometry:
  1145. if isinstance(target, LineString) or isinstance(target, LinearRing) or isinstance(target, MultiLineString):
  1146. diffs.append(target.difference(toolgeo))
  1147. else:
  1148. log.warning("Not implemented.")
  1149. return unary_union(diffs)
  1150. @staticmethod
  1151. def intersect_geo(target_geo, second_geo):
  1152. """
  1153. :param target_geo:
  1154. :type target_geo:
  1155. :param second_geo:
  1156. :type second_geo:
  1157. :return:
  1158. :rtype:
  1159. """
  1160. results = []
  1161. try:
  1162. __ = iter(target_geo)
  1163. except TypeError:
  1164. target_geo = [target_geo]
  1165. for geo in target_geo:
  1166. if second_geo.intersects(geo):
  1167. results.append(second_geo.intersection(geo))
  1168. return CutOut.flatten(results)
  1169. def reset_fields(self):
  1170. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1171. class CutoutUI:
  1172. toolName = _("Cutout PCB")
  1173. def __init__(self, layout, app):
  1174. self.app = app
  1175. self.decimals = self.app.decimals
  1176. self.layout = layout
  1177. # Title
  1178. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1179. title_label.setStyleSheet("""
  1180. QLabel
  1181. {
  1182. font-size: 16px;
  1183. font-weight: bold;
  1184. }
  1185. """)
  1186. self.layout.addWidget(title_label)
  1187. self.layout.addWidget(QtWidgets.QLabel(''))
  1188. # Form Layout
  1189. grid0 = QtWidgets.QGridLayout()
  1190. grid0.setColumnStretch(0, 0)
  1191. grid0.setColumnStretch(1, 1)
  1192. self.layout.addLayout(grid0)
  1193. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  1194. self.object_label.setToolTip('%s.' % _("Object to be cutout"))
  1195. grid0.addWidget(self.object_label, 0, 0, 1, 2)
  1196. # Object kind
  1197. self.kindlabel = QtWidgets.QLabel('%s:' % _('Kind'))
  1198. self.kindlabel.setToolTip(
  1199. _("Choice of what kind the object we want to cutout is.<BR>"
  1200. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  1201. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  1202. "out of many individual PCB outlines.")
  1203. )
  1204. self.obj_kind_combo = RadioSet([
  1205. {"label": _("Single"), "value": "single"},
  1206. {"label": _("Panel"), "value": "panel"},
  1207. ])
  1208. grid0.addWidget(self.kindlabel, 1, 0)
  1209. grid0.addWidget(self.obj_kind_combo, 1, 1)
  1210. # Type of object to be cutout
  1211. self.type_obj_radio = RadioSet([
  1212. {"label": _("Gerber"), "value": "grb"},
  1213. {"label": _("Geometry"), "value": "geo"},
  1214. ])
  1215. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Type"))
  1216. self.type_obj_combo_label.setToolTip(
  1217. _("Specify the type of object to be cutout.\n"
  1218. "It can be of type: Gerber or Geometry.\n"
  1219. "What is selected here will dictate the kind\n"
  1220. "of objects that will populate the 'Object' combobox.")
  1221. )
  1222. grid0.addWidget(self.type_obj_combo_label, 2, 0)
  1223. grid0.addWidget(self.type_obj_radio, 2, 1)
  1224. # Object to be cutout
  1225. self.obj_combo = FCComboBox()
  1226. self.obj_combo.setModel(self.app.collection)
  1227. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1228. self.obj_combo.is_last = True
  1229. grid0.addWidget(self.obj_combo, 3, 0, 1, 2)
  1230. separator_line = QtWidgets.QFrame()
  1231. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1232. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1233. grid0.addWidget(separator_line, 4, 0, 1, 2)
  1234. grid0.addWidget(QtWidgets.QLabel(''), 5, 0, 1, 2)
  1235. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _("Tool Parameters"))
  1236. grid0.addWidget(self.param_label, 6, 0, 1, 2)
  1237. # Tool Diameter
  1238. self.dia = FCDoubleSpinner(callback=self.confirmation_message)
  1239. self.dia.set_precision(self.decimals)
  1240. self.dia.set_range(0.0000, 9999.9999)
  1241. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool Diameter"))
  1242. self.dia_label.setToolTip(
  1243. _("Diameter of the tool used to cutout\n"
  1244. "the PCB shape out of the surrounding material.")
  1245. )
  1246. grid0.addWidget(self.dia_label, 8, 0)
  1247. grid0.addWidget(self.dia, 8, 1)
  1248. # Cut Z
  1249. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1250. cutzlabel.setToolTip(
  1251. _(
  1252. "Cutting depth (negative)\n"
  1253. "below the copper surface."
  1254. )
  1255. )
  1256. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1257. self.cutz_entry.set_precision(self.decimals)
  1258. if machinist_setting == 0:
  1259. self.cutz_entry.setRange(-9999.9999, -0.00001)
  1260. else:
  1261. self.cutz_entry.setRange(-9999.9999, 9999.9999)
  1262. self.cutz_entry.setSingleStep(0.1)
  1263. grid0.addWidget(cutzlabel, 9, 0)
  1264. grid0.addWidget(self.cutz_entry, 9, 1)
  1265. # Multi-pass
  1266. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  1267. self.mpass_cb.setToolTip(
  1268. _(
  1269. "Use multiple passes to limit\n"
  1270. "the cut depth in each pass. Will\n"
  1271. "cut multiple times until Cut Z is\n"
  1272. "reached."
  1273. )
  1274. )
  1275. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1276. self.maxdepth_entry.set_precision(self.decimals)
  1277. self.maxdepth_entry.setRange(0, 9999.9999)
  1278. self.maxdepth_entry.setSingleStep(0.1)
  1279. self.maxdepth_entry.setToolTip(
  1280. _(
  1281. "Depth of each pass (positive)."
  1282. )
  1283. )
  1284. grid0.addWidget(self.mpass_cb, 10, 0)
  1285. grid0.addWidget(self.maxdepth_entry, 10, 1)
  1286. # Thin gaps
  1287. self.thin_cb = FCCheckBox('%s:' % _("Thin gaps"))
  1288. self.thin_cb.setToolTip(
  1289. _("Active only when multi depth is active (negative value)\n"
  1290. "If checked, it will mill de gaps until the specified depth."))
  1291. self.thin_depth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1292. self.thin_depth_entry.set_precision(self.decimals)
  1293. if machinist_setting == 0:
  1294. self.thin_depth_entry.setRange(-9999.9999, -0.00001)
  1295. else:
  1296. self.thin_depth_entry.setRange(-9999.9999, 9999.9999)
  1297. self.thin_depth_entry.setSingleStep(0.1)
  1298. self.thin_depth_entry.setToolTip(
  1299. _("Active only when multi depth is active (negative value)\n"
  1300. "If checked, it will mill de gaps until the specified depth."))
  1301. grid0.addWidget(self.thin_cb, 12, 0)
  1302. grid0.addWidget(self.thin_depth_entry, 12, 1)
  1303. self.ois_mpass_geo = OptionalInputSection(self.mpass_cb,
  1304. [
  1305. self.maxdepth_entry,
  1306. self.thin_cb,
  1307. self.thin_depth_entry
  1308. ])
  1309. # Margin
  1310. self.margin = FCDoubleSpinner(callback=self.confirmation_message)
  1311. self.margin.set_range(-9999.9999, 9999.9999)
  1312. self.margin.setSingleStep(0.1)
  1313. self.margin.set_precision(self.decimals)
  1314. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  1315. self.margin_label.setToolTip(
  1316. _("Margin over bounds. A positive value here\n"
  1317. "will make the cutout of the PCB further from\n"
  1318. "the actual PCB border")
  1319. )
  1320. grid0.addWidget(self.margin_label, 14, 0)
  1321. grid0.addWidget(self.margin, 14, 1)
  1322. # Gapsize
  1323. self.gapsize = FCDoubleSpinner(callback=self.confirmation_message)
  1324. self.gapsize.set_precision(self.decimals)
  1325. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size"))
  1326. self.gapsize_label.setToolTip(
  1327. _("The size of the bridge gaps in the cutout\n"
  1328. "used to keep the board connected to\n"
  1329. "the surrounding material (the one \n"
  1330. "from which the PCB is cutout).")
  1331. )
  1332. grid0.addWidget(self.gapsize_label, 16, 0)
  1333. grid0.addWidget(self.gapsize, 16, 1)
  1334. # How gaps wil be rendered:
  1335. # lr - left + right
  1336. # tb - top + bottom
  1337. # 4 - left + right +top + bottom
  1338. # 2lr - 2*left + 2*right
  1339. # 2tb - 2*top + 2*bottom
  1340. # 8 - 2*left + 2*right +2*top + 2*bottom
  1341. # Surrounding convex box shape
  1342. self.convex_box = FCCheckBox('%s' % _("Convex Shape"))
  1343. # self.convex_box_label = QtWidgets.QLabel('%s' % _("Convex Sh."))
  1344. self.convex_box.setToolTip(
  1345. _("Create a convex shape surrounding the entire PCB.\n"
  1346. "Used only if the source object type is Gerber.")
  1347. )
  1348. grid0.addWidget(self.convex_box, 18, 0, 1, 2)
  1349. separator_line = QtWidgets.QFrame()
  1350. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1351. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1352. grid0.addWidget(separator_line, 20, 0, 1, 2)
  1353. grid0.addWidget(QtWidgets.QLabel(''), 22, 0, 1, 2)
  1354. # Title2
  1355. title_param_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Automatic'), _("Bridge Gaps")))
  1356. title_param_label.setToolTip(
  1357. _("This section handle creation of automatic bridge gaps.")
  1358. )
  1359. grid0.addWidget(title_param_label, 24, 0, 1, 2)
  1360. # Gaps
  1361. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  1362. gaps_label.setToolTip(
  1363. _("Number of gaps used for the Automatic cutout.\n"
  1364. "There can be maximum 8 bridges/gaps.\n"
  1365. "The choices are:\n"
  1366. "- None - no gaps\n"
  1367. "- lr - left + right\n"
  1368. "- tb - top + bottom\n"
  1369. "- 4 - left + right +top + bottom\n"
  1370. "- 2lr - 2*left + 2*right\n"
  1371. "- 2tb - 2*top + 2*bottom\n"
  1372. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  1373. )
  1374. # gaps_label.setMinimumWidth(60)
  1375. self.gaps = FCComboBox()
  1376. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  1377. for it in gaps_items:
  1378. self.gaps.addItem(it)
  1379. # self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  1380. grid0.addWidget(gaps_label, 26, 0)
  1381. grid0.addWidget(self.gaps, 26, 1)
  1382. # Buttons
  1383. self.ff_cutout_object_btn = FCButton(_("Generate Geometry"))
  1384. self.ff_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/irregular32.png'))
  1385. self.ff_cutout_object_btn.setToolTip(
  1386. _("Cutout the selected object.\n"
  1387. "The cutout shape can be of any shape.\n"
  1388. "Useful when the PCB has a non-rectangular shape.")
  1389. )
  1390. self.ff_cutout_object_btn.setStyleSheet("""
  1391. QPushButton
  1392. {
  1393. font-weight: bold;
  1394. }
  1395. """)
  1396. grid0.addWidget(self.ff_cutout_object_btn, 28, 0, 1, 2)
  1397. self.rect_cutout_object_btn = FCButton(_("Generate Geometry"))
  1398. self.rect_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1399. self.rect_cutout_object_btn.setToolTip(
  1400. _("Cutout the selected object.\n"
  1401. "The resulting cutout shape is\n"
  1402. "always a rectangle shape and it will be\n"
  1403. "the bounding box of the Object.")
  1404. )
  1405. self.rect_cutout_object_btn.setStyleSheet("""
  1406. QPushButton
  1407. {
  1408. font-weight: bold;
  1409. }
  1410. """)
  1411. grid0.addWidget(self.rect_cutout_object_btn, 30, 0, 1, 2)
  1412. separator_line = QtWidgets.QFrame()
  1413. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1414. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1415. grid0.addWidget(separator_line, 32, 0, 1, 2)
  1416. grid0.addWidget(QtWidgets.QLabel(''), 34, 0, 1, 2)
  1417. # MANUAL BRIDGE GAPS
  1418. title_manual_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Manual'), _("Bridge Gaps")))
  1419. title_manual_label.setToolTip(
  1420. _("This section handle creation of manual bridge gaps.\n"
  1421. "This is done by mouse clicking on the perimeter of the\n"
  1422. "Geometry object that is used as a cutout object. ")
  1423. )
  1424. grid0.addWidget(title_manual_label, 36, 0, 1, 2)
  1425. # Big Cursor
  1426. big_cursor_label = QtWidgets.QLabel('%s:' % _("Big cursor"))
  1427. big_cursor_label.setToolTip(
  1428. _("Use a big cursor when adding manual gaps."))
  1429. self.big_cursor_cb = FCCheckBox()
  1430. grid0.addWidget(big_cursor_label, 38, 0)
  1431. grid0.addWidget(self.big_cursor_cb, 38, 1)
  1432. # Generate a surrounding Geometry object
  1433. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  1434. self.man_geo_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1435. self.man_geo_creation_btn.setToolTip(
  1436. _("If the object to be cutout is a Gerber\n"
  1437. "first create a Geometry that surrounds it,\n"
  1438. "to be used as the cutout, if one doesn't exist yet.\n"
  1439. "Select the source Gerber file in the top object combobox.")
  1440. )
  1441. # self.man_geo_creation_btn.setStyleSheet("""
  1442. # QPushButton
  1443. # {
  1444. # font-weight: bold;
  1445. # }
  1446. # """)
  1447. grid0.addWidget(self.man_geo_creation_btn, 40, 0, 1, 2)
  1448. # Manual Geo Object
  1449. self.man_object_combo = FCComboBox()
  1450. self.man_object_combo.setModel(self.app.collection)
  1451. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1452. self.man_object_combo.is_last = True
  1453. self.man_object_combo.obj_type = "Geometry"
  1454. self.man_object_label = QtWidgets.QLabel('%s:' % _("Manual cutout Geometry"))
  1455. self.man_object_label.setToolTip(
  1456. _("Geometry object used to create the manual cutout.")
  1457. )
  1458. # self.man_object_label.setMinimumWidth(60)
  1459. grid0.addWidget(self.man_object_label, 42, 0, 1, 2)
  1460. grid0.addWidget(self.man_object_combo, 44, 0, 1, 2)
  1461. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  1462. self.man_gaps_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/gaps32.png'))
  1463. self.man_gaps_creation_btn.setToolTip(
  1464. _("Use the left mouse button (LMB) click\n"
  1465. "to create a bridge gap to separate the PCB from\n"
  1466. "the surrounding material.\n"
  1467. "The LMB click has to be done on the perimeter of\n"
  1468. "the Geometry object used as a cutout geometry.")
  1469. )
  1470. self.man_gaps_creation_btn.setStyleSheet("""
  1471. QPushButton
  1472. {
  1473. font-weight: bold;
  1474. }
  1475. """)
  1476. grid0.addWidget(self.man_gaps_creation_btn, 46, 0, 1, 2)
  1477. self.layout.addStretch()
  1478. # ## Reset Tool
  1479. self.reset_button = FCButton(_("Reset Tool"))
  1480. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  1481. self.reset_button.setToolTip(
  1482. _("Will reset the tool parameters.")
  1483. )
  1484. self.reset_button.setStyleSheet("""
  1485. QPushButton
  1486. {
  1487. font-weight: bold;
  1488. }
  1489. """)
  1490. self.layout.addWidget(self.reset_button)
  1491. # ############################ FINSIHED GUI ###################################
  1492. # #############################################################################
  1493. def confirmation_message(self, accepted, minval, maxval):
  1494. if accepted is False:
  1495. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1496. self.decimals,
  1497. minval,
  1498. self.decimals,
  1499. maxval), False)
  1500. else:
  1501. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1502. def confirmation_message_int(self, accepted, minval, maxval):
  1503. if accepted is False:
  1504. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1505. (_("Edited value is out of range"), minval, maxval), False)
  1506. else:
  1507. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)