ToolPunchGerber.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import RadioSet, FCDoubleSpinner, FCCheckBox, FCComboBox, FCTable
  10. from copy import deepcopy
  11. import logging
  12. from shapely.geometry import MultiPolygon, Point
  13. from shapely.ops import unary_union
  14. import gettext
  15. import appTranslation as fcTranslate
  16. import builtins
  17. fcTranslate.apply_language('strings')
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class ToolPunchGerber(AppTool):
  22. def __init__(self, app):
  23. AppTool.__init__(self, app)
  24. self.app = app
  25. self.decimals = self.app.decimals
  26. self.units = self.app.defaults['units']
  27. # store here the old object name
  28. self.old_name = ''
  29. # #############################################################################
  30. # ######################### Tool GUI ##########################################
  31. # #############################################################################
  32. self.ui = PunchUI(layout=self.layout, app=self.app)
  33. self.toolName = self.ui.toolName
  34. # ## Signals
  35. self.ui.method_punch.activated_custom.connect(self.on_method)
  36. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  37. self.ui.punch_object_button.clicked.connect(self.on_generate_object)
  38. self.ui.gerber_object_combo.currentIndexChanged.connect(self.build_tool_ui)
  39. self.ui.circular_cb.stateChanged.connect(
  40. lambda state:
  41. self.ui.circular_ring_entry.setDisabled(False) if state else
  42. self.ui.circular_ring_entry.setDisabled(True)
  43. )
  44. self.ui.oblong_cb.stateChanged.connect(
  45. lambda state:
  46. self.ui.oblong_ring_entry.setDisabled(False) if state else self.ui.oblong_ring_entry.setDisabled(True)
  47. )
  48. self.ui.square_cb.stateChanged.connect(
  49. lambda state:
  50. self.ui.square_ring_entry.setDisabled(False) if state else self.ui.square_ring_entry.setDisabled(True)
  51. )
  52. self.ui.rectangular_cb.stateChanged.connect(
  53. lambda state:
  54. self.ui.rectangular_ring_entry.setDisabled(False) if state else
  55. self.ui.rectangular_ring_entry.setDisabled(True)
  56. )
  57. self.ui.other_cb.stateChanged.connect(
  58. lambda state:
  59. self.ui.other_ring_entry.setDisabled(False) if state else self.ui.other_ring_entry.setDisabled(True)
  60. )
  61. self.ui.circular_cb.stateChanged.connect(self.build_tool_ui)
  62. self.ui.oblong_cb.stateChanged.connect(self.build_tool_ui)
  63. self.ui.square_cb.stateChanged.connect(self.build_tool_ui)
  64. self.ui.rectangular_cb.stateChanged.connect(self.build_tool_ui)
  65. self.ui.other_cb.stateChanged.connect(self.build_tool_ui)
  66. self.ui.gerber_object_combo.currentIndexChanged.connect(self.on_object_combo_changed)
  67. def on_object_combo_changed(self):
  68. # get the Gerber file who is the source of the punched Gerber
  69. selection_index = self.ui.gerber_object_combo.currentIndex()
  70. model_index = self.app.collection.index(selection_index, 0, self.ui.gerber_object_combo.rootModelIndex())
  71. try:
  72. grb_obj = model_index.internalPointer().obj
  73. except Exception:
  74. return
  75. if self.old_name != '':
  76. old_obj = self.app.collection.get_by_name(self.old_name)
  77. if old_obj:
  78. old_obj.clear_plot_apertures()
  79. old_obj.mark_shapes.enabled = False
  80. # enable mark shapes
  81. if grb_obj:
  82. grb_obj.mark_shapes.enabled = True
  83. # create storage for shapes
  84. for ap_code in grb_obj.apertures:
  85. grb_obj.mark_shapes_storage[ap_code] = []
  86. self.old_name = grb_obj.options['name']
  87. def run(self, toggle=True):
  88. self.app.defaults.report_usage("ToolPunchGerber()")
  89. if toggle:
  90. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  91. if self.app.ui.splitter.sizes()[0] == 0:
  92. self.app.ui.splitter.setSizes([1, 1])
  93. else:
  94. try:
  95. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  96. # if tab is populated with the tool but it does not have the focus, focus on it
  97. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  98. # focus on Tool Tab
  99. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  100. else:
  101. self.app.ui.splitter.setSizes([0, 1])
  102. except AttributeError:
  103. pass
  104. else:
  105. if self.app.ui.splitter.sizes()[0] == 0:
  106. self.app.ui.splitter.setSizes([1, 1])
  107. AppTool.run(self)
  108. self.set_tool_ui()
  109. self.build_tool_ui()
  110. self.app.ui.notebook.setTabText(2, _("Punch Tool"))
  111. def install(self, icon=None, separator=None, **kwargs):
  112. AppTool.install(self, icon, separator, shortcut='Alt+H', **kwargs)
  113. def set_tool_ui(self):
  114. self.reset_fields()
  115. self.ui_disconnect()
  116. self.ui_connect()
  117. self.ui.method_punch.set_value(self.app.defaults["tools_punch_hole_type"])
  118. self.ui.select_all_cb.set_value(False)
  119. self.ui.dia_entry.set_value(float(self.app.defaults["tools_punch_hole_fixed_dia"]))
  120. self.ui.circular_ring_entry.set_value(float(self.app.defaults["tools_punch_circular_ring"]))
  121. self.ui.oblong_ring_entry.set_value(float(self.app.defaults["tools_punch_oblong_ring"]))
  122. self.ui.square_ring_entry.set_value(float(self.app.defaults["tools_punch_square_ring"]))
  123. self.ui.rectangular_ring_entry.set_value(float(self.app.defaults["tools_punch_rectangular_ring"]))
  124. self.ui.other_ring_entry.set_value(float(self.app.defaults["tools_punch_others_ring"]))
  125. self.ui.circular_cb.set_value(self.app.defaults["tools_punch_circular"])
  126. self.ui.oblong_cb.set_value(self.app.defaults["tools_punch_oblong"])
  127. self.ui.square_cb.set_value(self.app.defaults["tools_punch_square"])
  128. self.ui.rectangular_cb.set_value(self.app.defaults["tools_punch_rectangular"])
  129. self.ui.other_cb.set_value(self.app.defaults["tools_punch_others"])
  130. self.ui.factor_entry.set_value(float(self.app.defaults["tools_punch_hole_prop_factor"]))
  131. def build_tool_ui(self):
  132. self.ui_disconnect()
  133. # reset table
  134. # self.ui.apertures_table.clear() # this deletes the headers/tooltips too ... not nice!
  135. self.ui.apertures_table.setRowCount(0)
  136. # get the Gerber file who is the source of the punched Gerber
  137. selection_index = self.ui.gerber_object_combo.currentIndex()
  138. model_index = self.app.collection.index(selection_index, 0, self.ui.gerber_object_combo.rootModelIndex())
  139. obj = None
  140. try:
  141. obj = model_index.internalPointer().obj
  142. sort = [int(k) for k in obj.apertures.keys()]
  143. sorted_apertures = sorted(sort)
  144. except Exception:
  145. # no object loaded
  146. sorted_apertures = []
  147. # n = len(sorted_apertures)
  148. # calculate how many rows to add
  149. n = 0
  150. for ap_code in sorted_apertures:
  151. ap_code = str(ap_code)
  152. ap_type = obj.apertures[ap_code]['type']
  153. if ap_type == 'C' and self.ui.circular_cb.get_value() is True:
  154. n += 1
  155. if ap_type == 'R':
  156. if self.ui.square_cb.get_value() is True:
  157. n += 1
  158. elif self.ui.rectangular_cb.get_value() is True:
  159. n += 1
  160. if ap_type == 'O' and self.ui.oblong_cb.get_value() is True:
  161. n += 1
  162. if ap_type not in ['C', 'R', 'O'] and self.ui.other_cb.get_value() is True:
  163. n += 1
  164. self.ui.apertures_table.setRowCount(n)
  165. row = 0
  166. for ap_code in sorted_apertures:
  167. ap_code = str(ap_code)
  168. ap_type = obj.apertures[ap_code]['type']
  169. if ap_type == 'C':
  170. if self.ui.circular_cb.get_value() is False:
  171. continue
  172. elif ap_type == 'R':
  173. if self.ui.square_cb.get_value() is True:
  174. pass
  175. elif self.ui.rectangular_cb.get_value() is True:
  176. pass
  177. else:
  178. continue
  179. elif ap_type == 'O':
  180. if self.ui.oblong_cb.get_value() is False:
  181. continue
  182. elif self.ui.other_cb.get_value() is True:
  183. pass
  184. else:
  185. continue
  186. # Aperture CODE
  187. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  188. ap_code_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  189. # Aperture TYPE
  190. ap_type_item = QtWidgets.QTableWidgetItem(str(ap_type))
  191. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  192. # Aperture SIZE
  193. try:
  194. if obj.apertures[ap_code]['size'] is not None:
  195. size_val = self.app.dec_format(float(obj.apertures[ap_code]['size']), self.decimals)
  196. ap_size_item = QtWidgets.QTableWidgetItem(str(size_val))
  197. else:
  198. ap_size_item = QtWidgets.QTableWidgetItem('')
  199. except KeyError:
  200. ap_size_item = QtWidgets.QTableWidgetItem('')
  201. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  202. # Aperture MARK Item
  203. mark_item = FCCheckBox()
  204. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  205. # Empty PLOT ITEM
  206. empty_plot_item = QtWidgets.QTableWidgetItem('')
  207. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  208. empty_plot_item.setFlags(QtCore.Qt.ItemIsEnabled)
  209. self.ui.apertures_table.setItem(row, 0, ap_code_item) # Aperture Code
  210. self.ui.apertures_table.setItem(row, 1, ap_type_item) # Aperture Type
  211. self.ui.apertures_table.setItem(row, 2, ap_size_item) # Aperture Dimensions
  212. self.ui.apertures_table.setItem(row, 3, empty_plot_item)
  213. self.ui.apertures_table.setCellWidget(row, 3, mark_item)
  214. # increment row
  215. row += 1
  216. self.ui.apertures_table.selectColumn(0)
  217. self.ui.apertures_table.resizeColumnsToContents()
  218. self.ui.apertures_table.resizeRowsToContents()
  219. vertical_header = self.ui.apertures_table.verticalHeader()
  220. vertical_header.hide()
  221. # self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  222. horizontal_header = self.ui.apertures_table.horizontalHeader()
  223. horizontal_header.setMinimumSectionSize(10)
  224. horizontal_header.setDefaultSectionSize(70)
  225. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  226. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  227. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
  228. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.Fixed)
  229. horizontal_header.resizeSection(3, 17)
  230. self.ui.apertures_table.setColumnWidth(3, 17)
  231. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  232. self.ui.apertures_table.setSortingEnabled(False)
  233. # self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  234. # self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  235. self.ui_connect()
  236. def on_select_all(self, state):
  237. self.ui_disconnect()
  238. if state:
  239. self.ui.circular_cb.setChecked(True)
  240. self.ui.oblong_cb.setChecked(True)
  241. self.ui.square_cb.setChecked(True)
  242. self.ui.rectangular_cb.setChecked(True)
  243. self.ui.other_cb.setChecked(True)
  244. else:
  245. self.ui.circular_cb.setChecked(False)
  246. self.ui.oblong_cb.setChecked(False)
  247. self.ui.square_cb.setChecked(False)
  248. self.ui.rectangular_cb.setChecked(False)
  249. self.ui.other_cb.setChecked(False)
  250. # get the Gerber file who is the source of the punched Gerber
  251. selection_index = self.ui.gerber_object_combo.currentIndex()
  252. model_index = self.app.collection.index(selection_index, 0, self.ui.gerber_object_combo.rootModelIndex())
  253. try:
  254. grb_obj = model_index.internalPointer().obj
  255. except Exception:
  256. return
  257. grb_obj.clear_plot_apertures()
  258. self.ui_connect()
  259. def on_method(self, val):
  260. self.ui.exc_label.hide()
  261. self.ui.exc_combo.hide()
  262. self.ui.fixed_label.hide()
  263. self.ui.dia_label.hide()
  264. self.ui.dia_entry.hide()
  265. self.ui.ring_frame.hide()
  266. self.ui.prop_label.hide()
  267. self.ui.factor_label.hide()
  268. self.ui.factor_entry.hide()
  269. if val == 'exc':
  270. self.ui.exc_label.show()
  271. self.ui.exc_combo.show()
  272. elif val == 'fixed':
  273. self.ui.fixed_label.show()
  274. self.ui.dia_label.show()
  275. self.ui.dia_entry.show()
  276. elif val == 'ring':
  277. self.ui.ring_frame.show()
  278. elif val == 'prop':
  279. self.ui.prop_label.show()
  280. self.ui.factor_label.show()
  281. self.ui.factor_entry.show()
  282. def ui_connect(self):
  283. self.ui.select_all_cb.stateChanged.connect(self.on_select_all)
  284. # Mark Checkboxes
  285. for row in range(self.ui.apertures_table.rowCount()):
  286. try:
  287. self.ui.apertures_table.cellWidget(row, 3).clicked.disconnect()
  288. except (TypeError, AttributeError):
  289. pass
  290. self.ui.apertures_table.cellWidget(row, 3).clicked.connect(self.on_mark_cb_click_table)
  291. def ui_disconnect(self):
  292. try:
  293. self.ui.select_all_cb.stateChanged.disconnect()
  294. except (AttributeError, TypeError):
  295. pass
  296. # Mark Checkboxes
  297. for row in range(self.ui.apertures_table.rowCount()):
  298. try:
  299. self.ui.apertures_table.cellWidget(row, 3).clicked.disconnect()
  300. except (TypeError, AttributeError):
  301. pass
  302. def on_generate_object(self):
  303. # get the Gerber file who is the source of the punched Gerber
  304. selection_index = self.ui.gerber_object_combo.currentIndex()
  305. model_index = self.app.collection.index(selection_index, 0, self.ui.gerber_object_combo.rootModelIndex())
  306. try:
  307. grb_obj = model_index.internalPointer().obj
  308. except Exception:
  309. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  310. return
  311. name = grb_obj.options['name'].rpartition('.')[0]
  312. outname = name + "_punched"
  313. punch_method = self.ui.method_punch.get_value()
  314. if punch_method == 'exc':
  315. self.on_excellon_method(grb_obj, outname)
  316. elif punch_method == 'fixed':
  317. self.on_fixed_method(grb_obj, outname)
  318. elif punch_method == 'ring':
  319. self.on_ring_method(grb_obj, outname)
  320. elif punch_method == 'prop':
  321. self.on_proportional_method(grb_obj, outname)
  322. def on_excellon_method(self, grb_obj, outname):
  323. # get the Excellon file whose geometry will create the punch holes
  324. selection_index = self.ui.exc_combo.currentIndex()
  325. model_index = self.app.collection.index(selection_index, 0, self.ui.exc_combo.rootModelIndex())
  326. try:
  327. exc_obj = model_index.internalPointer().obj
  328. except Exception:
  329. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Excellon object loaded ..."))
  330. return
  331. new_options = {}
  332. for opt in grb_obj.options:
  333. new_options[opt] = deepcopy(grb_obj.options[opt])
  334. # selected codes in thre apertures UI table
  335. sel_apid = []
  336. for it in self.ui.apertures_table.selectedItems():
  337. sel_apid.append(it.text())
  338. # this is the punching geometry
  339. exc_solid_geometry = MultiPolygon(exc_obj.solid_geometry)
  340. # this is the target geometry
  341. # if isinstance(grb_obj.solid_geometry, list):
  342. # grb_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  343. # else:
  344. # grb_solid_geometry = grb_obj.solid_geometry
  345. grb_solid_geometry = []
  346. target_geometry = []
  347. for apid in grb_obj.apertures:
  348. if 'geometry' in grb_obj.apertures[apid]:
  349. for el_geo in grb_obj.apertures[apid]['geometry']:
  350. if 'solid' in el_geo:
  351. if apid in sel_apid:
  352. target_geometry.append(el_geo['solid'])
  353. else:
  354. grb_solid_geometry.append(el_geo['solid'])
  355. target_geometry = MultiPolygon(target_geometry).buffer(0)
  356. # create the punched Gerber solid_geometry
  357. punched_target_geometry = target_geometry.difference(exc_solid_geometry)
  358. # add together the punched geometry and the not affected geometry
  359. punched_solid_geometry = []
  360. try:
  361. for geo in punched_target_geometry.geoms:
  362. punched_solid_geometry.append(geo)
  363. except AttributeError:
  364. punched_solid_geometry.append(punched_target_geometry)
  365. for geo in grb_solid_geometry:
  366. punched_solid_geometry.append(geo)
  367. punched_solid_geometry = unary_union(punched_solid_geometry)
  368. # update the gerber apertures to include the clear geometry so it can be exported successfully
  369. new_apertures = deepcopy(grb_obj.apertures)
  370. new_apertures_items = new_apertures.items()
  371. # find maximum aperture id
  372. new_apid = max([int(x) for x, __ in new_apertures_items])
  373. # store here the clear geometry, the key is the drill size
  374. holes_apertures = {}
  375. for apid, val in new_apertures_items:
  376. if apid in sel_apid:
  377. for elem in val['geometry']:
  378. # make it work only for Gerber Flashes who are Points in 'follow'
  379. if 'solid' in elem and isinstance(elem['follow'], Point):
  380. for tool in exc_obj.tools:
  381. clear_apid_size = exc_obj.tools[tool]['tooldia']
  382. if 'drills' in exc_obj.tools[tool]:
  383. for drill_pt in exc_obj.tools[tool]['drills']:
  384. # since there may be drills that do not drill into a pad we test only for
  385. # drills in a pad
  386. if drill_pt.within(elem['solid']):
  387. geo_elem = {'clear': drill_pt}
  388. if clear_apid_size not in holes_apertures:
  389. holes_apertures[clear_apid_size] = {
  390. 'type': 'C',
  391. 'size': clear_apid_size,
  392. 'geometry': []
  393. }
  394. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  395. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  396. # size and add there the clear geometry
  397. for hole_size, ap_val in holes_apertures.items():
  398. new_apid += 1
  399. new_apertures[str(new_apid)] = deepcopy(ap_val)
  400. def init_func(new_obj, app_obj):
  401. new_obj.options.update(new_options)
  402. new_obj.options['name'] = outname
  403. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  404. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  405. new_obj.apertures = deepcopy(new_apertures)
  406. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  407. new_obj.source_file = app_obj.f_handlers.export_gerber(obj_name=outname, filename=None,
  408. local_use=new_obj, use_thread=False)
  409. self.app.app_obj.new_object('gerber', outname, init_func)
  410. def on_fixed_method(self, grb_obj, outname):
  411. punch_size = float(self.ui.dia_entry.get_value())
  412. if punch_size == 0.0:
  413. self.app.inform.emit('[WARNING_NOTCL] %s' % _("The value of the fixed diameter is 0.0. Aborting."))
  414. return 'fail'
  415. fail_msg = _("Could not generate punched hole Gerber because the punch hole size is bigger than"
  416. " some of the apertures in the Gerber object.")
  417. new_options = {}
  418. for opt in grb_obj.options:
  419. new_options[opt] = deepcopy(grb_obj.options[opt])
  420. # selected codes in thre apertures UI table
  421. sel_apid = []
  422. for it in self.ui.apertures_table.selectedItems():
  423. sel_apid.append(it.text())
  424. punching_geo = []
  425. for apid in grb_obj.apertures:
  426. if apid in sel_apid:
  427. if grb_obj.apertures[apid]['type'] == 'C' and self.ui.circular_cb.get_value():
  428. for elem in grb_obj.apertures[apid]['geometry']:
  429. if 'follow' in elem:
  430. if isinstance(elem['follow'], Point):
  431. if punch_size >= float(grb_obj.apertures[apid]['size']):
  432. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  433. return 'fail'
  434. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  435. elif grb_obj.apertures[apid]['type'] == 'R':
  436. if round(float(grb_obj.apertures[apid]['width']), self.decimals) == \
  437. round(float(grb_obj.apertures[apid]['height']), self.decimals) and \
  438. self.ui.square_cb.get_value():
  439. for elem in grb_obj.apertures[apid]['geometry']:
  440. if 'follow' in elem:
  441. if isinstance(elem['follow'], Point):
  442. if punch_size >= float(grb_obj.apertures[apid]['width']) or \
  443. punch_size >= float(grb_obj.apertures[apid]['height']):
  444. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  445. return 'fail'
  446. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  447. elif round(float(grb_obj.apertures[apid]['width']), self.decimals) != \
  448. round(float(grb_obj.apertures[apid]['height']), self.decimals) and \
  449. self.ui.rectangular_cb.get_value():
  450. for elem in grb_obj.apertures[apid]['geometry']:
  451. if 'follow' in elem:
  452. if isinstance(elem['follow'], Point):
  453. if punch_size >= float(grb_obj.apertures[apid]['width']) or \
  454. punch_size >= float(grb_obj.apertures[apid]['height']):
  455. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  456. return 'fail'
  457. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  458. elif grb_obj.apertures[apid]['type'] == 'O' and self.ui.oblong_cb.get_value():
  459. for elem in grb_obj.apertures[apid]['geometry']:
  460. if 'follow' in elem:
  461. if isinstance(elem['follow'], Point):
  462. if punch_size >= float(grb_obj.apertures[apid]['size']):
  463. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  464. return 'fail'
  465. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  466. elif grb_obj.apertures[apid]['type'] not in ['C', 'R', 'O'] and self.ui.other_cb.get_value():
  467. for elem in grb_obj.apertures[apid]['geometry']:
  468. if 'follow' in elem:
  469. if isinstance(elem['follow'], Point):
  470. if punch_size >= float(grb_obj.apertures[apid]['size']):
  471. self.app.inform.emit('[ERROR_NOTCL] %s' % fail_msg)
  472. return 'fail'
  473. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  474. punching_geo = MultiPolygon(punching_geo)
  475. if isinstance(grb_obj.solid_geometry, list):
  476. temp_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  477. else:
  478. temp_solid_geometry = grb_obj.solid_geometry
  479. punched_solid_geometry = temp_solid_geometry.difference(punching_geo)
  480. if punched_solid_geometry == temp_solid_geometry:
  481. self.app.inform.emit('[WARNING_NOTCL] %s' %
  482. _("Could not generate punched hole Gerber because the newly created object "
  483. "geometry is the same as the one in the source object geometry..."))
  484. return 'fail'
  485. # update the gerber apertures to include the clear geometry so it can be exported successfully
  486. new_apertures = deepcopy(grb_obj.apertures)
  487. new_apertures_items = new_apertures.items()
  488. # find maximum aperture id
  489. new_apid = max([int(x) for x, __ in new_apertures_items])
  490. # store here the clear geometry, the key is the drill size
  491. holes_apertures = {}
  492. for apid, val in new_apertures_items:
  493. for elem in val['geometry']:
  494. # make it work only for Gerber Flashes who are Points in 'follow'
  495. if 'solid' in elem and isinstance(elem['follow'], Point):
  496. for geo in punching_geo:
  497. clear_apid_size = punch_size
  498. # since there may be drills that do not drill into a pad we test only for drills in a pad
  499. if geo.within(elem['solid']):
  500. geo_elem = {'clear': geo.centroid}
  501. if clear_apid_size not in holes_apertures:
  502. holes_apertures[clear_apid_size] = {
  503. 'type': 'C',
  504. 'size': clear_apid_size,
  505. 'geometry': []
  506. }
  507. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  508. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  509. # size and add there the clear geometry
  510. for hole_size, ap_val in holes_apertures.items():
  511. new_apid += 1
  512. new_apertures[str(new_apid)] = deepcopy(ap_val)
  513. def init_func(new_obj, app_obj):
  514. new_obj.options.update(new_options)
  515. new_obj.options['name'] = outname
  516. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  517. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  518. new_obj.apertures = deepcopy(new_apertures)
  519. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  520. new_obj.source_file = app_obj.f_handlers.export_gerber(obj_name=outname, filename=None,
  521. local_use=new_obj, use_thread=False)
  522. self.app.app_obj.new_object('gerber', outname, init_func)
  523. def on_ring_method(self, grb_obj, outname):
  524. circ_r_val = self.ui.circular_ring_entry.get_value()
  525. oblong_r_val = self.ui.oblong_ring_entry.get_value()
  526. square_r_val = self.ui.square_ring_entry.get_value()
  527. rect_r_val = self.ui.rectangular_ring_entry.get_value()
  528. other_r_val = self.ui.other_ring_entry.get_value()
  529. dia = None
  530. new_options = {}
  531. for opt in grb_obj.options:
  532. new_options[opt] = deepcopy(grb_obj.options[opt])
  533. if isinstance(grb_obj.solid_geometry, list):
  534. temp_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  535. else:
  536. temp_solid_geometry = grb_obj.solid_geometry
  537. punched_solid_geometry = temp_solid_geometry
  538. new_apertures = deepcopy(grb_obj.apertures)
  539. new_apertures_items = new_apertures.items()
  540. # find maximum aperture id
  541. new_apid = max([int(x) for x, __ in new_apertures_items])
  542. # selected codes in the apertures UI table
  543. sel_apid = []
  544. for it in self.ui.apertures_table.selectedItems():
  545. sel_apid.append(it.text())
  546. # store here the clear geometry, the key is the new aperture size
  547. holes_apertures = {}
  548. for apid, apid_value in grb_obj.apertures.items():
  549. ap_type = apid_value['type']
  550. punching_geo = []
  551. if apid in sel_apid:
  552. if ap_type == 'C' and self.ui.circular_cb.get_value():
  553. dia = float(apid_value['size']) - (2 * circ_r_val)
  554. for elem in apid_value['geometry']:
  555. if 'follow' in elem and isinstance(elem['follow'], Point):
  556. punching_geo.append(elem['follow'].buffer(dia / 2))
  557. elif ap_type == 'O' and self.ui.oblong_cb.get_value():
  558. width = float(apid_value['width'])
  559. height = float(apid_value['height'])
  560. if width > height:
  561. dia = float(apid_value['height']) - (2 * oblong_r_val)
  562. else:
  563. dia = float(apid_value['width']) - (2 * oblong_r_val)
  564. for elem in grb_obj.apertures[apid]['geometry']:
  565. if 'follow' in elem:
  566. if isinstance(elem['follow'], Point):
  567. punching_geo.append(elem['follow'].buffer(dia / 2))
  568. elif ap_type == 'R':
  569. width = float(apid_value['width'])
  570. height = float(apid_value['height'])
  571. # if the height == width (float numbers so the reason for the following)
  572. if round(width, self.decimals) == round(height, self.decimals):
  573. if self.ui.square_cb.get_value():
  574. dia = float(apid_value['height']) - (2 * square_r_val)
  575. for elem in grb_obj.apertures[apid]['geometry']:
  576. if 'follow' in elem:
  577. if isinstance(elem['follow'], Point):
  578. punching_geo.append(elem['follow'].buffer(dia / 2))
  579. elif self.ui.rectangular_cb.get_value():
  580. if width > height:
  581. dia = float(apid_value['height']) - (2 * rect_r_val)
  582. else:
  583. dia = float(apid_value['width']) - (2 * rect_r_val)
  584. for elem in grb_obj.apertures[apid]['geometry']:
  585. if 'follow' in elem:
  586. if isinstance(elem['follow'], Point):
  587. punching_geo.append(elem['follow'].buffer(dia / 2))
  588. elif self.ui.other_cb.get_value():
  589. try:
  590. dia = float(apid_value['size']) - (2 * other_r_val)
  591. except KeyError:
  592. if ap_type == 'AM':
  593. pol = apid_value['geometry'][0]['solid']
  594. x0, y0, x1, y1 = pol.bounds
  595. dx = x1 - x0
  596. dy = y1 - y0
  597. if dx <= dy:
  598. dia = dx - (2 * other_r_val)
  599. else:
  600. dia = dy - (2 * other_r_val)
  601. for elem in grb_obj.apertures[apid]['geometry']:
  602. if 'follow' in elem:
  603. if isinstance(elem['follow'], Point):
  604. punching_geo.append(elem['follow'].buffer(dia / 2))
  605. # if dia is None then none of the above applied so we skip the following
  606. if dia is None:
  607. continue
  608. punching_geo = MultiPolygon(punching_geo)
  609. if punching_geo is None or punching_geo.is_empty:
  610. continue
  611. punched_solid_geometry = punched_solid_geometry.difference(punching_geo)
  612. # update the gerber apertures to include the clear geometry so it can be exported successfully
  613. for elem in apid_value['geometry']:
  614. # make it work only for Gerber Flashes who are Points in 'follow'
  615. if 'solid' in elem and isinstance(elem['follow'], Point):
  616. clear_apid_size = dia
  617. for geo in punching_geo:
  618. # since there may be drills that do not drill into a pad we test only for geos in a pad
  619. if geo.within(elem['solid']):
  620. geo_elem = {'clear': geo.centroid}
  621. if clear_apid_size not in holes_apertures:
  622. holes_apertures[clear_apid_size] = {
  623. 'type': 'C',
  624. 'size': clear_apid_size,
  625. 'geometry': []
  626. }
  627. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  628. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  629. # size and add there the clear geometry
  630. for hole_size, ap_val in holes_apertures.items():
  631. new_apid += 1
  632. new_apertures[str(new_apid)] = deepcopy(ap_val)
  633. def init_func(new_obj, app_obj):
  634. new_obj.options.update(new_options)
  635. new_obj.options['name'] = outname
  636. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  637. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  638. new_obj.apertures = deepcopy(new_apertures)
  639. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  640. new_obj.source_file = app_obj.f_handlers.export_gerber(obj_name=outname, filename=None,
  641. local_use=new_obj, use_thread=False)
  642. self.app.app_obj.new_object('gerber', outname, init_func)
  643. def on_proportional_method(self, grb_obj, outname):
  644. prop_factor = self.ui.factor_entry.get_value() / 100.0
  645. dia = None
  646. new_options = {}
  647. for opt in grb_obj.options:
  648. new_options[opt] = deepcopy(grb_obj.options[opt])
  649. if isinstance(grb_obj.solid_geometry, list):
  650. temp_solid_geometry = MultiPolygon(grb_obj.solid_geometry)
  651. else:
  652. temp_solid_geometry = grb_obj.solid_geometry
  653. punched_solid_geometry = temp_solid_geometry
  654. new_apertures = deepcopy(grb_obj.apertures)
  655. new_apertures_items = new_apertures.items()
  656. # find maximum aperture id
  657. new_apid = max([int(x) for x, __ in new_apertures_items])
  658. # selected codes in the apertures UI table
  659. sel_apid = []
  660. for it in self.ui.apertures_table.selectedItems():
  661. sel_apid.append(it.text())
  662. # store here the clear geometry, the key is the new aperture size
  663. holes_apertures = {}
  664. for apid, apid_value in grb_obj.apertures.items():
  665. ap_type = apid_value['type']
  666. punching_geo = []
  667. if apid in sel_apid:
  668. if ap_type == 'C' and self.ui.circular_cb.get_value():
  669. dia = float(apid_value['size']) * prop_factor
  670. for elem in apid_value['geometry']:
  671. if 'follow' in elem and isinstance(elem['follow'], Point):
  672. punching_geo.append(elem['follow'].buffer(dia / 2))
  673. elif ap_type == 'O' and self.ui.oblong_cb.get_value():
  674. width = float(apid_value['width'])
  675. height = float(apid_value['height'])
  676. if width > height:
  677. dia = float(apid_value['height']) * prop_factor
  678. else:
  679. dia = float(apid_value['width']) * prop_factor
  680. for elem in grb_obj.apertures[apid]['geometry']:
  681. if 'follow' in elem:
  682. if isinstance(elem['follow'], Point):
  683. punching_geo.append(elem['follow'].buffer(dia / 2))
  684. elif ap_type == 'R':
  685. width = float(apid_value['width'])
  686. height = float(apid_value['height'])
  687. # if the height == width (float numbers so the reason for the following)
  688. if round(width, self.decimals) == round(height, self.decimals):
  689. if self.ui.square_cb.get_value():
  690. dia = float(apid_value['height']) * prop_factor
  691. for elem in grb_obj.apertures[apid]['geometry']:
  692. if 'follow' in elem:
  693. if isinstance(elem['follow'], Point):
  694. punching_geo.append(elem['follow'].buffer(dia / 2))
  695. elif self.ui.rectangular_cb.get_value():
  696. if width > height:
  697. dia = float(apid_value['height']) * prop_factor
  698. else:
  699. dia = float(apid_value['width']) * prop_factor
  700. for elem in grb_obj.apertures[apid]['geometry']:
  701. if 'follow' in elem:
  702. if isinstance(elem['follow'], Point):
  703. punching_geo.append(elem['follow'].buffer(dia / 2))
  704. elif self.ui.other_cb.get_value():
  705. try:
  706. dia = float(apid_value['size']) * prop_factor
  707. except KeyError:
  708. if ap_type == 'AM':
  709. pol = apid_value['geometry'][0]['solid']
  710. x0, y0, x1, y1 = pol.bounds
  711. dx = x1 - x0
  712. dy = y1 - y0
  713. if dx <= dy:
  714. dia = dx * prop_factor
  715. else:
  716. dia = dy * prop_factor
  717. for elem in grb_obj.apertures[apid]['geometry']:
  718. if 'follow' in elem:
  719. if isinstance(elem['follow'], Point):
  720. punching_geo.append(elem['follow'].buffer(dia / 2))
  721. # if dia is None then none of the above applied so we skip the following
  722. if dia is None:
  723. continue
  724. punching_geo = MultiPolygon(punching_geo)
  725. if punching_geo is None or punching_geo.is_empty:
  726. continue
  727. punched_solid_geometry = punched_solid_geometry.difference(punching_geo)
  728. # update the gerber apertures to include the clear geometry so it can be exported successfully
  729. for elem in apid_value['geometry']:
  730. # make it work only for Gerber Flashes who are Points in 'follow'
  731. if 'solid' in elem and isinstance(elem['follow'], Point):
  732. clear_apid_size = dia
  733. for geo in punching_geo:
  734. # since there may be drills that do not drill into a pad we test only for geos in a pad
  735. if geo.within(elem['solid']):
  736. geo_elem = {'clear': geo.centroid}
  737. if clear_apid_size not in holes_apertures:
  738. holes_apertures[clear_apid_size] = {
  739. 'type': 'C',
  740. 'size': clear_apid_size,
  741. 'geometry': []
  742. }
  743. holes_apertures[clear_apid_size]['geometry'].append(deepcopy(geo_elem))
  744. # add the clear geometry to new apertures; it's easier than to test if there are apertures with the same
  745. # size and add there the clear geometry
  746. for hole_size, ap_val in holes_apertures.items():
  747. new_apid += 1
  748. new_apertures[str(new_apid)] = deepcopy(ap_val)
  749. def init_func(new_obj, app_obj):
  750. new_obj.options.update(new_options)
  751. new_obj.options['name'] = outname
  752. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  753. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  754. new_obj.apertures = deepcopy(new_apertures)
  755. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  756. new_obj.source_file = app_obj.f_handlers.export_gerber(obj_name=outname, filename=None,
  757. local_use=new_obj, use_thread=False)
  758. self.app.app_obj.new_object('gerber', outname, init_func)
  759. def on_mark_cb_click_table(self):
  760. """
  761. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  762. :return:
  763. """
  764. try:
  765. cw = self.sender()
  766. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  767. cw_row = cw_index.row()
  768. except AttributeError:
  769. cw_row = 0
  770. except TypeError:
  771. return
  772. try:
  773. aperture = self.ui.apertures_table.item(cw_row, 0).text()
  774. except AttributeError:
  775. return
  776. # get the Gerber file who is the source of the punched Gerber
  777. selection_index = self.ui.gerber_object_combo.currentIndex()
  778. model_index = self.app.collection.index(selection_index, 0, self.ui.gerber_object_combo.rootModelIndex())
  779. try:
  780. grb_obj = model_index.internalPointer().obj
  781. except Exception:
  782. return
  783. if self.ui.apertures_table.cellWidget(cw_row, 3).isChecked():
  784. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  785. grb_obj.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AA',
  786. marked_aperture=aperture, visible=True, run_thread=True)
  787. else:
  788. grb_obj.clear_plot_apertures(aperture=aperture)
  789. def reset_fields(self):
  790. self.ui.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  791. self.ui.exc_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  792. self.ui_disconnect()
  793. class PunchUI:
  794. toolName = _("Punch Gerber")
  795. def __init__(self, layout, app):
  796. self.app = app
  797. self.decimals = self.app.decimals
  798. self.layout = layout
  799. # ## Title
  800. title_label = QtWidgets.QLabel("%s" % self.toolName)
  801. title_label.setStyleSheet("""
  802. QLabel
  803. {
  804. font-size: 16px;
  805. font-weight: bold;
  806. }
  807. """)
  808. self.layout.addWidget(title_label)
  809. # Punch Drill holes
  810. self.layout.addWidget(QtWidgets.QLabel(""))
  811. # ## Grid Layout
  812. grid_lay = QtWidgets.QGridLayout()
  813. self.layout.addLayout(grid_lay)
  814. grid_lay.setColumnStretch(0, 1)
  815. grid_lay.setColumnStretch(1, 0)
  816. # ## Gerber Object
  817. self.gerber_object_combo = FCComboBox()
  818. self.gerber_object_combo.setModel(self.app.collection)
  819. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  820. self.gerber_object_combo.is_last = True
  821. self.gerber_object_combo.obj_type = "Gerber"
  822. self.grb_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  823. self.grb_label.setToolTip('%s.' % _("Gerber into which to punch holes"))
  824. grid_lay.addWidget(self.grb_label, 0, 0, 1, 2)
  825. grid_lay.addWidget(self.gerber_object_combo, 1, 0, 1, 2)
  826. separator_line = QtWidgets.QFrame()
  827. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  828. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  829. grid_lay.addWidget(separator_line, 2, 0, 1, 2)
  830. self.padt_label = QtWidgets.QLabel("<b>%s</b>" % _("Processed Pads Type"))
  831. self.padt_label.setToolTip(
  832. _("The type of pads shape to be processed.\n"
  833. "If the PCB has many SMD pads with rectangular pads,\n"
  834. "disable the Rectangular aperture.")
  835. )
  836. grid_lay.addWidget(self.padt_label, 3, 0, 1, 2)
  837. pad_all_grid = QtWidgets.QGridLayout()
  838. pad_all_grid.setColumnStretch(0, 0)
  839. pad_all_grid.setColumnStretch(1, 1)
  840. grid_lay.addLayout(pad_all_grid, 5, 0, 1, 2)
  841. pad_grid = QtWidgets.QGridLayout()
  842. pad_grid.setColumnStretch(0, 0)
  843. pad_all_grid.addLayout(pad_grid, 0, 0)
  844. # Select all
  845. self.select_all_cb = FCCheckBox('%s' % _("ALL"))
  846. pad_grid.addWidget(self.select_all_cb, 0, 0)
  847. # Circular Aperture Selection
  848. self.circular_cb = FCCheckBox('%s' % _("Circular"))
  849. self.circular_cb.setToolTip(
  850. _("Process Circular Pads.")
  851. )
  852. pad_grid.addWidget(self.circular_cb, 1, 0)
  853. # Oblong Aperture Selection
  854. self.oblong_cb = FCCheckBox('%s' % _("Oblong"))
  855. self.oblong_cb.setToolTip(
  856. _("Process Oblong Pads.")
  857. )
  858. pad_grid.addWidget(self.oblong_cb, 2, 0)
  859. # Square Aperture Selection
  860. self.square_cb = FCCheckBox('%s' % _("Square"))
  861. self.square_cb.setToolTip(
  862. _("Process Square Pads.")
  863. )
  864. pad_grid.addWidget(self.square_cb, 3, 0)
  865. # Rectangular Aperture Selection
  866. self.rectangular_cb = FCCheckBox('%s' % _("Rectangular"))
  867. self.rectangular_cb.setToolTip(
  868. _("Process Rectangular Pads.")
  869. )
  870. pad_grid.addWidget(self.rectangular_cb, 4, 0)
  871. # Others type of Apertures Selection
  872. self.other_cb = FCCheckBox('%s' % _("Others"))
  873. self.other_cb.setToolTip(
  874. _("Process pads not in the categories above.")
  875. )
  876. pad_grid.addWidget(self.other_cb, 5, 0)
  877. # Aperture Table
  878. self.apertures_table = FCTable()
  879. pad_all_grid.addWidget(self.apertures_table, 0, 1)
  880. self.apertures_table.setColumnCount(4)
  881. self.apertures_table.setHorizontalHeaderLabels([_('Code'), _('Type'), _('Size'), 'M'])
  882. self.apertures_table.setSortingEnabled(False)
  883. self.apertures_table.setRowCount(0)
  884. self.apertures_table.resizeColumnsToContents()
  885. self.apertures_table.resizeRowsToContents()
  886. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  887. _("Aperture Code"))
  888. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  889. _("Type of aperture: circular, rectangle, macros etc"))
  890. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  891. _("Aperture Size:"))
  892. self.apertures_table.horizontalHeaderItem(3).setToolTip(
  893. _("Mark the aperture instances on canvas."))
  894. sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Preferred)
  895. self.apertures_table.setSizePolicy(sizePolicy)
  896. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  897. separator_line = QtWidgets.QFrame()
  898. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  899. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  900. grid_lay.addWidget(separator_line, 10, 0, 1, 2)
  901. # Grid Layout
  902. grid0 = QtWidgets.QGridLayout()
  903. self.layout.addLayout(grid0)
  904. grid0.setColumnStretch(0, 0)
  905. grid0.setColumnStretch(1, 1)
  906. self.method_label = QtWidgets.QLabel('<b>%s:</b>' % _("Method"))
  907. self.method_label.setToolTip(
  908. _("The punch hole source can be:\n"
  909. "- Excellon Object-> the Excellon object drills center will serve as reference.\n"
  910. "- Fixed Diameter -> will try to use the pads center as reference adding fixed diameter holes.\n"
  911. "- Fixed Annular Ring -> will try to keep a set annular ring.\n"
  912. "- Proportional -> will make a Gerber punch hole having the diameter a percentage of the pad diameter.")
  913. )
  914. self.method_punch = RadioSet(
  915. [
  916. {'label': _('Excellon'), 'value': 'exc'},
  917. {'label': _("Fixed Diameter"), 'value': 'fixed'},
  918. {'label': _("Proportional"), 'value': 'prop'},
  919. {'label': _("Fixed Annular Ring"), 'value': 'ring'}
  920. ],
  921. orientation='vertical',
  922. stretch=False)
  923. grid0.addWidget(self.method_label, 0, 0, 1, 2)
  924. grid0.addWidget(self.method_punch, 1, 0, 1, 2)
  925. separator_line = QtWidgets.QFrame()
  926. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  927. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  928. grid0.addWidget(separator_line, 2, 0, 1, 2)
  929. self.exc_label = QtWidgets.QLabel('<b>%s</b>' % _("Excellon"))
  930. self.exc_label.setToolTip(
  931. _("Remove the geometry of Excellon from the Gerber to create the holes in pads.")
  932. )
  933. self.exc_combo = FCComboBox()
  934. self.exc_combo.setModel(self.app.collection)
  935. self.exc_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  936. self.exc_combo.is_last = True
  937. self.exc_combo.obj_type = "Excellon"
  938. grid0.addWidget(self.exc_label, 3, 0, 1, 2)
  939. grid0.addWidget(self.exc_combo, 4, 0, 1, 2)
  940. # Fixed Dia
  941. self.fixed_label = QtWidgets.QLabel('<b>%s</b>' % _("Fixed Diameter"))
  942. grid0.addWidget(self.fixed_label, 6, 0, 1, 2)
  943. # Diameter value
  944. self.dia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  945. self.dia_entry.set_precision(self.decimals)
  946. self.dia_entry.set_range(0.0000, 9999.9999)
  947. self.dia_label = QtWidgets.QLabel('%s:' % _("Value"))
  948. self.dia_label.setToolTip(
  949. _("Fixed hole diameter.")
  950. )
  951. grid0.addWidget(self.dia_label, 8, 0)
  952. grid0.addWidget(self.dia_entry, 8, 1)
  953. # #############################################################################################################
  954. # RING FRAME
  955. # #############################################################################################################
  956. self.ring_frame = QtWidgets.QFrame()
  957. self.ring_frame.setContentsMargins(0, 0, 0, 0)
  958. grid0.addWidget(self.ring_frame, 10, 0, 1, 2)
  959. self.ring_box = QtWidgets.QVBoxLayout()
  960. self.ring_box.setContentsMargins(0, 0, 0, 0)
  961. self.ring_frame.setLayout(self.ring_box)
  962. # Annular Ring value
  963. self.ring_label = QtWidgets.QLabel('<b>%s</b>' % _("Fixed Annular Ring"))
  964. self.ring_label.setToolTip(
  965. _("The size of annular ring.\n"
  966. "The copper sliver between the hole exterior\n"
  967. "and the margin of the copper pad.")
  968. )
  969. self.ring_box.addWidget(self.ring_label)
  970. # ## Grid Layout
  971. self.grid1 = QtWidgets.QGridLayout()
  972. self.grid1.setColumnStretch(0, 0)
  973. self.grid1.setColumnStretch(1, 1)
  974. self.ring_box.addLayout(self.grid1)
  975. # Circular Annular Ring Value
  976. self.circular_ring_label = QtWidgets.QLabel('%s:' % _("Circular"))
  977. self.circular_ring_label.setToolTip(
  978. _("The size of annular ring for circular pads.")
  979. )
  980. self.circular_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  981. self.circular_ring_entry.set_precision(self.decimals)
  982. self.circular_ring_entry.set_range(0.0000, 9999.9999)
  983. self.grid1.addWidget(self.circular_ring_label, 3, 0)
  984. self.grid1.addWidget(self.circular_ring_entry, 3, 1)
  985. # Oblong Annular Ring Value
  986. self.oblong_ring_label = QtWidgets.QLabel('%s:' % _("Oblong"))
  987. self.oblong_ring_label.setToolTip(
  988. _("The size of annular ring for oblong pads.")
  989. )
  990. self.oblong_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  991. self.oblong_ring_entry.set_precision(self.decimals)
  992. self.oblong_ring_entry.set_range(0.0000, 9999.9999)
  993. self.grid1.addWidget(self.oblong_ring_label, 4, 0)
  994. self.grid1.addWidget(self.oblong_ring_entry, 4, 1)
  995. # Square Annular Ring Value
  996. self.square_ring_label = QtWidgets.QLabel('%s:' % _("Square"))
  997. self.square_ring_label.setToolTip(
  998. _("The size of annular ring for square pads.")
  999. )
  1000. self.square_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1001. self.square_ring_entry.set_precision(self.decimals)
  1002. self.square_ring_entry.set_range(0.0000, 9999.9999)
  1003. self.grid1.addWidget(self.square_ring_label, 5, 0)
  1004. self.grid1.addWidget(self.square_ring_entry, 5, 1)
  1005. # Rectangular Annular Ring Value
  1006. self.rectangular_ring_label = QtWidgets.QLabel('%s:' % _("Rectangular"))
  1007. self.rectangular_ring_label.setToolTip(
  1008. _("The size of annular ring for rectangular pads.")
  1009. )
  1010. self.rectangular_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1011. self.rectangular_ring_entry.set_precision(self.decimals)
  1012. self.rectangular_ring_entry.set_range(0.0000, 9999.9999)
  1013. self.grid1.addWidget(self.rectangular_ring_label, 6, 0)
  1014. self.grid1.addWidget(self.rectangular_ring_entry, 6, 1)
  1015. # Others Annular Ring Value
  1016. self.other_ring_label = QtWidgets.QLabel('%s:' % _("Others"))
  1017. self.other_ring_label.setToolTip(
  1018. _("The size of annular ring for other pads.")
  1019. )
  1020. self.other_ring_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1021. self.other_ring_entry.set_precision(self.decimals)
  1022. self.other_ring_entry.set_range(0.0000, 9999.9999)
  1023. self.grid1.addWidget(self.other_ring_label, 7, 0)
  1024. self.grid1.addWidget(self.other_ring_entry, 7, 1)
  1025. # #############################################################################################################
  1026. # Proportional value
  1027. self.prop_label = QtWidgets.QLabel('<b>%s</b>' % _("Proportional Diameter"))
  1028. grid0.addWidget(self.prop_label, 12, 0, 1, 2)
  1029. # Diameter value
  1030. self.factor_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  1031. self.factor_entry.set_precision(self.decimals)
  1032. self.factor_entry.set_range(0.0000, 100.0000)
  1033. self.factor_entry.setSingleStep(0.1)
  1034. self.factor_label = QtWidgets.QLabel('%s:' % _("Value"))
  1035. self.factor_label.setToolTip(
  1036. _("Proportional Diameter.\n"
  1037. "The hole diameter will be a fraction of the pad size.")
  1038. )
  1039. grid0.addWidget(self.factor_label, 13, 0)
  1040. grid0.addWidget(self.factor_entry, 13, 1)
  1041. separator_line3 = QtWidgets.QFrame()
  1042. separator_line3.setFrameShape(QtWidgets.QFrame.HLine)
  1043. separator_line3.setFrameShadow(QtWidgets.QFrame.Sunken)
  1044. grid0.addWidget(separator_line3, 14, 0, 1, 2)
  1045. # Buttons
  1046. self.punch_object_button = QtWidgets.QPushButton(_("Punch Gerber"))
  1047. self.punch_object_button.setIcon(QtGui.QIcon(self.app.resource_location + '/punch32.png'))
  1048. self.punch_object_button.setToolTip(
  1049. _("Create a Gerber object from the selected object, within\n"
  1050. "the specified box.")
  1051. )
  1052. self.punch_object_button.setStyleSheet("""
  1053. QPushButton
  1054. {
  1055. font-weight: bold;
  1056. }
  1057. """)
  1058. self.layout.addWidget(self.punch_object_button)
  1059. self.layout.addStretch()
  1060. # ## Reset Tool
  1061. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  1062. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  1063. self.reset_button.setToolTip(
  1064. _("Will reset the tool parameters.")
  1065. )
  1066. self.reset_button.setStyleSheet("""
  1067. QPushButton
  1068. {
  1069. font-weight: bold;
  1070. }
  1071. """)
  1072. self.layout.addWidget(self.reset_button)
  1073. self.circular_ring_entry.setEnabled(False)
  1074. self.oblong_ring_entry.setEnabled(False)
  1075. self.square_ring_entry.setEnabled(False)
  1076. self.rectangular_ring_entry.setEnabled(False)
  1077. self.other_ring_entry.setEnabled(False)
  1078. self.dia_entry.hide()
  1079. self.dia_label.hide()
  1080. self.factor_label.hide()
  1081. self.factor_entry.hide()
  1082. # #################################### FINSIHED GUI ###########################
  1083. # #############################################################################
  1084. def confirmation_message(self, accepted, minval, maxval):
  1085. if accepted is False:
  1086. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1087. self.decimals,
  1088. minval,
  1089. self.decimals,
  1090. maxval), False)
  1091. else:
  1092. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1093. def confirmation_message_int(self, accepted, minval, maxval):
  1094. if accepted is False:
  1095. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1096. (_("Edited value is out of range"), minval, maxval), False)
  1097. else:
  1098. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)