ToolExtractDrills.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 1/10/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import RadioSet, FCDoubleSpinner, FCCheckBox
  10. from shapely.geometry import Point
  11. import logging
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. import builtins
  15. fcTranslate.apply_language('strings')
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. log = logging.getLogger('base')
  19. class ToolExtractDrills(FlatCAMTool):
  20. toolName = _("Extract Drills")
  21. def __init__(self, app):
  22. FlatCAMTool.__init__(self, app)
  23. self.decimals = self.app.decimals
  24. # ## Title
  25. title_label = QtWidgets.QLabel("%s" % self.toolName)
  26. title_label.setStyleSheet("""
  27. QLabel
  28. {
  29. font-size: 16px;
  30. font-weight: bold;
  31. }
  32. """)
  33. self.layout.addWidget(title_label)
  34. self.empty_lb = QtWidgets.QLabel("")
  35. self.layout.addWidget(self.empty_lb)
  36. # ## Grid Layout
  37. grid_lay = QtWidgets.QGridLayout()
  38. self.layout.addLayout(grid_lay)
  39. grid_lay.setColumnStretch(0, 1)
  40. grid_lay.setColumnStretch(1, 0)
  41. # ## Gerber Object
  42. self.gerber_object_combo = QtWidgets.QComboBox()
  43. self.gerber_object_combo.setModel(self.app.collection)
  44. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  45. self.gerber_object_combo.setCurrentIndex(1)
  46. self.grb_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  47. self.grb_label.setToolTip('%s.' % _("Gerber from which to extract drill holes"))
  48. # grid_lay.addRow("Bottom Layer:", self.object_combo)
  49. grid_lay.addWidget(self.grb_label, 0, 0, 1, 2)
  50. grid_lay.addWidget(self.gerber_object_combo, 1, 0, 1, 2)
  51. self.padt_label = QtWidgets.QLabel("<b>%s</b>" % _("Processed Pads Type"))
  52. self.padt_label.setToolTip(
  53. _("The type of pads shape to be processed.\n"
  54. "If the PCB has many SMD pads with rectangular pads,\n"
  55. "disable the Rectangular aperture.")
  56. )
  57. grid_lay.addWidget(self.padt_label, 2, 0, 1, 2)
  58. # Circular Aperture Selection
  59. self.circular_cb = FCCheckBox('%s' % _("Circular"))
  60. self.circular_cb.setToolTip(
  61. _("Create drills from circular pads.")
  62. )
  63. grid_lay.addWidget(self.circular_cb, 3, 0, 1, 2)
  64. # Oblong Aperture Selection
  65. self.oblong_cb = FCCheckBox('%s' % _("Oblong"))
  66. self.oblong_cb.setToolTip(
  67. _("Create drills from oblong pads.")
  68. )
  69. grid_lay.addWidget(self.oblong_cb, 4, 0, 1, 2)
  70. # Square Aperture Selection
  71. self.square_cb = FCCheckBox('%s' % _("Square"))
  72. self.square_cb.setToolTip(
  73. _("Create drills from square pads.")
  74. )
  75. grid_lay.addWidget(self.square_cb, 5, 0, 1, 2)
  76. # Rectangular Aperture Selection
  77. self.rectangular_cb = FCCheckBox('%s' % _("Rectangular"))
  78. self.rectangular_cb.setToolTip(
  79. _("Create drills from rectangular pads.")
  80. )
  81. grid_lay.addWidget(self.rectangular_cb, 6, 0, 1, 2)
  82. # Others type of Apertures Selection
  83. self.other_cb = FCCheckBox('%s' % _("Others"))
  84. self.other_cb.setToolTip(
  85. _("Create drills from other types of pad shape.")
  86. )
  87. grid_lay.addWidget(self.other_cb, 7, 0, 1, 2)
  88. separator_line = QtWidgets.QFrame()
  89. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  90. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  91. grid_lay.addWidget(separator_line, 8, 0, 1, 2)
  92. # ## Grid Layout
  93. grid1 = QtWidgets.QGridLayout()
  94. self.layout.addLayout(grid1)
  95. grid1.setColumnStretch(0, 0)
  96. grid1.setColumnStretch(1, 1)
  97. # ## Axis
  98. self.hole_size_radio = RadioSet([{'label': _("Fixed"), 'value': 'fixed'},
  99. {'label': _("Proportional"), 'value': 'prop'}])
  100. self.hole_size_label = QtWidgets.QLabel('%s:' % _("Hole Size"))
  101. self.hole_size_label.setToolTip(
  102. _("The type of hole size. Can be:\n"
  103. "- Fixed -> all holes will have a set size\n"
  104. "- Proprotional -> each hole will havea a variable size\n"
  105. "such as to preserve a set annular ring"))
  106. grid1.addWidget(self.hole_size_label, 3, 0)
  107. grid1.addWidget(self.hole_size_radio, 3, 1)
  108. # grid_lay1.addWidget(QtWidgets.QLabel(''))
  109. separator_line = QtWidgets.QFrame()
  110. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  111. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  112. grid1.addWidget(separator_line, 5, 0, 1, 2)
  113. # Diameter value
  114. self.dia_entry = FCDoubleSpinner()
  115. self.dia_entry.set_precision(self.decimals)
  116. self.dia_entry.set_range(0.0000, 9999.9999)
  117. self.dia_label = QtWidgets.QLabel('%s:' % _("Diameter"))
  118. self.dia_label.setToolTip(
  119. _("Fixed hole diameter.")
  120. )
  121. grid1.addWidget(self.dia_label, 7, 0)
  122. grid1.addWidget(self.dia_entry, 7, 1)
  123. self.ring_frame = QtWidgets.QFrame()
  124. self.ring_frame.setContentsMargins(0, 0, 0, 0)
  125. self.layout.addWidget(self.ring_frame)
  126. self.ring_box = QtWidgets.QVBoxLayout()
  127. self.ring_box.setContentsMargins(0, 0, 0, 0)
  128. self.ring_frame.setLayout(self.ring_box)
  129. # ## Grid Layout
  130. grid2 = QtWidgets.QGridLayout()
  131. grid2.setColumnStretch(0, 0)
  132. grid2.setColumnStretch(1, 1)
  133. self.ring_box.addLayout(grid2)
  134. # Annular Ring value
  135. self.ring_label = QtWidgets.QLabel('<b>%s</b>' % _("Annular Ring"))
  136. self.ring_label.setToolTip(
  137. _("The size of annular ring.\n"
  138. "The copper sliver between the drill hole exterior\n"
  139. "and the margin of the copper pad.")
  140. )
  141. grid2.addWidget(self.ring_label, 0, 0, 1, 2)
  142. # Circular Annular Ring Value
  143. self.circular_ring_label = QtWidgets.QLabel('%s:' % _("Circular"))
  144. self.circular_ring_label.setToolTip(
  145. _("The size of annular ring for circular pads.")
  146. )
  147. self.circular_ring_entry = FCDoubleSpinner()
  148. self.circular_ring_entry.set_precision(self.decimals)
  149. self.circular_ring_entry.set_range(0.0000, 9999.9999)
  150. grid2.addWidget(self.circular_ring_label, 1, 0)
  151. grid2.addWidget(self.circular_ring_entry, 1, 1)
  152. # Oblong Annular Ring Value
  153. self.oblong_ring_label = QtWidgets.QLabel('%s:' % _("Oblong"))
  154. self.oblong_ring_label.setToolTip(
  155. _("The size of annular ring for oblong pads.")
  156. )
  157. self.oblong_ring_entry = FCDoubleSpinner()
  158. self.oblong_ring_entry.set_precision(self.decimals)
  159. self.oblong_ring_entry.set_range(0.0000, 9999.9999)
  160. grid2.addWidget(self.oblong_ring_label, 2, 0)
  161. grid2.addWidget(self.oblong_ring_entry, 2, 1)
  162. # Square Annular Ring Value
  163. self.square_ring_label = QtWidgets.QLabel('%s:' % _("Square"))
  164. self.square_ring_label.setToolTip(
  165. _("The size of annular ring for square pads.")
  166. )
  167. self.square_ring_entry = FCDoubleSpinner()
  168. self.square_ring_entry.set_precision(self.decimals)
  169. self.square_ring_entry.set_range(0.0000, 9999.9999)
  170. grid2.addWidget(self.square_ring_label, 3, 0)
  171. grid2.addWidget(self.square_ring_entry, 3, 1)
  172. # Rectangular Annular Ring Value
  173. self.rectangular_ring_label = QtWidgets.QLabel('%s:' % _("Rectangular"))
  174. self.rectangular_ring_label.setToolTip(
  175. _("The size of annular ring for rectangular pads.")
  176. )
  177. self.rectangular_ring_entry = FCDoubleSpinner()
  178. self.rectangular_ring_entry.set_precision(self.decimals)
  179. self.rectangular_ring_entry.set_range(0.0000, 9999.9999)
  180. grid2.addWidget(self.rectangular_ring_label, 4, 0)
  181. grid2.addWidget(self.rectangular_ring_entry, 4, 1)
  182. # Others Annular Ring Value
  183. self.other_ring_label = QtWidgets.QLabel('%s:' % _("Others"))
  184. self.other_ring_label.setToolTip(
  185. _("The size of annular ring for other pads.")
  186. )
  187. self.other_ring_entry = FCDoubleSpinner()
  188. self.other_ring_entry.set_precision(self.decimals)
  189. self.other_ring_entry.set_range(0.0000, 9999.9999)
  190. grid2.addWidget(self.other_ring_label, 5, 0)
  191. grid2.addWidget(self.other_ring_entry, 5, 1)
  192. # Extract drills from Gerber apertures flashes (pads)
  193. self.e_drills_button = QtWidgets.QPushButton(_("Extract Drills"))
  194. self.e_drills_button.setToolTip(
  195. _("Extract drills from a given Gerber file.")
  196. )
  197. self.e_drills_button.setStyleSheet("""
  198. QPushButton
  199. {
  200. font-weight: bold;
  201. }
  202. """)
  203. self.layout.addWidget(self.e_drills_button)
  204. self.layout.addStretch()
  205. # ## Reset Tool
  206. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  207. self.reset_button.setToolTip(
  208. _("Will reset the tool parameters.")
  209. )
  210. self.reset_button.setStyleSheet("""
  211. QPushButton
  212. {
  213. font-weight: bold;
  214. }
  215. """)
  216. self.layout.addWidget(self.reset_button)
  217. self.circular_ring_entry.setEnabled(False)
  218. self.oblong_ring_entry.setEnabled(False)
  219. self.square_ring_entry.setEnabled(False)
  220. self.rectangular_ring_entry.setEnabled(False)
  221. self.other_ring_entry.setEnabled(False)
  222. # ## Signals
  223. self.hole_size_radio.activated_custom.connect(self.on_hole_size_toggle)
  224. self.e_drills_button.clicked.connect(self.on_extract_drills_click)
  225. self.reset_button.clicked.connect(self.set_tool_ui)
  226. self.circular_cb.stateChanged.connect(
  227. lambda state:
  228. self.circular_ring_entry.setDisabled(False) if state else self.circular_ring_entry.setDisabled(True)
  229. )
  230. self.oblong_cb.stateChanged.connect(
  231. lambda state:
  232. self.oblong_ring_entry.setDisabled(False) if state else self.oblong_ring_entry.setDisabled(True)
  233. )
  234. self.square_cb.stateChanged.connect(
  235. lambda state:
  236. self.square_ring_entry.setDisabled(False) if state else self.square_ring_entry.setDisabled(True)
  237. )
  238. self.rectangular_cb.stateChanged.connect(
  239. lambda state:
  240. self.rectangular_ring_entry.setDisabled(False) if state else self.rectangular_ring_entry.setDisabled(True)
  241. )
  242. self.other_cb.stateChanged.connect(
  243. lambda state:
  244. self.other_ring_entry.setDisabled(False) if state else self.other_ring_entry.setDisabled(True)
  245. )
  246. def install(self, icon=None, separator=None, **kwargs):
  247. FlatCAMTool.install(self, icon, separator, shortcut='ALT+I', **kwargs)
  248. def run(self, toggle=True):
  249. self.app.report_usage("Extract Drills()")
  250. if toggle:
  251. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  252. if self.app.ui.splitter.sizes()[0] == 0:
  253. self.app.ui.splitter.setSizes([1, 1])
  254. else:
  255. try:
  256. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  257. # if tab is populated with the tool but it does not have the focus, focus on it
  258. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  259. # focus on Tool Tab
  260. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  261. else:
  262. self.app.ui.splitter.setSizes([0, 1])
  263. except AttributeError:
  264. pass
  265. else:
  266. if self.app.ui.splitter.sizes()[0] == 0:
  267. self.app.ui.splitter.setSizes([1, 1])
  268. FlatCAMTool.run(self)
  269. self.set_tool_ui()
  270. self.app.ui.notebook.setTabText(2, _("Extract Drills Tool"))
  271. def set_tool_ui(self):
  272. self.reset_fields()
  273. self.hole_size_radio.set_value(self.app.defaults["tools_edrills_hole_type"])
  274. self.dia_entry.set_value(float(self.app.defaults["tools_edrills_hole_fixed_dia"]))
  275. self.circular_ring_entry.set_value(float(self.app.defaults["tools_edrills_circular_ring"]))
  276. self.oblong_ring_entry.set_value(float(self.app.defaults["tools_edrills_oblong_ring"]))
  277. self.square_ring_entry.set_value(float(self.app.defaults["tools_edrills_square_ring"]))
  278. self.rectangular_ring_entry.set_value(float(self.app.defaults["tools_edrills_rectangular_ring"]))
  279. self.other_ring_entry.set_value(float(self.app.defaults["tools_edrills_others_ring"]))
  280. self.circular_cb.set_value(self.app.defaults["tools_edrills_circular"])
  281. self.oblong_cb.set_value(self.app.defaults["tools_edrills_oblong"])
  282. self.square_cb.set_value(self.app.defaults["tools_edrills_square"])
  283. self.rectangular_cb.set_value(self.app.defaults["tools_edrills_rectangular"])
  284. self.other_cb.set_value(self.app.defaults["tools_edrills_others"])
  285. def on_extract_drills_click(self):
  286. drill_dia = self.dia_entry.get_value()
  287. circ_r_val = self.circular_ring_entry.get_value()
  288. oblong_r_val = self.oblong_ring_entry.get_value()
  289. square_r_val = self.square_ring_entry.get_value()
  290. rect_r_val = self.rectangular_ring_entry.get_value()
  291. other_r_val = self.other_ring_entry.get_value()
  292. drills = list()
  293. tools = dict()
  294. selection_index = self.gerber_object_combo.currentIndex()
  295. model_index = self.app.collection.index(selection_index, 0, self.gerber_object_combo.rootModelIndex())
  296. try:
  297. fcobj = model_index.internalPointer().obj
  298. except Exception as e:
  299. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  300. return
  301. outname = fcobj.options['name'].rpartition('.')[0]
  302. mode = self.hole_size_radio.get_value()
  303. if mode == 'fixed':
  304. tools = {"1": {"C": drill_dia}}
  305. for apid, apid_value in fcobj.apertures.items():
  306. ap_type = apid_value['type']
  307. if ap_type == 'C':
  308. if self.circular_cb.get_value() is False:
  309. continue
  310. elif ap_type == 'O':
  311. if self.oblong_cb.get_value() is False:
  312. continue
  313. elif ap_type == 'R':
  314. width = float(apid_value['width'])
  315. height = float(apid_value['height'])
  316. # if the height == width (float numbers so the reason for the following)
  317. if round(width, self.decimals) == round(height, self.decimals):
  318. if self.square_cb.get_value() is False:
  319. continue
  320. else:
  321. if self.rectangular_cb.get_value() is False:
  322. continue
  323. else:
  324. if self.other_cb.get_value() is False:
  325. continue
  326. for geo_el in apid_value['geometry']:
  327. if 'follow' in geo_el and isinstance(geo_el['follow'], Point):
  328. drills.append({"point": geo_el['follow'], "tool": "1"})
  329. if 'solid_geometry' not in tools["1"]:
  330. tools["1"]['solid_geometry'] = list()
  331. else:
  332. tools["1"]['solid_geometry'].append(geo_el['follow'])
  333. if 'solid_geometry' not in tools["1"] or not tools["1"]['solid_geometry']:
  334. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No drills extracted. Try different parameters."))
  335. return
  336. else:
  337. drills_found = set()
  338. for apid, apid_value in fcobj.apertures.items():
  339. ap_type = apid_value['type']
  340. dia = None
  341. if ap_type == 'C':
  342. if self.circular_cb.get_value():
  343. dia = float(apid_value['size']) - (2 * circ_r_val)
  344. elif ap_type == 'O':
  345. width = float(apid_value['width'])
  346. height = float(apid_value['height'])
  347. if self.oblong_cb.get_value():
  348. if width > height:
  349. dia = float(apid_value['height']) - (2 * rect_r_val)
  350. else:
  351. dia = float(apid_value['width']) - (2 * rect_r_val)
  352. elif ap_type == 'R':
  353. width = float(apid_value['width'])
  354. height = float(apid_value['height'])
  355. # if the height == width (float numbers so the reason for the following)
  356. if abs(float('%.*f' % (self.decimals, width)) - float('%.*f' % (self.decimals, height))) < \
  357. (10 ** -self.decimals):
  358. if self.square_cb.get_value():
  359. dia = float(apid_value['height']) - (2 * square_r_val)
  360. else:
  361. if self.rectangular_cb.get_value():
  362. if width > height:
  363. dia = float(apid_value['height']) - (2 * rect_r_val)
  364. else:
  365. dia = float(apid_value['width']) - (2 * rect_r_val)
  366. else:
  367. if self.other_cb.get_value():
  368. try:
  369. dia = float(apid_value['size']) - (2 * other_r_val)
  370. except KeyError:
  371. if ap_type == 'AM':
  372. pol = apid_value['geometry'][0]['solid']
  373. x0, y0, x1, y1 = pol.bounds
  374. dx = x1 - x0
  375. dy = y1 - y0
  376. if dx <= dy:
  377. dia = dx - (2 * other_r_val)
  378. else:
  379. dia = dy - (2 * other_r_val)
  380. # if dia is None then none of the above applied so we skip the following
  381. if dia is None:
  382. continue
  383. tool_in_drills = False
  384. for tool, tool_val in tools.items():
  385. if abs(float('%.*f' % (self.decimals, tool_val["C"])) - float('%.*f' % (self.decimals, dia))) < \
  386. (10 ** -self.decimals):
  387. tool_in_drills = tool
  388. if tool_in_drills is False:
  389. if tools:
  390. new_tool = max([int(t) for t in tools]) + 1
  391. tool_in_drills = str(new_tool)
  392. else:
  393. tool_in_drills = "1"
  394. for geo_el in apid_value['geometry']:
  395. if 'follow' in geo_el and isinstance(geo_el['follow'], Point):
  396. if tool_in_drills not in tools:
  397. tools[tool_in_drills] = {"C": dia}
  398. drills.append({"point": geo_el['follow'], "tool": tool_in_drills})
  399. if 'solid_geometry' not in tools[tool_in_drills]:
  400. tools[tool_in_drills]['solid_geometry'] = list()
  401. else:
  402. tools[tool_in_drills]['solid_geometry'].append(geo_el['follow'])
  403. if tool_in_drills in tools:
  404. if 'solid_geometry' not in tools[tool_in_drills] or not tools[tool_in_drills]['solid_geometry']:
  405. drills_found.add(False)
  406. else:
  407. drills_found.add(True)
  408. if True not in drills_found:
  409. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No drills extracted. Try different parameters."))
  410. return
  411. def obj_init(obj_inst, app_inst):
  412. obj_inst.tools = tools
  413. obj_inst.drills = drills
  414. obj_inst.create_geometry()
  415. obj_inst.source_file = self.app.export_excellon(obj_name=outname, local_use=obj_inst, filename=None,
  416. use_thread=False)
  417. self.app.new_object("excellon", outname, obj_init)
  418. def on_hole_size_toggle(self, val):
  419. if val == "fixed":
  420. self.dia_entry.setDisabled(False)
  421. self.dia_label.setDisabled(False)
  422. self.ring_frame.setDisabled(True)
  423. else:
  424. self.dia_entry.setDisabled(True)
  425. self.dia_label.setDisabled(True)
  426. self.ring_frame.setDisabled(False)
  427. def reset_fields(self):
  428. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  429. self.gerber_object_combo.setCurrentIndex(0)