ToolPunchGerber.py 44 KB

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