ToolPunchGerber.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 1/24/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtCore, QtWidgets
  8. from appTool import AppTool
  9. from appGUI.GUIElements import RadioSet, FCDoubleSpinner, FCCheckBox, FCComboBox
  10. from copy import deepcopy
  11. import logging
  12. from shapely.geometry import MultiPolygon, Point
  13. import gettext
  14. import appTranslation as fcTranslate
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. log = logging.getLogger('base')
  20. class ToolPunchGerber(AppTool):
  21. def __init__(self, app):
  22. AppTool.__init__(self, app)
  23. self.app = app
  24. self.decimals = self.app.decimals
  25. self.units = self.app.defaults['units']
  26. # #############################################################################
  27. # ######################### Tool GUI ##########################################
  28. # #############################################################################
  29. self.ui = PunchUI(layout=self.layout, app=self.app)
  30. self.toolName = self.ui.toolName
  31. # ## Signals
  32. self.ui.method_punch.activated_custom.connect(self.on_method)
  33. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  34. self.ui.punch_object_button.clicked.connect(self.on_generate_object)
  35. self.ui.circular_cb.stateChanged.connect(
  36. lambda state:
  37. self.ui.circular_ring_entry.setDisabled(False) if state else
  38. self.ui.circular_ring_entry.setDisabled(True)
  39. )
  40. self.ui.oblong_cb.stateChanged.connect(
  41. lambda state:
  42. self.ui.oblong_ring_entry.setDisabled(False) if state else self.ui.oblong_ring_entry.setDisabled(True)
  43. )
  44. self.ui.square_cb.stateChanged.connect(
  45. lambda state:
  46. self.ui.square_ring_entry.setDisabled(False) if state else self.ui.square_ring_entry.setDisabled(True)
  47. )
  48. self.ui.rectangular_cb.stateChanged.connect(
  49. lambda state:
  50. self.ui.rectangular_ring_entry.setDisabled(False) if state else
  51. self.ui.rectangular_ring_entry.setDisabled(True)
  52. )
  53. self.ui.other_cb.stateChanged.connect(
  54. lambda state:
  55. self.ui.other_ring_entry.setDisabled(False) if state else self.ui.other_ring_entry.setDisabled(True)
  56. )
  57. def run(self, toggle=True):
  58. self.app.defaults.report_usage("ToolPunchGerber()")
  59. if toggle:
  60. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  61. if self.app.ui.splitter.sizes()[0] == 0:
  62. self.app.ui.splitter.setSizes([1, 1])
  63. else:
  64. try:
  65. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  66. # if tab is populated with the tool but it does not have the focus, focus on it
  67. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  68. # focus on Tool Tab
  69. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  70. else:
  71. self.app.ui.splitter.setSizes([0, 1])
  72. except AttributeError:
  73. pass
  74. else:
  75. if self.app.ui.splitter.sizes()[0] == 0:
  76. self.app.ui.splitter.setSizes([1, 1])
  77. AppTool.run(self)
  78. self.set_tool_ui()
  79. self.app.ui.notebook.setTabText(2, _("Punch Tool"))
  80. def install(self, icon=None, separator=None, **kwargs):
  81. AppTool.install(self, icon, separator, shortcut='Alt+H', **kwargs)
  82. def set_tool_ui(self):
  83. self.reset_fields()
  84. self.ui_connect()
  85. self.ui.method_punch.set_value(self.app.defaults["tools_punch_hole_type"])
  86. self.ui.select_all_cb.set_value(False)
  87. self.ui.dia_entry.set_value(float(self.app.defaults["tools_punch_hole_fixed_dia"]))
  88. self.ui.circular_ring_entry.set_value(float(self.app.defaults["tools_punch_circular_ring"]))
  89. self.ui.oblong_ring_entry.set_value(float(self.app.defaults["tools_punch_oblong_ring"]))
  90. self.ui.square_ring_entry.set_value(float(self.app.defaults["tools_punch_square_ring"]))
  91. self.ui.rectangular_ring_entry.set_value(float(self.app.defaults["tools_punch_rectangular_ring"]))
  92. self.ui.other_ring_entry.set_value(float(self.app.defaults["tools_punch_others_ring"]))
  93. self.ui.circular_cb.set_value(self.app.defaults["tools_punch_circular"])
  94. self.ui.oblong_cb.set_value(self.app.defaults["tools_punch_oblong"])
  95. self.ui.square_cb.set_value(self.app.defaults["tools_punch_square"])
  96. self.ui.rectangular_cb.set_value(self.app.defaults["tools_punch_rectangular"])
  97. self.ui.other_cb.set_value(self.app.defaults["tools_punch_others"])
  98. self.ui.factor_entry.set_value(float(self.app.defaults["tools_punch_hole_prop_factor"]))
  99. def on_select_all(self, state):
  100. self.ui_disconnect()
  101. if state:
  102. self.ui.circular_cb.setChecked(True)
  103. self.ui.oblong_cb.setChecked(True)
  104. self.ui.square_cb.setChecked(True)
  105. self.ui.rectangular_cb.setChecked(True)
  106. self.ui.other_cb.setChecked(True)
  107. else:
  108. self.ui.circular_cb.setChecked(False)
  109. self.ui.oblong_cb.setChecked(False)
  110. self.ui.square_cb.setChecked(False)
  111. self.ui.rectangular_cb.setChecked(False)
  112. self.ui.other_cb.setChecked(False)
  113. self.ui_connect()
  114. def on_method(self, val):
  115. self.ui.exc_label.setEnabled(False)
  116. self.ui.exc_combo.setEnabled(False)
  117. self.ui.fixed_label.setEnabled(False)
  118. self.ui.dia_label.setEnabled(False)
  119. self.ui.dia_entry.setEnabled(False)
  120. self.ui.ring_frame.setEnabled(False)
  121. self.ui.prop_label.setEnabled(False)
  122. self.ui.factor_label.setEnabled(False)
  123. self.ui.factor_entry.setEnabled(False)
  124. if val == 'exc':
  125. self.ui.exc_label.setEnabled(True)
  126. self.ui.exc_combo.setEnabled(True)
  127. elif val == 'fixed':
  128. self.ui.fixed_label.setEnabled(True)
  129. self.ui.dia_label.setEnabled(True)
  130. self.ui.dia_entry.setEnabled(True)
  131. elif val == 'ring':
  132. self.ui.ring_frame.setEnabled(True)
  133. elif val == 'prop':
  134. self.ui.prop_label.setEnabled(True)
  135. self.ui.factor_label.setEnabled(True)
  136. self.ui.factor_entry.setEnabled(True)
  137. def ui_connect(self):
  138. self.ui.select_all_cb.stateChanged.connect(self.on_select_all)
  139. def ui_disconnect(self):
  140. try:
  141. self.ui.select_all_cb.stateChanged.disconnect()
  142. except (AttributeError, TypeError):
  143. pass
  144. def on_generate_object(self):
  145. # get the Gerber file who is the source of the punched Gerber
  146. selection_index = self.ui.gerber_object_combo.currentIndex()
  147. model_index = self.app.collection.index(selection_index, 0, self.ui.gerber_object_combo.rootModelIndex())
  148. try:
  149. grb_obj = model_index.internalPointer().obj
  150. except Exception:
  151. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  152. return
  153. name = grb_obj.options['name'].rpartition('.')[0]
  154. outname = name + "_punched"
  155. punch_method = self.ui.method_punch.get_value()
  156. new_options = {}
  157. for opt in grb_obj.options:
  158. new_options[opt] = deepcopy(grb_obj.options[opt])
  159. if punch_method == 'exc':
  160. # get the Excellon file whose geometry will create the punch holes
  161. selection_index = self.ui.exc_combo.currentIndex()
  162. model_index = self.app.collection.index(selection_index, 0, self.ui.exc_combo.rootModelIndex())
  163. try:
  164. exc_obj = model_index.internalPointer().obj
  165. except Exception:
  166. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Excellon object loaded ..."))
  167. return
  168. # this is the punching geometry
  169. exc_solid_geometry = MultiPolygon(exc_obj.solid_geometry)
  170. if isinstance(grb_obj.solid_geometry, list):
  171. grb_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  172. else:
  173. grb_solid_geometry = grb_obj.solid_geometry
  174. # create the punched Gerber solid_geometry
  175. punched_solid_geometry = grb_solid_geometry.difference(exc_solid_geometry)
  176. # update the gerber apertures to include the clear geometry so it can be exported successfully
  177. new_apertures = deepcopy(grb_obj.apertures)
  178. new_apertures_items = new_apertures.items()
  179. # find maximum aperture id
  180. new_apid = max([int(x) for x, __ in new_apertures_items])
  181. # store here the clear geometry, the key is the drill size
  182. holes_apertures = {}
  183. for apid, val in new_apertures_items:
  184. for elem in val['geometry']:
  185. # make it work only for Gerber Flashes who are Points in 'follow'
  186. if 'solid' in elem and isinstance(elem['follow'], Point):
  187. for drill in exc_obj.drills:
  188. clear_apid_size = exc_obj.tools[drill['tool']]['tooldia']
  189. # since there may be drills that do not drill into a pad we test only for drills in a pad
  190. if drill['point'].within(elem['solid']):
  191. geo_elem = {}
  192. geo_elem['clear'] = drill['point']
  193. if clear_apid_size not in holes_apertures:
  194. holes_apertures[clear_apid_size] = {}
  195. holes_apertures[clear_apid_size]['type'] = 'C'
  196. holes_apertures[clear_apid_size]['size'] = clear_apid_size
  197. holes_apertures[clear_apid_size]['geometry'] = []
  198. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  199. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  200. # size and add there the clear geometry
  201. for hole_size, ap_val in holes_apertures.items():
  202. new_apid += 1
  203. new_apertures[str(new_apid)] = deepcopy(ap_val)
  204. def init_func(new_obj, app_obj):
  205. new_obj.options.update(new_options)
  206. new_obj.options['name'] = outname
  207. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  208. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  209. new_obj.apertures = deepcopy(new_apertures)
  210. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  211. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  212. local_use=new_obj, use_thread=False)
  213. self.app.app_obj.new_object('gerber', outname, init_func)
  214. elif punch_method == 'fixed':
  215. punch_size = float(self.ui.dia_entry.get_value())
  216. if punch_size == 0.0:
  217. self.app.inform.emit('[WARNING_NOTCL] %s' % _("The value of the fixed diameter is 0.0. Aborting."))
  218. return 'fail'
  219. fail_msg = _("Could not generate punched hole Gerber because the punch hole size is bigger than"
  220. " some of the apertures in the Gerber object.")
  221. punching_geo = []
  222. for apid in grb_obj.apertures:
  223. if grb_obj.apertures[apid]['type'] == 'C' and self.ui.circular_cb.get_value():
  224. for elem in grb_obj.apertures[apid]['geometry']:
  225. if 'follow' in elem:
  226. if isinstance(elem['follow'], Point):
  227. if punch_size >= float(grb_obj.apertures[apid]['size']):
  228. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  229. return 'fail'
  230. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  231. elif grb_obj.apertures[apid]['type'] == 'R':
  232. if round(float(grb_obj.apertures[apid]['width']), self.decimals) == \
  233. round(float(grb_obj.apertures[apid]['height']), self.decimals) and \
  234. self.ui.square_cb.get_value():
  235. for elem in grb_obj.apertures[apid]['geometry']:
  236. if 'follow' in elem:
  237. if isinstance(elem['follow'], Point):
  238. if punch_size >= float(grb_obj.apertures[apid]['width']) or \
  239. punch_size >= float(grb_obj.apertures[apid]['height']):
  240. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  241. return 'fail'
  242. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  243. elif round(float(grb_obj.apertures[apid]['width']), self.decimals) != \
  244. round(float(grb_obj.apertures[apid]['height']), self.decimals) and \
  245. self.ui.rectangular_cb.get_value():
  246. for elem in grb_obj.apertures[apid]['geometry']:
  247. if 'follow' in elem:
  248. if isinstance(elem['follow'], Point):
  249. if punch_size >= float(grb_obj.apertures[apid]['width']) or \
  250. punch_size >= float(grb_obj.apertures[apid]['height']):
  251. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  252. return 'fail'
  253. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  254. elif grb_obj.apertures[apid]['type'] == 'O' and self.ui.oblong_cb.get_value():
  255. for elem in grb_obj.apertures[apid]['geometry']:
  256. if 'follow' in elem:
  257. if isinstance(elem['follow'], Point):
  258. if punch_size >= float(grb_obj.apertures[apid]['size']):
  259. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  260. return 'fail'
  261. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  262. elif grb_obj.apertures[apid]['type'] not in ['C', 'R', 'O'] and self.ui.other_cb.get_value():
  263. for elem in grb_obj.apertures[apid]['geometry']:
  264. if 'follow' in elem:
  265. if isinstance(elem['follow'], Point):
  266. if punch_size >= float(grb_obj.apertures[apid]['size']):
  267. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  268. return 'fail'
  269. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  270. punching_geo = MultiPolygon(punching_geo)
  271. if isinstance(grb_obj.solid_geometry, list):
  272. temp_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  273. else:
  274. temp_solid_geometry = grb_obj.solid_geometry
  275. punched_solid_geometry = temp_solid_geometry.difference(punching_geo)
  276. if punched_solid_geometry == temp_solid_geometry:
  277. self.app.inform.emit('[WARNING_NOTCL] %s' %
  278. _("Could not generate punched hole Gerber because the newly created object "
  279. "geometry is the same as the one in the source object geometry..."))
  280. return 'fail'
  281. # update the gerber apertures to include the clear geometry so it can be exported successfully
  282. new_apertures = deepcopy(grb_obj.apertures)
  283. new_apertures_items = new_apertures.items()
  284. # find maximum aperture id
  285. new_apid = max([int(x) for x, __ in new_apertures_items])
  286. # store here the clear geometry, the key is the drill size
  287. holes_apertures = {}
  288. for apid, val in new_apertures_items:
  289. for elem in val['geometry']:
  290. # make it work only for Gerber Flashes who are Points in 'follow'
  291. if 'solid' in elem and isinstance(elem['follow'], Point):
  292. for geo in punching_geo:
  293. clear_apid_size = punch_size
  294. # since there may be drills that do not drill into a pad we test only for drills in a pad
  295. if geo.within(elem['solid']):
  296. geo_elem = {}
  297. geo_elem['clear'] = geo.centroid
  298. if clear_apid_size not in holes_apertures:
  299. holes_apertures[clear_apid_size] = {}
  300. holes_apertures[clear_apid_size]['type'] = 'C'
  301. holes_apertures[clear_apid_size]['size'] = clear_apid_size
  302. holes_apertures[clear_apid_size]['geometry'] = []
  303. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  304. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  305. # size and add there the clear geometry
  306. for hole_size, ap_val in holes_apertures.items():
  307. new_apid += 1
  308. new_apertures[str(new_apid)] = deepcopy(ap_val)
  309. def init_func(new_obj, app_obj):
  310. new_obj.options.update(new_options)
  311. new_obj.options['name'] = outname
  312. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  313. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  314. new_obj.apertures = deepcopy(new_apertures)
  315. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  316. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  317. local_use=new_obj, use_thread=False)
  318. self.app.app_obj.new_object('gerber', outname, init_func)
  319. elif punch_method == 'ring':
  320. circ_r_val = self.ui.circular_ring_entry.get_value()
  321. oblong_r_val = self.ui.oblong_ring_entry.get_value()
  322. square_r_val = self.ui.square_ring_entry.get_value()
  323. rect_r_val = self.ui.rectangular_ring_entry.get_value()
  324. other_r_val = self.ui.other_ring_entry.get_value()
  325. dia = None
  326. if isinstance(grb_obj.solid_geometry, list):
  327. temp_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  328. else:
  329. temp_solid_geometry = grb_obj.solid_geometry
  330. punched_solid_geometry = temp_solid_geometry
  331. new_apertures = deepcopy(grb_obj.apertures)
  332. new_apertures_items = new_apertures.items()
  333. # find maximum aperture id
  334. new_apid = max([int(x) for x, __ in new_apertures_items])
  335. # store here the clear geometry, the key is the new aperture size
  336. holes_apertures = {}
  337. for apid, apid_value in grb_obj.apertures.items():
  338. ap_type = apid_value['type']
  339. punching_geo = []
  340. if ap_type == 'C' and self.ui.circular_cb.get_value():
  341. dia = float(apid_value['size']) - (2 * circ_r_val)
  342. for elem in apid_value['geometry']:
  343. if 'follow' in elem and isinstance(elem['follow'], Point):
  344. punching_geo.append(elem['follow'].buffer(dia / 2))
  345. elif ap_type == 'O' and self.ui.oblong_cb.get_value():
  346. width = float(apid_value['width'])
  347. height = float(apid_value['height'])
  348. if width > height:
  349. dia = float(apid_value['height']) - (2 * oblong_r_val)
  350. else:
  351. dia = float(apid_value['width']) - (2 * oblong_r_val)
  352. for elem in grb_obj.apertures[apid]['geometry']:
  353. if 'follow' in elem:
  354. if isinstance(elem['follow'], Point):
  355. punching_geo.append(elem['follow'].buffer(dia / 2))
  356. elif ap_type == 'R':
  357. width = float(apid_value['width'])
  358. height = float(apid_value['height'])
  359. # if the height == width (float numbers so the reason for the following)
  360. if round(width, self.decimals) == round(height, self.decimals):
  361. if self.ui.square_cb.get_value():
  362. dia = float(apid_value['height']) - (2 * square_r_val)
  363. for elem in grb_obj.apertures[apid]['geometry']:
  364. if 'follow' in elem:
  365. if isinstance(elem['follow'], Point):
  366. punching_geo.append(elem['follow'].buffer(dia / 2))
  367. elif self.ui.rectangular_cb.get_value():
  368. if width > height:
  369. dia = float(apid_value['height']) - (2 * rect_r_val)
  370. else:
  371. dia = float(apid_value['width']) - (2 * rect_r_val)
  372. for elem in grb_obj.apertures[apid]['geometry']:
  373. if 'follow' in elem:
  374. if isinstance(elem['follow'], Point):
  375. punching_geo.append(elem['follow'].buffer(dia / 2))
  376. elif self.ui.other_cb.get_value():
  377. try:
  378. dia = float(apid_value['size']) - (2 * other_r_val)
  379. except KeyError:
  380. if ap_type == 'AM':
  381. pol = apid_value['geometry'][0]['solid']
  382. x0, y0, x1, y1 = pol.bounds
  383. dx = x1 - x0
  384. dy = y1 - y0
  385. if dx <= dy:
  386. dia = dx - (2 * other_r_val)
  387. else:
  388. dia = dy - (2 * other_r_val)
  389. for elem in grb_obj.apertures[apid]['geometry']:
  390. if 'follow' in elem:
  391. if isinstance(elem['follow'], Point):
  392. punching_geo.append(elem['follow'].buffer(dia / 2))
  393. # if dia is None then none of the above applied so we skip the following
  394. if dia is None:
  395. continue
  396. punching_geo = MultiPolygon(punching_geo)
  397. if punching_geo is None or punching_geo.is_empty:
  398. continue
  399. punched_solid_geometry = punched_solid_geometry.difference(punching_geo)
  400. # update the gerber apertures to include the clear geometry so it can be exported successfully
  401. for elem in apid_value['geometry']:
  402. # make it work only for Gerber Flashes who are Points in 'follow'
  403. if 'solid' in elem and isinstance(elem['follow'], Point):
  404. clear_apid_size = dia
  405. for geo in punching_geo:
  406. # since there may be drills that do not drill into a pad we test only for geos in a pad
  407. if geo.within(elem['solid']):
  408. geo_elem = {}
  409. geo_elem['clear'] = geo.centroid
  410. if clear_apid_size not in holes_apertures:
  411. holes_apertures[clear_apid_size] = {}
  412. holes_apertures[clear_apid_size]['type'] = 'C'
  413. holes_apertures[clear_apid_size]['size'] = clear_apid_size
  414. holes_apertures[clear_apid_size]['geometry'] = []
  415. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  416. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  417. # size and add there the clear geometry
  418. for hole_size, ap_val in holes_apertures.items():
  419. new_apid += 1
  420. new_apertures[str(new_apid)] = deepcopy(ap_val)
  421. def init_func(new_obj, app_obj):
  422. new_obj.options.update(new_options)
  423. new_obj.options['name'] = outname
  424. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  425. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  426. new_obj.apertures = deepcopy(new_apertures)
  427. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  428. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  429. local_use=new_obj, use_thread=False)
  430. self.app.app_obj.new_object('gerber', outname, init_func)
  431. elif punch_method == 'prop':
  432. prop_factor = self.ui.factor_entry.get_value() / 100.0
  433. dia = None
  434. if isinstance(grb_obj.solid_geometry, list):
  435. temp_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  436. else:
  437. temp_solid_geometry = grb_obj.solid_geometry
  438. punched_solid_geometry = temp_solid_geometry
  439. new_apertures = deepcopy(grb_obj.apertures)
  440. new_apertures_items = new_apertures.items()
  441. # find maximum aperture id
  442. new_apid = max([int(x) for x, __ in new_apertures_items])
  443. # store here the clear geometry, the key is the new aperture size
  444. holes_apertures = {}
  445. for apid, apid_value in grb_obj.apertures.items():
  446. ap_type = apid_value['type']
  447. punching_geo = []
  448. if ap_type == 'C' and self.ui.circular_cb.get_value():
  449. dia = float(apid_value['size']) * prop_factor
  450. for elem in apid_value['geometry']:
  451. if 'follow' in elem and isinstance(elem['follow'], Point):
  452. punching_geo.append(elem['follow'].buffer(dia / 2))
  453. elif ap_type == 'O' and self.ui.oblong_cb.get_value():
  454. width = float(apid_value['width'])
  455. height = float(apid_value['height'])
  456. if width > height:
  457. dia = float(apid_value['height']) * prop_factor
  458. else:
  459. dia = float(apid_value['width']) * prop_factor
  460. for elem in grb_obj.apertures[apid]['geometry']:
  461. if 'follow' in elem:
  462. if isinstance(elem['follow'], Point):
  463. punching_geo.append(elem['follow'].buffer(dia / 2))
  464. elif ap_type == 'R':
  465. width = float(apid_value['width'])
  466. height = float(apid_value['height'])
  467. # if the height == width (float numbers so the reason for the following)
  468. if round(width, self.decimals) == round(height, self.decimals):
  469. if self.ui.square_cb.get_value():
  470. dia = float(apid_value['height']) * prop_factor
  471. for elem in grb_obj.apertures[apid]['geometry']:
  472. if 'follow' in elem:
  473. if isinstance(elem['follow'], Point):
  474. punching_geo.append(elem['follow'].buffer(dia / 2))
  475. elif self.ui.rectangular_cb.get_value():
  476. if width > height:
  477. dia = float(apid_value['height']) * prop_factor
  478. else:
  479. dia = float(apid_value['width']) * prop_factor
  480. for elem in grb_obj.apertures[apid]['geometry']:
  481. if 'follow' in elem:
  482. if isinstance(elem['follow'], Point):
  483. punching_geo.append(elem['follow'].buffer(dia / 2))
  484. elif self.ui.other_cb.get_value():
  485. try:
  486. dia = float(apid_value['size']) * prop_factor
  487. except KeyError:
  488. if ap_type == 'AM':
  489. pol = apid_value['geometry'][0]['solid']
  490. x0, y0, x1, y1 = pol.bounds
  491. dx = x1 - x0
  492. dy = y1 - y0
  493. if dx <= dy:
  494. dia = dx * prop_factor
  495. else:
  496. dia = dy * prop_factor
  497. for elem in grb_obj.apertures[apid]['geometry']:
  498. if 'follow' in elem:
  499. if isinstance(elem['follow'], Point):
  500. punching_geo.append(elem['follow'].buffer(dia / 2))
  501. # if dia is None then none of the above applied so we skip the following
  502. if dia is None:
  503. continue
  504. punching_geo = MultiPolygon(punching_geo)
  505. if punching_geo is None or punching_geo.is_empty:
  506. continue
  507. punched_solid_geometry = punched_solid_geometry.difference(punching_geo)
  508. # update the gerber apertures to include the clear geometry so it can be exported successfully
  509. for elem in apid_value['geometry']:
  510. # make it work only for Gerber Flashes who are Points in 'follow'
  511. if 'solid' in elem and isinstance(elem['follow'], Point):
  512. clear_apid_size = dia
  513. for geo in punching_geo:
  514. # since there may be drills that do not drill into a pad we test only for geos in a pad
  515. if geo.within(elem['solid']):
  516. geo_elem = {}
  517. geo_elem['clear'] = geo.centroid
  518. if clear_apid_size not in holes_apertures:
  519. holes_apertures[clear_apid_size] = {}
  520. holes_apertures[clear_apid_size]['type'] = 'C'
  521. holes_apertures[clear_apid_size]['size'] = clear_apid_size
  522. holes_apertures[clear_apid_size]['geometry'] = []
  523. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  524. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  525. # size and add there the clear geometry
  526. for hole_size, ap_val in holes_apertures.items():
  527. new_apid += 1
  528. new_apertures[str(new_apid)] = deepcopy(ap_val)
  529. def init_func(new_obj, app_obj):
  530. new_obj.options.update(new_options)
  531. new_obj.options['name'] = outname
  532. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  533. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  534. new_obj.apertures = deepcopy(new_apertures)
  535. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  536. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  537. local_use=new_obj, use_thread=False)
  538. self.app.app_obj.new_object('gerber', outname, init_func)
  539. def reset_fields(self):
  540. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  541. self.exc_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  542. self.ui_disconnect()
  543. class PunchUI:
  544. toolName = _("Punch Gerber")
  545. def __init__(self, layout, app):
  546. self.app = app
  547. self.decimals = self.app.decimals
  548. self.layout = layout
  549. # ## Title
  550. title_label = QtWidgets.QLabel("%s" % self.toolName)
  551. title_label.setStyleSheet("""
  552. QLabel
  553. {
  554. font-size: 16px;
  555. font-weight: bold;
  556. }
  557. """)
  558. self.layout.addWidget(title_label)
  559. # Punch Drill holes
  560. self.layout.addWidget(QtWidgets.QLabel(""))
  561. # ## Grid Layout
  562. grid_lay = QtWidgets.QGridLayout()
  563. self.layout.addLayout(grid_lay)
  564. grid_lay.setColumnStretch(0, 1)
  565. grid_lay.setColumnStretch(1, 0)
  566. # ## Gerber Object
  567. self.gerber_object_combo = FCComboBox()
  568. self.gerber_object_combo.setModel(self.app.collection)
  569. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  570. self.gerber_object_combo.is_last = True
  571. self.gerber_object_combo.obj_type = "Gerber"
  572. self.grb_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  573. self.grb_label.setToolTip('%s.' % _("Gerber into which to punch holes"))
  574. grid_lay.addWidget(self.grb_label, 0, 0, 1, 2)
  575. grid_lay.addWidget(self.gerber_object_combo, 1, 0, 1, 2)
  576. separator_line = QtWidgets.QFrame()
  577. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  578. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  579. grid_lay.addWidget(separator_line, 2, 0, 1, 2)
  580. self.padt_label = QtWidgets.QLabel("<b>%s</b>" % _("Processed Pads Type"))
  581. self.padt_label.setToolTip(
  582. _("The type of pads shape to be processed.\n"
  583. "If the PCB has many SMD pads with rectangular pads,\n"
  584. "disable the Rectangular aperture.")
  585. )
  586. grid_lay.addWidget(self.padt_label, 3, 0, 1, 2)
  587. # Select all
  588. self.select_all_cb = FCCheckBox('%s' % _("ALL"))
  589. grid_lay.addWidget(self.select_all_cb)
  590. # Circular Aperture Selection
  591. self.circular_cb = FCCheckBox('%s' % _("Circular"))
  592. self.circular_cb.setToolTip(
  593. _("Process Circular Pads.")
  594. )
  595. grid_lay.addWidget(self.circular_cb, 5, 0, 1, 2)
  596. # Oblong Aperture Selection
  597. self.oblong_cb = FCCheckBox('%s' % _("Oblong"))
  598. self.oblong_cb.setToolTip(
  599. _("Process Oblong Pads.")
  600. )
  601. grid_lay.addWidget(self.oblong_cb, 6, 0, 1, 2)
  602. # Square Aperture Selection
  603. self.square_cb = FCCheckBox('%s' % _("Square"))
  604. self.square_cb.setToolTip(
  605. _("Process Square Pads.")
  606. )
  607. grid_lay.addWidget(self.square_cb, 7, 0, 1, 2)
  608. # Rectangular Aperture Selection
  609. self.rectangular_cb = FCCheckBox('%s' % _("Rectangular"))
  610. self.rectangular_cb.setToolTip(
  611. _("Process Rectangular Pads.")
  612. )
  613. grid_lay.addWidget(self.rectangular_cb, 8, 0, 1, 2)
  614. # Others type of Apertures Selection
  615. self.other_cb = FCCheckBox('%s' % _("Others"))
  616. self.other_cb.setToolTip(
  617. _("Process pads not in the categories above.")
  618. )
  619. grid_lay.addWidget(self.other_cb, 9, 0, 1, 2)
  620. separator_line = QtWidgets.QFrame()
  621. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  622. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  623. grid_lay.addWidget(separator_line, 10, 0, 1, 2)
  624. # Grid Layout
  625. grid0 = QtWidgets.QGridLayout()
  626. self.layout.addLayout(grid0)
  627. grid0.setColumnStretch(0, 0)
  628. grid0.setColumnStretch(1, 1)
  629. self.method_label = QtWidgets.QLabel('<b>%s:</b>' % _("Method"))
  630. self.method_label.setToolTip(
  631. _("The punch hole source can be:\n"
  632. "- Excellon Object-> the Excellon object drills center will serve as reference.\n"
  633. "- Fixed Diameter -> will try to use the pads center as reference adding fixed diameter holes.\n"
  634. "- Fixed Annular Ring -> will try to keep a set annular ring.\n"
  635. "- Proportional -> will make a Gerber punch hole having the diameter a percentage of the pad diameter.")
  636. )
  637. self.method_punch = RadioSet(
  638. [
  639. {'label': _('Excellon'), 'value': 'exc'},
  640. {'label': _("Fixed Diameter"), 'value': 'fixed'},
  641. {'label': _("Fixed Annular Ring"), 'value': 'ring'},
  642. {'label': _("Proportional"), 'value': 'prop'}
  643. ],
  644. orientation='vertical',
  645. stretch=False)
  646. grid0.addWidget(self.method_label, 0, 0, 1, 2)
  647. grid0.addWidget(self.method_punch, 1, 0, 1, 2)
  648. separator_line = QtWidgets.QFrame()
  649. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  650. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  651. grid0.addWidget(separator_line, 2, 0, 1, 2)
  652. self.exc_label = QtWidgets.QLabel('<b>%s</b>' % _("Excellon"))
  653. self.exc_label.setToolTip(
  654. _("Remove the geometry of Excellon from the Gerber to create the holes in pads.")
  655. )
  656. self.exc_combo = FCComboBox()
  657. self.exc_combo.setModel(self.app.collection)
  658. self.exc_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  659. self.exc_combo.is_last = True
  660. self.exc_combo.obj_type = "Excellon"
  661. grid0.addWidget(self.exc_label, 3, 0, 1, 2)
  662. grid0.addWidget(self.exc_combo, 4, 0, 1, 2)
  663. separator_line = QtWidgets.QFrame()
  664. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  665. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  666. grid0.addWidget(separator_line, 5, 0, 1, 2)
  667. # Fixed Dia
  668. self.fixed_label = QtWidgets.QLabel('<b>%s</b>' % _("Fixed Diameter"))
  669. grid0.addWidget(self.fixed_label, 6, 0, 1, 2)
  670. # Diameter value
  671. self.dia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  672. self.dia_entry.set_precision(self.decimals)
  673. self.dia_entry.set_range(0.0000, 9999.9999)
  674. self.dia_label = QtWidgets.QLabel('%s:' % _("Value"))
  675. self.dia_label.setToolTip(
  676. _("Fixed hole diameter.")
  677. )
  678. grid0.addWidget(self.dia_label, 8, 0)
  679. grid0.addWidget(self.dia_entry, 8, 1)
  680. separator_line = QtWidgets.QFrame()
  681. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  682. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  683. grid0.addWidget(separator_line, 9, 0, 1, 2)
  684. self.ring_frame = QtWidgets.QFrame()
  685. self.ring_frame.setContentsMargins(0, 0, 0, 0)
  686. grid0.addWidget(self.ring_frame, 10, 0, 1, 2)
  687. self.ring_box = QtWidgets.QVBoxLayout()
  688. self.ring_box.setContentsMargins(0, 0, 0, 0)
  689. self.ring_frame.setLayout(self.ring_box)
  690. # Annular Ring value
  691. self.ring_label = QtWidgets.QLabel('<b>%s</b>' % _("Fixed Annular Ring"))
  692. self.ring_label.setToolTip(
  693. _("The size of annular ring.\n"
  694. "The copper sliver between the hole exterior\n"
  695. "and the margin of the copper pad.")
  696. )
  697. self.ring_box.addWidget(self.ring_label)
  698. # ## Grid Layout
  699. self.grid1 = QtWidgets.QGridLayout()
  700. self.grid1.setColumnStretch(0, 0)
  701. self.grid1.setColumnStretch(1, 1)
  702. self.ring_box.addLayout(self.grid1)
  703. # Circular Annular Ring Value
  704. self.circular_ring_label = QtWidgets.QLabel('%s:' % _("Circular"))
  705. self.circular_ring_label.setToolTip(
  706. _("The size of annular ring for circular pads.")
  707. )
  708. self.circular_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  709. self.circular_ring_entry.set_precision(self.decimals)
  710. self.circular_ring_entry.set_range(0.0000, 9999.9999)
  711. self.grid1.addWidget(self.circular_ring_label, 3, 0)
  712. self.grid1.addWidget(self.circular_ring_entry, 3, 1)
  713. # Oblong Annular Ring Value
  714. self.oblong_ring_label = QtWidgets.QLabel('%s:' % _("Oblong"))
  715. self.oblong_ring_label.setToolTip(
  716. _("The size of annular ring for oblong pads.")
  717. )
  718. self.oblong_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  719. self.oblong_ring_entry.set_precision(self.decimals)
  720. self.oblong_ring_entry.set_range(0.0000, 9999.9999)
  721. self.grid1.addWidget(self.oblong_ring_label, 4, 0)
  722. self.grid1.addWidget(self.oblong_ring_entry, 4, 1)
  723. # Square Annular Ring Value
  724. self.square_ring_label = QtWidgets.QLabel('%s:' % _("Square"))
  725. self.square_ring_label.setToolTip(
  726. _("The size of annular ring for square pads.")
  727. )
  728. self.square_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  729. self.square_ring_entry.set_precision(self.decimals)
  730. self.square_ring_entry.set_range(0.0000, 9999.9999)
  731. self.grid1.addWidget(self.square_ring_label, 5, 0)
  732. self.grid1.addWidget(self.square_ring_entry, 5, 1)
  733. # Rectangular Annular Ring Value
  734. self.rectangular_ring_label = QtWidgets.QLabel('%s:' % _("Rectangular"))
  735. self.rectangular_ring_label.setToolTip(
  736. _("The size of annular ring for rectangular pads.")
  737. )
  738. self.rectangular_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  739. self.rectangular_ring_entry.set_precision(self.decimals)
  740. self.rectangular_ring_entry.set_range(0.0000, 9999.9999)
  741. self.grid1.addWidget(self.rectangular_ring_label, 6, 0)
  742. self.grid1.addWidget(self.rectangular_ring_entry, 6, 1)
  743. # Others Annular Ring Value
  744. self.other_ring_label = QtWidgets.QLabel('%s:' % _("Others"))
  745. self.other_ring_label.setToolTip(
  746. _("The size of annular ring for other pads.")
  747. )
  748. self.other_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  749. self.other_ring_entry.set_precision(self.decimals)
  750. self.other_ring_entry.set_range(0.0000, 9999.9999)
  751. self.grid1.addWidget(self.other_ring_label, 7, 0)
  752. self.grid1.addWidget(self.other_ring_entry, 7, 1)
  753. separator_line = QtWidgets.QFrame()
  754. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  755. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  756. grid0.addWidget(separator_line, 11, 0, 1, 2)
  757. # Proportional value
  758. self.prop_label = QtWidgets.QLabel('<b>%s</b>' % _("Proportional Diameter"))
  759. grid0.addWidget(self.prop_label, 12, 0, 1, 2)
  760. # Diameter value
  761. self.factor_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  762. self.factor_entry.set_precision(self.decimals)
  763. self.factor_entry.set_range(0.0000, 100.0000)
  764. self.factor_entry.setSingleStep(0.1)
  765. self.factor_label = QtWidgets.QLabel('%s:' % _("Value"))
  766. self.factor_label.setToolTip(
  767. _("Proportional Diameter.\n"
  768. "The hole diameter will be a fraction of the pad size.")
  769. )
  770. grid0.addWidget(self.factor_label, 13, 0)
  771. grid0.addWidget(self.factor_entry, 13, 1)
  772. separator_line3 = QtWidgets.QFrame()
  773. separator_line3.setFrameShape(QtWidgets.QFrame.HLine)
  774. separator_line3.setFrameShadow(QtWidgets.QFrame.Sunken)
  775. grid0.addWidget(separator_line3, 14, 0, 1, 2)
  776. # Buttons
  777. self.punch_object_button = QtWidgets.QPushButton(_("Punch Gerber"))
  778. self.punch_object_button.setToolTip(
  779. _("Create a Gerber object from the selected object, within\n"
  780. "the specified box.")
  781. )
  782. self.punch_object_button.setStyleSheet("""
  783. QPushButton
  784. {
  785. font-weight: bold;
  786. }
  787. """)
  788. self.layout.addWidget(self.punch_object_button)
  789. self.layout.addStretch()
  790. # ## Reset Tool
  791. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  792. self.reset_button.setToolTip(
  793. _("Will reset the tool parameters.")
  794. )
  795. self.reset_button.setStyleSheet("""
  796. QPushButton
  797. {
  798. font-weight: bold;
  799. }
  800. """)
  801. self.layout.addWidget(self.reset_button)
  802. self.circular_ring_entry.setEnabled(False)
  803. self.oblong_ring_entry.setEnabled(False)
  804. self.square_ring_entry.setEnabled(False)
  805. self.rectangular_ring_entry.setEnabled(False)
  806. self.other_ring_entry.setEnabled(False)
  807. self.dia_entry.setDisabled(True)
  808. self.dia_label.setDisabled(True)
  809. self.factor_label.setDisabled(True)
  810. self.factor_entry.setDisabled(True)
  811. # #################################### FINSIHED GUI ###########################
  812. # #############################################################################
  813. def confirmation_message(self, accepted, minval, maxval):
  814. if accepted is False:
  815. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  816. self.decimals,
  817. minval,
  818. self.decimals,
  819. maxval), False)
  820. else:
  821. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  822. def confirmation_message_int(self, accepted, minval, maxval):
  823. if accepted is False:
  824. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  825. (_("Edited value is out of range"), minval, maxval), False)
  826. else:
  827. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)