ToolEtchCompensation.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 2/14/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCButton, FCDoubleSpinner, RadioSet, FCComboBox, NumericalEvalEntry, FCEntry
  10. from shapely.ops import unary_union
  11. from copy import deepcopy
  12. import math
  13. import logging
  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 ToolEtchCompensation(AppTool):
  22. def __init__(self, app):
  23. self.app = app
  24. self.decimals = self.app.decimals
  25. AppTool.__init__(self, app)
  26. # #############################################################################
  27. # ######################### Tool GUI ##########################################
  28. # #############################################################################
  29. self.ui = EtchUI(layout=self.layout, app=self.app)
  30. self.toolName = self.ui.toolName
  31. self.ui.compensate_btn.clicked.connect(self.on_compensate)
  32. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  33. self.ui.ratio_radio.activated_custom.connect(self.on_ratio_change)
  34. self.ui.oz_entry.textChanged.connect(self.on_oz_conversion)
  35. self.ui.mils_entry.textChanged.connect(self.on_mils_conversion)
  36. def install(self, icon=None, separator=None, **kwargs):
  37. AppTool.install(self, icon, separator, shortcut='', **kwargs)
  38. def run(self, toggle=True):
  39. self.app.defaults.report_usage("ToolEtchCompensation()")
  40. log.debug("ToolEtchCompensation() is running ...")
  41. if toggle:
  42. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  43. if self.app.ui.splitter.sizes()[0] == 0:
  44. self.app.ui.splitter.setSizes([1, 1])
  45. else:
  46. try:
  47. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  48. # if tab is populated with the tool but it does not have the focus, focus on it
  49. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  50. # focus on Tool Tab
  51. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  52. else:
  53. self.app.ui.splitter.setSizes([0, 1])
  54. except AttributeError:
  55. pass
  56. else:
  57. if self.app.ui.splitter.sizes()[0] == 0:
  58. self.app.ui.splitter.setSizes([1, 1])
  59. AppTool.run(self)
  60. self.set_tool_ui()
  61. self.app.ui.notebook.setTabText(2, _("Etch Compensation Tool"))
  62. def set_tool_ui(self):
  63. self.ui.thick_entry.set_value(18.0)
  64. self.ui.ratio_radio.set_value('factor')
  65. def on_ratio_change(self, val):
  66. """
  67. Called on activated_custom signal of the RadioSet GUI element self.radio_ratio
  68. :param val: 'c' or 'p': 'c' means custom factor and 'p' means preselected etchants
  69. :type val: str
  70. :return: None
  71. :rtype:
  72. """
  73. if val == 'factor':
  74. self.ui.etchants_label.hide()
  75. self.ui.etchants_combo.hide()
  76. self.ui.factor_label.show()
  77. self.ui.factor_entry.show()
  78. self.ui.offset_label.hide()
  79. self.ui.offset_entry.hide()
  80. elif val == 'etch_list':
  81. self.ui.etchants_label.show()
  82. self.ui.etchants_combo.show()
  83. self.ui.factor_label.hide()
  84. self.ui.factor_entry.hide()
  85. self.ui.offset_label.hide()
  86. self.ui.offset_entry.hide()
  87. else:
  88. self.ui.etchants_label.hide()
  89. self.ui.etchants_combo.hide()
  90. self.ui.factor_label.hide()
  91. self.ui.factor_entry.hide()
  92. self.ui.offset_label.show()
  93. self.ui.offset_entry.show()
  94. def on_oz_conversion(self, txt):
  95. try:
  96. val = eval(txt)
  97. # oz thickness to mils by multiplying with 1.37
  98. # mils to microns by multiplying with 25.4
  99. val *= 34.798
  100. except Exception:
  101. self.ui.oz_to_um_entry.set_value('')
  102. return
  103. self.ui.oz_to_um_entry.set_value(val, self.decimals)
  104. def on_mils_conversion(self, txt):
  105. try:
  106. val = eval(txt)
  107. val *= 25.4
  108. except Exception:
  109. self.ui.mils_to_um_entry.set_value('')
  110. return
  111. self.ui.mils_to_um_entry.set_value(val, self.decimals)
  112. def on_compensate(self):
  113. log.debug("ToolEtchCompensation.on_compensate()")
  114. ratio_type = self.ui.ratio_radio.get_value()
  115. thickness = self.ui.thick_entry.get_value() / 1000 # in microns
  116. grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  117. obj_name = self.ui.gerber_combo.currentText()
  118. outname = obj_name + "_comp"
  119. # Get source object.
  120. try:
  121. grb_obj = self.app.collection.get_by_name(obj_name)
  122. except Exception as e:
  123. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  124. return "Could not retrieve object: %s with error: %s" % (obj_name, str(e))
  125. if grb_obj is None:
  126. if obj_name == '':
  127. obj_name = 'None'
  128. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  129. return
  130. if ratio_type == 'factor':
  131. etch_factor = 1 / self.ui.factor_entry.get_value()
  132. offset = thickness / etch_factor
  133. elif ratio_type == 'etch_list':
  134. etchant = self.ui.etchants_combo.get_value()
  135. if etchant == "CuCl2":
  136. etch_factor = 0.33
  137. else:
  138. etch_factor = 0.25
  139. offset = thickness / etch_factor
  140. else:
  141. offset = self.ui.offset_entry.get_value() / 1000 # in microns
  142. try:
  143. __ = iter(grb_obj.solid_geometry)
  144. except TypeError:
  145. grb_obj.solid_geometry = list(grb_obj.solid_geometry)
  146. new_solid_geometry = []
  147. for poly in grb_obj.solid_geometry:
  148. new_solid_geometry.append(poly.buffer(offset, int(grb_circle_steps)))
  149. new_solid_geometry = unary_union(new_solid_geometry)
  150. new_options = {}
  151. for opt in grb_obj.options:
  152. new_options[opt] = deepcopy(grb_obj.options[opt])
  153. new_apertures = deepcopy(grb_obj.apertures)
  154. # update the apertures attributes (keys in the apertures dict)
  155. for ap in new_apertures:
  156. ap_type = new_apertures[ap]['type']
  157. for k in new_apertures[ap]:
  158. if ap_type == 'R' or ap_type == 'O':
  159. if k == 'width' or k == 'height':
  160. new_apertures[ap][k] += offset
  161. else:
  162. if k == 'size' or k == 'width' or k == 'height':
  163. new_apertures[ap][k] += offset
  164. if k == 'geometry':
  165. for geo_el in new_apertures[ap][k]:
  166. if 'solid' in geo_el:
  167. geo_el['solid'] = geo_el['solid'].buffer(offset, int(grb_circle_steps))
  168. # in case of 'R' or 'O' aperture type we need to update the aperture 'size' after
  169. # the 'width' and 'height' keys were updated
  170. for ap in new_apertures:
  171. ap_type = new_apertures[ap]['type']
  172. for k in new_apertures[ap]:
  173. if ap_type == 'R' or ap_type == 'O':
  174. if k == 'size':
  175. new_apertures[ap][k] = math.sqrt(
  176. new_apertures[ap]['width'] ** 2 + new_apertures[ap]['height'] ** 2)
  177. def init_func(new_obj, app_obj):
  178. """
  179. Init a new object in FlatCAM Object collection
  180. :param new_obj: New object
  181. :type new_obj: ObjectCollection
  182. :param app_obj: App
  183. :type app_obj: app_Main.App
  184. :return: None
  185. :rtype:
  186. """
  187. new_obj.options.update(new_options)
  188. new_obj.options['name'] = outname
  189. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  190. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  191. new_obj.apertures = deepcopy(new_apertures)
  192. new_obj.solid_geometry = deepcopy(new_solid_geometry)
  193. new_obj.source_file = app_obj.f_handlers.export_gerber(obj_name=outname, filename=None, local_use=new_obj,
  194. use_thread=False)
  195. self.app.app_obj.new_object('gerber', outname, init_func)
  196. def reset_fields(self):
  197. self.ui.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  198. @staticmethod
  199. def poly2rings(poly):
  200. return [poly.exterior] + [interior for interior in poly.interiors]
  201. class EtchUI:
  202. toolName = _("Etch Compensation Tool")
  203. def __init__(self, layout, app):
  204. self.app = app
  205. self.decimals = self.app.decimals
  206. self.layout = layout
  207. self.tools_frame = QtWidgets.QFrame()
  208. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  209. self.layout.addWidget(self.tools_frame)
  210. self.tools_box = QtWidgets.QVBoxLayout()
  211. self.tools_box.setContentsMargins(0, 0, 0, 0)
  212. self.tools_frame.setLayout(self.tools_box)
  213. # Title
  214. title_label = QtWidgets.QLabel("%s" % self.toolName)
  215. title_label.setStyleSheet("""
  216. QLabel
  217. {
  218. font-size: 16px;
  219. font-weight: bold;
  220. }
  221. """)
  222. self.tools_box.addWidget(title_label)
  223. # Grid Layout
  224. grid0 = QtWidgets.QGridLayout()
  225. grid0.setColumnStretch(0, 0)
  226. grid0.setColumnStretch(1, 1)
  227. self.tools_box.addLayout(grid0)
  228. grid0.addWidget(QtWidgets.QLabel(''), 0, 0, 1, 2)
  229. # Target Gerber Object
  230. self.gerber_combo = FCComboBox()
  231. self.gerber_combo.setModel(self.app.collection)
  232. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  233. self.gerber_combo.is_last = True
  234. self.gerber_combo.obj_type = "Gerber"
  235. self.gerber_label = QtWidgets.QLabel('<b>%s:</b>' % _("GERBER"))
  236. self.gerber_label.setToolTip(
  237. _("Gerber object that will be inverted.")
  238. )
  239. grid0.addWidget(self.gerber_label, 1, 0, 1, 2)
  240. grid0.addWidget(self.gerber_combo, 2, 0, 1, 2)
  241. separator_line = QtWidgets.QFrame()
  242. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  243. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  244. grid0.addWidget(separator_line, 3, 0, 1, 2)
  245. self.util_label = QtWidgets.QLabel("<b>%s:</b>" % _("Utilities"))
  246. self.util_label.setToolTip('%s.' % _("Conversion utilities"))
  247. grid0.addWidget(self.util_label, 4, 0, 1, 2)
  248. # Oz to um conversion
  249. self.oz_um_label = QtWidgets.QLabel('%s:' % _('Oz to Microns'))
  250. self.oz_um_label.setToolTip(
  251. _("Will convert from oz thickness to microns [um].\n"
  252. "Can use formulas with operators: /, *, +, -, %, .\n"
  253. "The real numbers use the dot decimals separator.")
  254. )
  255. grid0.addWidget(self.oz_um_label, 5, 0, 1, 2)
  256. hlay_1 = QtWidgets.QHBoxLayout()
  257. self.oz_entry = NumericalEvalEntry(border_color='#0069A9')
  258. self.oz_entry.setPlaceholderText(_("Oz value"))
  259. self.oz_to_um_entry = FCEntry()
  260. self.oz_to_um_entry.setPlaceholderText(_("Microns value"))
  261. self.oz_to_um_entry.setReadOnly(True)
  262. hlay_1.addWidget(self.oz_entry)
  263. hlay_1.addWidget(self.oz_to_um_entry)
  264. grid0.addLayout(hlay_1, 6, 0, 1, 2)
  265. # Mils to um conversion
  266. self.mils_um_label = QtWidgets.QLabel('%s:' % _('Mils to Microns'))
  267. self.mils_um_label.setToolTip(
  268. _("Will convert from mils to microns [um].\n"
  269. "Can use formulas with operators: /, *, +, -, %, .\n"
  270. "The real numbers use the dot decimals separator.")
  271. )
  272. grid0.addWidget(self.mils_um_label, 7, 0, 1, 2)
  273. hlay_2 = QtWidgets.QHBoxLayout()
  274. self.mils_entry = NumericalEvalEntry(border_color='#0069A9')
  275. self.mils_entry.setPlaceholderText(_("Mils value"))
  276. self.mils_to_um_entry = FCEntry()
  277. self.mils_to_um_entry.setPlaceholderText(_("Microns value"))
  278. self.mils_to_um_entry.setReadOnly(True)
  279. hlay_2.addWidget(self.mils_entry)
  280. hlay_2.addWidget(self.mils_to_um_entry)
  281. grid0.addLayout(hlay_2, 8, 0, 1, 2)
  282. separator_line = QtWidgets.QFrame()
  283. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  284. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  285. grid0.addWidget(separator_line, 9, 0, 1, 2)
  286. self.param_label = QtWidgets.QLabel("<b>%s:</b>" % _("Parameters"))
  287. self.param_label.setToolTip('%s.' % _("Parameters for this tool"))
  288. grid0.addWidget(self.param_label, 10, 0, 1, 2)
  289. # Thickness
  290. self.thick_label = QtWidgets.QLabel('%s:' % _('Copper Thickness'))
  291. self.thick_label.setToolTip(
  292. _("The thickness of the copper foil.\n"
  293. "In microns [um].")
  294. )
  295. self.thick_entry = FCDoubleSpinner(callback=self.confirmation_message)
  296. self.thick_entry.set_precision(self.decimals)
  297. self.thick_entry.set_range(0.0000, 9999.9999)
  298. self.thick_entry.setObjectName(_("Thickness"))
  299. grid0.addWidget(self.thick_label, 12, 0)
  300. grid0.addWidget(self.thick_entry, 12, 1)
  301. self.ratio_label = QtWidgets.QLabel('%s:' % _("Ratio"))
  302. self.ratio_label.setToolTip(
  303. _("The ratio of lateral etch versus depth etch.\n"
  304. "Can be:\n"
  305. "- custom -> the user will enter a custom value\n"
  306. "- preselection -> value which depends on a selection of etchants")
  307. )
  308. self.ratio_radio = RadioSet([
  309. {'label': _('Etch Factor'), 'value': 'factor'},
  310. {'label': _('Etchants list'), 'value': 'etch_list'},
  311. {'label': _('Manual offset'), 'value': 'manual'}
  312. ], orientation='vertical', stretch=False)
  313. grid0.addWidget(self.ratio_label, 14, 0, 1, 2)
  314. grid0.addWidget(self.ratio_radio, 16, 0, 1, 2)
  315. # Etchants
  316. self.etchants_label = QtWidgets.QLabel('%s:' % _('Etchants'))
  317. self.etchants_label.setToolTip(
  318. _("A list of etchants.")
  319. )
  320. self.etchants_combo = FCComboBox(callback=self.confirmation_message)
  321. self.etchants_combo.setObjectName(_("Etchants"))
  322. self.etchants_combo.addItems(["CuCl2", "Fe3Cl", _("Alkaline baths")])
  323. grid0.addWidget(self.etchants_label, 18, 0)
  324. grid0.addWidget(self.etchants_combo, 18, 1)
  325. # Etch Factor
  326. self.factor_label = QtWidgets.QLabel('%s:' % _('Etch factor'))
  327. self.factor_label.setToolTip(
  328. _("The ratio between depth etch and lateral etch .\n"
  329. "Accepts real numbers and formulas using the operators: /,*,+,-,%")
  330. )
  331. self.factor_entry = NumericalEvalEntry(border_color='#0069A9')
  332. self.factor_entry.setPlaceholderText(_("Real number or formula"))
  333. self.factor_entry.setObjectName(_("Etch_factor"))
  334. grid0.addWidget(self.factor_label, 19, 0)
  335. grid0.addWidget(self.factor_entry, 19, 1)
  336. # Manual Offset
  337. self.offset_label = QtWidgets.QLabel('%s:' % _('Offset'))
  338. self.offset_label.setToolTip(
  339. _("Value with which to increase or decrease (buffer)\n"
  340. "the copper features. In microns [um].")
  341. )
  342. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  343. self.offset_entry.set_precision(self.decimals)
  344. self.offset_entry.set_range(-9999.9999, 9999.9999)
  345. self.offset_entry.setObjectName(_("Offset"))
  346. grid0.addWidget(self.offset_label, 20, 0)
  347. grid0.addWidget(self.offset_entry, 20, 1)
  348. # Hide the Etchants and Etch factor
  349. self.etchants_label.hide()
  350. self.etchants_combo.hide()
  351. self.factor_label.hide()
  352. self.factor_entry.hide()
  353. self.offset_label.hide()
  354. self.offset_entry.hide()
  355. separator_line = QtWidgets.QFrame()
  356. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  357. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  358. grid0.addWidget(separator_line, 22, 0, 1, 2)
  359. self.compensate_btn = FCButton(_('Compensate'))
  360. self.compensate_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/etch_32.png'))
  361. self.compensate_btn.setToolTip(
  362. _("Will increase the copper features thickness to compensate the lateral etch.")
  363. )
  364. self.compensate_btn.setStyleSheet("""
  365. QPushButton
  366. {
  367. font-weight: bold;
  368. }
  369. """)
  370. grid0.addWidget(self.compensate_btn, 24, 0, 1, 2)
  371. self.tools_box.addStretch()
  372. # ## Reset Tool
  373. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  374. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  375. self.reset_button.setToolTip(
  376. _("Will reset the tool parameters.")
  377. )
  378. self.reset_button.setStyleSheet("""
  379. QPushButton
  380. {
  381. font-weight: bold;
  382. }
  383. """)
  384. self.tools_box.addWidget(self.reset_button)
  385. # #################################### FINSIHED GUI ###########################
  386. # #############################################################################
  387. def confirmation_message(self, accepted, minval, maxval):
  388. if accepted is False:
  389. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  390. self.decimals,
  391. minval,
  392. self.decimals,
  393. maxval), False)
  394. else:
  395. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  396. def confirmation_message_int(self, accepted, minval, maxval):
  397. if accepted is False:
  398. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  399. (_("Edited value is out of range"), minval, maxval), False)
  400. else:
  401. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  402. # end of file