ToolSilk.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Marius Adrian Stanciu (c) #
  5. # Date: 4/24/2019 #
  6. # MIT Licence #
  7. ############################################################
  8. from FlatCAMTool import FlatCAMTool
  9. # from copy import copy, deepcopy
  10. from ObjectCollection import *
  11. # import time
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. from shapely.geometry import base
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. class ToolSilk(FlatCAMTool):
  20. toolName = _("Silkscreen Tool")
  21. def __init__(self, app):
  22. self.app = app
  23. FlatCAMTool.__init__(self, app)
  24. self.tools_frame = QtWidgets.QFrame()
  25. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  26. self.layout.addWidget(self.tools_frame)
  27. self.tools_box = QtWidgets.QVBoxLayout()
  28. self.tools_box.setContentsMargins(0, 0, 0, 0)
  29. self.tools_frame.setLayout(self.tools_box)
  30. # Title
  31. title_label = QtWidgets.QLabel("%s" % self.toolName)
  32. title_label.setStyleSheet("""
  33. QLabel
  34. {
  35. font-size: 16px;
  36. font-weight: bold;
  37. }
  38. """)
  39. self.tools_box.addWidget(title_label)
  40. # Form Layout
  41. form_layout = QtWidgets.QFormLayout()
  42. self.tools_box.addLayout(form_layout)
  43. # Object Silkscreen
  44. self.silk_object_combo = QtWidgets.QComboBox()
  45. self.silk_object_combo.setModel(self.app.collection)
  46. self.silk_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  47. self.silk_object_combo.setCurrentIndex(1)
  48. self.silk_object_label = QtWidgets.QLabel("Silk Gerber:")
  49. self.silk_object_label.setToolTip(
  50. _("Silkscreen Gerber object to be adjusted\n"
  51. "so it does not intersects the soldermask.")
  52. )
  53. e_lab_0 = QtWidgets.QLabel('')
  54. form_layout.addRow(self.silk_object_label, self.silk_object_combo)
  55. # Object Soldermask
  56. self.sm_object_combo = QtWidgets.QComboBox()
  57. self.sm_object_combo.setModel(self.app.collection)
  58. self.sm_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  59. self.sm_object_combo.setCurrentIndex(1)
  60. self.sm_object_label = QtWidgets.QLabel("SM Gerber:")
  61. self.sm_object_label.setToolTip(
  62. _("Soldermask Gerber object that will adjust\n"
  63. "the silkscreen so it does not overlap.")
  64. )
  65. e_lab_1 = QtWidgets.QLabel('')
  66. form_layout.addRow(self.sm_object_label, self.sm_object_combo)
  67. form_layout.addRow(e_lab_1)
  68. self.intersect_btn = FCButton(_('Remove overlap'))
  69. self.intersect_btn.setToolTip(
  70. _("Remove the silkscreen geometry\n"
  71. "that overlaps over the soldermask.")
  72. )
  73. self.tools_box.addWidget(self.intersect_btn)
  74. self.tools_box.addStretch()
  75. # QTimer for periodic check
  76. self.check_thread = QtCore.QTimer()
  77. # Every time an intersection job is started we add a promise; every time an intersection job is finished
  78. # we remove a promise.
  79. # When empty we start the layer rendering
  80. self.promises = []
  81. self.new_apertures = {}
  82. self.new_solid_geometry = []
  83. self.solder_union = None
  84. self.intersect_btn.clicked.connect(self.on_intersection_click)
  85. def install(self, icon=None, separator=None, **kwargs):
  86. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  87. def run(self, toggle=True):
  88. self.app.report_usage("ToolNonCopperClear()")
  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. self.app.ui.splitter.setSizes([0, 1])
  97. except AttributeError:
  98. pass
  99. else:
  100. if self.app.ui.splitter.sizes()[0] == 0:
  101. self.app.ui.splitter.setSizes([1, 1])
  102. FlatCAMTool.run(self)
  103. self.set_tool_ui()
  104. self.new_apertures.clear()
  105. self.new_solid_geometry = []
  106. self.app.ui.notebook.setTabText(2, _("Silk Tool"))
  107. def set_tool_ui(self):
  108. self.tools_frame.show()
  109. def on_intersection_click(self):
  110. self.silk_obj_name = self.silk_object_combo.currentText()
  111. # Get source object.
  112. try:
  113. self.silk_obj = self.app.collection.get_by_name(self.silk_obj_name)
  114. except:
  115. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  116. return "Could not retrieve object: %s" % self.silk_obj_name
  117. self.sm_obj_name = self.silk_object_combo.currentText()
  118. # Get source object.
  119. try:
  120. self.sm_obj = self.app.collection.get_by_name(self.sm_obj_name)
  121. except:
  122. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  123. return "Could not retrieve object: %s" % self.sm_obj_name
  124. # crate the new_apertures dict structure
  125. for apid in self.silk_obj.apertures:
  126. self.new_apertures[apid] = {}
  127. self.new_apertures[apid]['type'] = 'C'
  128. self.new_apertures[apid]['size'] = self.silk_obj.apertures[apid]['size']
  129. self.new_apertures[apid]['solid_geometry'] = []
  130. geo_union_list = []
  131. for apid1 in self.sm_obj.apertures:
  132. geo_union_list += self.sm_obj.apertures[apid1]['solid_geometry']
  133. self.solder_union = cascaded_union(geo_union_list)
  134. # start the QTimer with 1 second period check
  135. self.periodic_check(1000)
  136. for apid in self.silk_obj.apertures:
  137. ap_size = self.silk_obj.apertures[apid]['size']
  138. geo_list = self.silk_obj.apertures[apid]['solid_geometry']
  139. self.app.worker_task.emit({'fcn': self.aperture_intersection,
  140. 'params': [apid, ap_size, geo_list]})
  141. def aperture_intersection(self, aperture_id, aperture_size, geo_list):
  142. self.promises.append(aperture_id)
  143. new_solid_geometry = []
  144. with self.app.proc_container.new(_("Parsing aperture %s geometry ..." % str(aperture_id))):
  145. for geo_silk in geo_list:
  146. for sm_ap in self.sm_obj.apertures:
  147. for key in self.sm_obj.apertures[sm_ap]:
  148. if key == 'solid_geometry':
  149. if geo_silk.intersects(self.solder_union):
  150. new_geo = geo_silk.symmetric_difference(self.solder_union)
  151. # if the resulting geometry is not empty add it to the new_apertures solid_geometry
  152. if type(new_geo) == MultiPolygon:
  153. for g in new_geo:
  154. new_solid_geometry.append(g)
  155. else:
  156. new_solid_geometry.append(new_geo)
  157. else:
  158. new_solid_geometry.append(geo_silk)
  159. # while not self.new_apertures[aperture_id]['solid_geometry']:
  160. try:
  161. self.new_apertures[aperture_id]['solid_geometry'] = new_solid_geometry
  162. except:
  163. pass
  164. # while aperture_id in self.promises:
  165. # removal from list is done in a multithreaded way therefore not always the removal can be done
  166. try:
  167. self.promises.remove(aperture_id)
  168. except:
  169. pass
  170. def periodic_check(self, check_period):
  171. """
  172. This function starts an QTimer and it will periodically check if intersections are done
  173. :param check_period: time at which to check periodically
  174. :return:
  175. """
  176. log.debug("ToolSilk --> Periodic Check started.")
  177. try:
  178. self.check_thread.stop()
  179. except:
  180. pass
  181. self.check_thread.setInterval(check_period)
  182. try:
  183. self.check_thread.timeout.disconnect(self.periodic_check_handler)
  184. except:
  185. pass
  186. self.check_thread.timeout.connect(self.periodic_check_handler)
  187. self.check_thread.start(QtCore.QThread.HighPriority)
  188. def periodic_check_handler(self):
  189. """
  190. If the intersections workers finished then start creating the solid_geometry
  191. :return:
  192. """
  193. # log.debug("checking parsing --> %s" % str(self.parsing_promises))
  194. outname = self.silk_object_combo.currentText() + '_cleaned'
  195. try:
  196. if not self.promises:
  197. self.check_thread.stop()
  198. # intersection jobs finished, start the creation of solid_geometry
  199. self.app.worker_task.emit({'fcn': self.new_silkscreen_object,
  200. 'params': [outname]})
  201. log.debug("ToolPDF --> Periodic check finished.")
  202. except Exception:
  203. traceback.print_exc()
  204. def new_silkscreen_object(self, outname):
  205. def obj_init(grb_obj, app_obj):
  206. grb_obj.apertures = deepcopy(self.new_apertures)
  207. poly_buff = []
  208. for ap in self.new_apertures:
  209. for k in self.new_apertures[ap]:
  210. if k == 'solid_geometry':
  211. poly_buff += self.new_apertures[ap][k]
  212. poly_buff = unary_union(poly_buff)
  213. try:
  214. poly_buff = poly_buff.buffer(0.0000001)
  215. except ValueError:
  216. pass
  217. try:
  218. poly_buff = poly_buff.buffer(-0.0000001)
  219. except ValueError:
  220. pass
  221. grb_obj.solid_geometry = deepcopy(poly_buff)
  222. # self.new_apertures.clear()
  223. with self.app.proc_container.new(_("Generating cleaned SS object ...")):
  224. ret = self.app.new_object('gerber', outname, obj_init, autoselected=False)
  225. if ret == 'fail':
  226. self.app.inform.emit(_('[ERROR_NOTCL] Generating SilkScreen file failed.'))
  227. return
  228. # Register recent file
  229. self.app.file_opened.emit('gerber', outname)
  230. # GUI feedback
  231. self.app.inform.emit(_("[success] Created: %s") % outname)
  232. def reset_fields(self):
  233. self.silk_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  234. self.sm_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))