ToolEtchCompensation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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
  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 logging
  13. import gettext
  14. import AppTranslation as fcTranslate
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. log = logging.getLogger('base')
  20. class ToolEtchCompensation(AppTool):
  21. toolName = _("Etch Compensation Tool")
  22. def __init__(self, app):
  23. self.app = app
  24. self.decimals = self.app.decimals
  25. AppTool.__init__(self, app)
  26. self.tools_frame = QtWidgets.QFrame()
  27. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  28. self.layout.addWidget(self.tools_frame)
  29. self.tools_box = QtWidgets.QVBoxLayout()
  30. self.tools_box.setContentsMargins(0, 0, 0, 0)
  31. self.tools_frame.setLayout(self.tools_box)
  32. # Title
  33. title_label = QtWidgets.QLabel("%s" % self.toolName)
  34. title_label.setStyleSheet("""
  35. QLabel
  36. {
  37. font-size: 16px;
  38. font-weight: bold;
  39. }
  40. """)
  41. self.tools_box.addWidget(title_label)
  42. # Grid Layout
  43. grid0 = QtWidgets.QGridLayout()
  44. grid0.setColumnStretch(0, 0)
  45. grid0.setColumnStretch(1, 1)
  46. self.tools_box.addLayout(grid0)
  47. grid0.addWidget(QtWidgets.QLabel(''), 0, 0, 1, 2)
  48. # Target Gerber Object
  49. self.gerber_combo = FCComboBox()
  50. self.gerber_combo.setModel(self.app.collection)
  51. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  52. self.gerber_combo.is_last = True
  53. self.gerber_combo.obj_type = "Gerber"
  54. self.gerber_label = QtWidgets.QLabel('<b>%s:</b>' % _("GERBER"))
  55. self.gerber_label.setToolTip(
  56. _("Gerber object that will be inverted.")
  57. )
  58. grid0.addWidget(self.gerber_label, 1, 0, 1, 2)
  59. grid0.addWidget(self.gerber_combo, 2, 0, 1, 2)
  60. grid0.addWidget(QtWidgets.QLabel(""), 3, 0, 1, 2)
  61. self.util_label = QtWidgets.QLabel("<b>%s:</b>" % _("Utilities"))
  62. self.util_label.setToolTip('%s.' % _("Conversion utilities"))
  63. grid0.addWidget(self.util_label, 4, 0, 1, 2)
  64. # Oz to um conversion
  65. self.oz_um_label = QtWidgets.QLabel('%s:' % _('Oz to Microns'))
  66. self.oz_um_label.setToolTip(
  67. _("Will convert from oz thickness to microns [um].\n"
  68. "Can use formulas with operators: /, *, +, -, %, .\n"
  69. "The real numbers use the dot decimals separator.")
  70. )
  71. grid0.addWidget(self.oz_um_label, 5, 0, 1, 2)
  72. hlay_1 = QtWidgets.QHBoxLayout()
  73. self.oz_entry = NumericalEvalEntry()
  74. self.oz_entry.setPlaceholderText(_("Oz value"))
  75. self.oz_to_um_entry = FCEntry()
  76. self.oz_to_um_entry.setPlaceholderText(_("Microns value"))
  77. self.oz_to_um_entry.setReadOnly(True)
  78. hlay_1.addWidget(self.oz_entry)
  79. hlay_1.addWidget(self.oz_to_um_entry)
  80. grid0.addLayout(hlay_1, 6, 0, 1, 2)
  81. # Mils to um conversion
  82. self.mils_um_label = QtWidgets.QLabel('%s:' % _('Mils to Microns'))
  83. self.mils_um_label.setToolTip(
  84. _("Will convert from mils to microns [um].\n"
  85. "Can use formulas with operators: /, *, +, -, %, .\n"
  86. "The real numbers use the dot decimals separator.")
  87. )
  88. grid0.addWidget(self.mils_um_label, 7, 0, 1, 2)
  89. hlay_2 = QtWidgets.QHBoxLayout()
  90. self.mils_entry = NumericalEvalEntry()
  91. self.mils_entry.setPlaceholderText(_("Mils value"))
  92. self.mils_to_um_entry = FCEntry()
  93. self.mils_to_um_entry.setPlaceholderText(_("Microns value"))
  94. self.mils_to_um_entry.setReadOnly(True)
  95. hlay_2.addWidget(self.mils_entry)
  96. hlay_2.addWidget(self.mils_to_um_entry)
  97. grid0.addLayout(hlay_2, 8, 0, 1, 2)
  98. grid0.addWidget(QtWidgets.QLabel(""), 9, 0, 1, 2)
  99. self.param_label = QtWidgets.QLabel("<b>%s:</b>" % _("Parameters"))
  100. self.param_label.setToolTip('%s.' % _("Parameters for this tool"))
  101. grid0.addWidget(self.param_label, 10, 0, 1, 2)
  102. # Thickness
  103. self.thick_label = QtWidgets.QLabel('%s:' % _('Copper Thickness'))
  104. self.thick_label.setToolTip(
  105. _("The thickness of the copper foil.\n"
  106. "In microns [um].")
  107. )
  108. self.thick_entry = FCDoubleSpinner(callback=self.confirmation_message)
  109. self.thick_entry.set_precision(self.decimals)
  110. self.thick_entry.set_range(0.0000, 9999.9999)
  111. self.thick_entry.setObjectName(_("Thickness"))
  112. grid0.addWidget(self.thick_label, 12, 0)
  113. grid0.addWidget(self.thick_entry, 12, 1)
  114. self.ratio_label = QtWidgets.QLabel('%s:' % _("Ratio"))
  115. self.ratio_label.setToolTip(
  116. _("The ratio of lateral etch versus depth etch.\n"
  117. "Can be:\n"
  118. "- custom -> the user will enter a custom value\n"
  119. "- preselection -> value which depends on a selection of etchants")
  120. )
  121. self.ratio_radio = RadioSet([
  122. {'label': _('Custom'), 'value': 'c'},
  123. {'label': _('PreSelection'), 'value': 'p'}
  124. ], orientation='vertical', stretch=False)
  125. grid0.addWidget(self.ratio_label, 14, 0, 1, 2)
  126. grid0.addWidget(self.ratio_radio, 16, 0, 1, 2)
  127. # Etchants
  128. self.etchants_label = QtWidgets.QLabel('%s:' % _('Etchants'))
  129. self.etchants_label.setToolTip(
  130. _("A list of etchants.")
  131. )
  132. self.etchants_combo = FCComboBox(callback=self.confirmation_message)
  133. self.etchants_combo.setObjectName(_("Etchants"))
  134. self.etchants_combo.addItems(["CuCl2", "Fe3Cl"])
  135. grid0.addWidget(self.etchants_label, 18, 0)
  136. grid0.addWidget(self.etchants_combo, 18, 1)
  137. # Etch Factor
  138. self.factor_label = QtWidgets.QLabel('%s:' % _('Etch factor'))
  139. self.factor_label.setToolTip(
  140. _("The ratio between depth etch and lateral etch .\n"
  141. "Accepts real numbers and formulas using the operators: /,*,+,-,%")
  142. )
  143. self.factor_entry = NumericalEvalEntry()
  144. self.factor_entry.setPlaceholderText(_("Real number or formula"))
  145. self.factor_entry.setObjectName(_("Etch_factor"))
  146. # Hide the Etchants and Etch factor
  147. self.etchants_label.hide()
  148. self.etchants_combo.hide()
  149. self.factor_label.hide()
  150. self.factor_entry.hide()
  151. grid0.addWidget(self.factor_label, 20, 0)
  152. grid0.addWidget(self.factor_entry, 20, 1)
  153. separator_line = QtWidgets.QFrame()
  154. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  155. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  156. grid0.addWidget(separator_line, 22, 0, 1, 2)
  157. self.compensate_btn = FCButton(_('Compensate'))
  158. self.compensate_btn.setToolTip(
  159. _("Will increase the copper features thickness to compensate the lateral etch.")
  160. )
  161. self.compensate_btn.setStyleSheet("""
  162. QPushButton
  163. {
  164. font-weight: bold;
  165. }
  166. """)
  167. grid0.addWidget(self.compensate_btn, 24, 0, 1, 2)
  168. self.tools_box.addStretch()
  169. # ## Reset Tool
  170. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  171. self.reset_button.setToolTip(
  172. _("Will reset the tool parameters.")
  173. )
  174. self.reset_button.setStyleSheet("""
  175. QPushButton
  176. {
  177. font-weight: bold;
  178. }
  179. """)
  180. self.tools_box.addWidget(self.reset_button)
  181. self.compensate_btn.clicked.connect(self.on_compensate)
  182. self.reset_button.clicked.connect(self.set_tool_ui)
  183. self.ratio_radio.activated_custom.connect(self.on_ratio_change)
  184. self.oz_entry.textChanged.connect(self.on_oz_conversion)
  185. self.mils_entry.textChanged.connect(self.on_mils_conversion)
  186. def install(self, icon=None, separator=None, **kwargs):
  187. AppTool.install(self, icon, separator, shortcut='', **kwargs)
  188. def run(self, toggle=True):
  189. self.app.defaults.report_usage("ToolEtchCompensation()")
  190. log.debug("ToolEtchCompensation() is running ...")
  191. if toggle:
  192. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  193. if self.app.ui.splitter.sizes()[0] == 0:
  194. self.app.ui.splitter.setSizes([1, 1])
  195. else:
  196. try:
  197. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  198. # if tab is populated with the tool but it does not have the focus, focus on it
  199. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  200. # focus on Tool Tab
  201. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  202. else:
  203. self.app.ui.splitter.setSizes([0, 1])
  204. except AttributeError:
  205. pass
  206. else:
  207. if self.app.ui.splitter.sizes()[0] == 0:
  208. self.app.ui.splitter.setSizes([1, 1])
  209. AppTool.run(self)
  210. self.set_tool_ui()
  211. self.app.ui.notebook.setTabText(2, _("Etch Compensation Tool"))
  212. def set_tool_ui(self):
  213. self.thick_entry.set_value(18.0)
  214. self.ratio_radio.set_value('c')
  215. def on_ratio_change(self, val):
  216. """
  217. Called on activated_custom signal of the RadioSet GUI element self.radio_ratio
  218. :param val: 'c' or 'p': 'c' means custom factor and 'p' means preselected etchants
  219. :type val: str
  220. :return: None
  221. :rtype:
  222. """
  223. if val == 'c':
  224. self.etchants_label.hide()
  225. self.etchants_combo.hide()
  226. self.factor_label.show()
  227. self.factor_entry.show()
  228. else:
  229. self.etchants_label.show()
  230. self.etchants_combo.show()
  231. self.factor_label.hide()
  232. self.factor_entry.hide()
  233. def on_oz_conversion(self, txt):
  234. try:
  235. val = eval(txt)
  236. # oz thickness to mils by multiplying with 1.37
  237. # mils to microns by multiplying with 25.4
  238. val *= 34.798
  239. except Exception:
  240. return
  241. self.oz_to_um_entry.set_value(val, self.decimals)
  242. def on_mils_conversion(self, txt):
  243. try:
  244. val = eval(txt)
  245. val *= 25.4
  246. except Exception:
  247. return
  248. self.mils_to_um_entry.set_value(val, self.decimals)
  249. def on_compensate(self):
  250. ratio_type = self.ratio_radio.get_value()
  251. thickness = self.thick_entry.get_value() / 1000 # in microns
  252. grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  253. obj_name = self.gerber_combo.currentText()
  254. outname = obj_name + "_comp"
  255. # Get source object.
  256. try:
  257. grb_obj = self.app.collection.get_by_name(obj_name)
  258. except Exception as e:
  259. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  260. return "Could not retrieve object: %s with error: %s" % (obj_name, str(e))
  261. if grb_obj is None:
  262. if obj_name == '':
  263. obj_name = 'None'
  264. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  265. return
  266. if ratio_type == 'c':
  267. etch_factor = 1 / self.factor_entry.get_value()
  268. else:
  269. etchant = self.etchants_combo.get_value()
  270. if etchant == "CuCl2":
  271. etch_factor = 0.33
  272. else:
  273. etch_factor = 0.25
  274. offset = thickness / etch_factor
  275. try:
  276. __ = iter(grb_obj.solid_geometry)
  277. except TypeError:
  278. grb_obj.solid_geometry = list(grb_obj.solid_geometry)
  279. new_solid_geometry = []
  280. for poly in grb_obj.solid_geometry:
  281. new_solid_geometry.append(poly.buffer(offset, int(grb_circle_steps)))
  282. new_solid_geometry = unary_union(new_solid_geometry)
  283. new_options = {}
  284. for opt in grb_obj.options:
  285. new_options[opt] = deepcopy(grb_obj.options[opt])
  286. new_apertures = deepcopy(grb_obj.apertures)
  287. for ap in new_apertures:
  288. for k in ap:
  289. if k == 'geometry':
  290. for geo_el in new_apertures[ap]['geometry']:
  291. if 'solid' in geo_el:
  292. geo_el['solid'] = geo_el['solid'].buffer(offset, int(grb_circle_steps))
  293. def init_func(new_obj, app_obj):
  294. """
  295. Init a new object in FlatCAM Object collection
  296. :param new_obj: New object
  297. :type new_obj: ObjectCollection
  298. :param app_obj: App
  299. :type app_obj: App_Main.App
  300. :return: None
  301. :rtype:
  302. """
  303. new_obj.options.update(new_options)
  304. new_obj.options['name'] = outname
  305. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  306. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  307. new_obj.apertures = deepcopy(new_apertures)
  308. new_obj.solid_geometry = deepcopy(new_solid_geometry)
  309. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  310. local_use=new_obj, use_thread=False)
  311. self.app.app_obj.new_object('gerber', outname, init_func)
  312. def reset_fields(self):
  313. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  314. @staticmethod
  315. def poly2rings(poly):
  316. return [poly.exterior] + [interior for interior in poly.interiors]
  317. # end of file