ToolEtchCompensation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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
  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.param_label = QtWidgets.QLabel("<b>%s:</b>" % _("Parameters"))
  62. self.param_label.setToolTip('%s.' % _("Parameters for this tool"))
  63. grid0.addWidget(self.param_label, 4, 0, 1, 2)
  64. # Thickness
  65. self.thick_label = QtWidgets.QLabel('%s:' % _('Copper Thickness'))
  66. self.thick_label.setToolTip(
  67. _("The thickness of the copper foil.\n"
  68. "In microns [um].")
  69. )
  70. self.thick_entry = FCDoubleSpinner(callback=self.confirmation_message)
  71. self.thick_entry.set_precision(self.decimals)
  72. self.thick_entry.set_range(0.0000, 9999.9999)
  73. self.thick_entry.setObjectName(_("Thickness"))
  74. grid0.addWidget(self.thick_label, 5, 0)
  75. grid0.addWidget(self.thick_entry, 5, 1)
  76. self.ratio_label = QtWidgets.QLabel('%s:' % _("Ratio"))
  77. self.ratio_label.setToolTip(
  78. _("The ratio of lateral etch versus depth etch.\n"
  79. "Can be:\n"
  80. "- custom -> the user will enter a custom value\n"
  81. "- preselection -> value which depends on a selection of etchants")
  82. )
  83. self.ratio_radio = RadioSet([
  84. {'label': _('Custom'), 'value': 'c'},
  85. {'label': _('PreSelection'), 'value': 'p'}
  86. ], orientation='vertical', stretch=False)
  87. grid0.addWidget(self.ratio_label, 7, 0, 1, 2)
  88. grid0.addWidget(self.ratio_radio, 8, 0, 1, 2)
  89. # Etchants
  90. self.etchants_label = QtWidgets.QLabel('%s:' % _('Etchants'))
  91. self.etchants_label.setToolTip(
  92. _("A list of etchants.")
  93. )
  94. self.etchants_combo = FCComboBox(callback=self.confirmation_message)
  95. self.etchants_combo.setObjectName(_("Etchants"))
  96. self.etchants_combo.addItems(["CuCl2", "FeCl3"])
  97. grid0.addWidget(self.etchants_label, 9, 0)
  98. grid0.addWidget(self.etchants_combo, 9, 1)
  99. # Etch Factor
  100. self.factor_label = QtWidgets.QLabel('%s:' % _('Etch factor'))
  101. self.factor_label.setToolTip(
  102. _("The ratio between depth etch and lateral etch .\n"
  103. "Accepts real numbers and formulas using the operators: /,*,+,-,%")
  104. )
  105. self.factor_entry = NumericalEvalEntry()
  106. self.factor_entry.setPlaceholderText(_("Real number or formula"))
  107. self.factor_entry.setObjectName(_("Etch_factor"))
  108. # Hide the Etchants and Etch factor
  109. self.etchants_label.hide()
  110. self.etchants_combo.hide()
  111. self.factor_label.hide()
  112. self.factor_entry.hide()
  113. grid0.addWidget(self.factor_label, 10, 0)
  114. grid0.addWidget(self.factor_entry, 10, 1)
  115. separator_line = QtWidgets.QFrame()
  116. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  117. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  118. grid0.addWidget(separator_line, 13, 0, 1, 2)
  119. self.compensate_btn = FCButton(_('Compensate'))
  120. self.compensate_btn.setToolTip(
  121. _("Will increase the copper features thickness to compensate the lateral etch.")
  122. )
  123. self.compensate_btn.setStyleSheet("""
  124. QPushButton
  125. {
  126. font-weight: bold;
  127. }
  128. """)
  129. grid0.addWidget(self.compensate_btn, 14, 0, 1, 2)
  130. self.tools_box.addStretch()
  131. # ## Reset Tool
  132. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  133. self.reset_button.setToolTip(
  134. _("Will reset the tool parameters.")
  135. )
  136. self.reset_button.setStyleSheet("""
  137. QPushButton
  138. {
  139. font-weight: bold;
  140. }
  141. """)
  142. self.tools_box.addWidget(self.reset_button)
  143. self.compensate_btn.clicked.connect(self.on_compensate)
  144. self.reset_button.clicked.connect(self.set_tool_ui)
  145. self.ratio_radio.activated_custom.connect(self.on_ratio_change)
  146. def install(self, icon=None, separator=None, **kwargs):
  147. AppTool.install(self, icon, separator, shortcut='', **kwargs)
  148. def run(self, toggle=True):
  149. self.app.defaults.report_usage("ToolEtchCompensation()")
  150. log.debug("ToolEtchCompensation() is running ...")
  151. if toggle:
  152. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  153. if self.app.ui.splitter.sizes()[0] == 0:
  154. self.app.ui.splitter.setSizes([1, 1])
  155. else:
  156. try:
  157. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  158. # if tab is populated with the tool but it does not have the focus, focus on it
  159. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  160. # focus on Tool Tab
  161. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  162. else:
  163. self.app.ui.splitter.setSizes([0, 1])
  164. except AttributeError:
  165. pass
  166. else:
  167. if self.app.ui.splitter.sizes()[0] == 0:
  168. self.app.ui.splitter.setSizes([1, 1])
  169. AppTool.run(self)
  170. self.set_tool_ui()
  171. self.app.ui.notebook.setTabText(2, _("Etch Compensation Tool"))
  172. def set_tool_ui(self):
  173. self.thick_entry.set_value(18.0)
  174. self.ratio_radio.set_value('c')
  175. def on_ratio_change(self, val):
  176. """
  177. Called on activated_custom signal of the RadioSet GUI element self.radio_ratio
  178. :param val: 'c' or 'p': 'c' means custom factor and 'p' means preselected etchants
  179. :type val: str
  180. :return: None
  181. :rtype:
  182. """
  183. if val == 'c':
  184. self.etchants_label.hide()
  185. self.etchants_combo.hide()
  186. self.factor_label.show()
  187. self.factor_entry.show()
  188. else:
  189. self.etchants_label.show()
  190. self.etchants_combo.show()
  191. self.factor_label.hide()
  192. self.factor_entry.hide()
  193. def on_compensate(self):
  194. ratio_type = self.ratio_radio.get_value()
  195. thickness = self.thick_entry.get_value() / 1000 # in microns
  196. grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  197. obj_name = self.gerber_combo.currentText()
  198. outname = obj_name + "_comp"
  199. # Get source object.
  200. try:
  201. grb_obj = self.app.collection.get_by_name(obj_name)
  202. except Exception as e:
  203. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  204. return "Could not retrieve object: %s with error: %s" % (obj_name, str(e))
  205. if grb_obj is None:
  206. if obj_name == '':
  207. obj_name = 'None'
  208. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  209. return
  210. if ratio_type == 'c':
  211. etch_factor = 1 / self.factor_entry.get_value()
  212. else:
  213. etchant = self.etchants_combo.get_value()
  214. if etchant == "CuCl2":
  215. etch_factor = 0.33
  216. else:
  217. etch_factor = 0.25
  218. offset = thickness / etch_factor
  219. try:
  220. __ = iter(grb_obj.solid_geometry)
  221. except TypeError:
  222. grb_obj.solid_geometry = list(grb_obj.solid_geometry)
  223. new_solid_geometry = []
  224. for poly in grb_obj.solid_geometry:
  225. new_solid_geometry.append(poly.buffer(offset, int(grb_circle_steps)))
  226. new_solid_geometry = unary_union(new_solid_geometry)
  227. new_options = {}
  228. for opt in grb_obj.options:
  229. new_options[opt] = deepcopy(grb_obj.options[opt])
  230. new_apertures = deepcopy(grb_obj.apertures)
  231. for ap in new_apertures:
  232. for k in ap:
  233. if k == 'geometry':
  234. for geo_el in new_apertures[ap]['geometry']:
  235. if 'solid' in geo_el:
  236. geo_el['solid'] = geo_el['solid'].buffer(offset, int(grb_circle_steps))
  237. def init_func(new_obj, app_obj):
  238. """
  239. Init a new object in FlatCAM Object collection
  240. :param new_obj: New object
  241. :type new_obj: ObjectCollection
  242. :param app_obj: App
  243. :type app_obj: App_Main.App
  244. :return: None
  245. :rtype:
  246. """
  247. new_obj.options.update(new_options)
  248. new_obj.options['name'] = outname
  249. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  250. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  251. new_obj.apertures = deepcopy(new_apertures)
  252. new_obj.solid_geometry = deepcopy(new_solid_geometry)
  253. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  254. local_use=new_obj, use_thread=False)
  255. self.app.app_obj.new_object('gerber', outname, init_func)
  256. def reset_fields(self):
  257. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  258. @staticmethod
  259. def poly2rings(poly):
  260. return [poly.exterior] + [interior for interior in poly.interiors]
  261. # end of file