ToolSub.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 4/24/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from AppTool import AppTool
  9. from AppGUI.GUIElements import FCCheckBox, FCButton, FCComboBox
  10. from shapely.geometry import Polygon, MultiPolygon, MultiLineString, LineString
  11. from shapely.ops import cascaded_union
  12. import traceback
  13. from copy import deepcopy
  14. import time
  15. import logging
  16. import gettext
  17. import AppTranslation as fcTranslate
  18. import builtins
  19. fcTranslate.apply_language('strings')
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. log = logging.getLogger('base')
  23. class ToolSub(AppTool):
  24. job_finished = QtCore.pyqtSignal(bool)
  25. # the string param is the outname and the list is a list of tuples each being formed from the new_aperture_geometry
  26. # list and the second element is also a list with possible geometry that needs to be added to the '0' aperture
  27. # meaning geometry that was deformed
  28. aperture_processing_finished = QtCore.pyqtSignal(str, list)
  29. toolName = _("Subtract Tool")
  30. def __init__(self, app):
  31. self.app = app
  32. self.decimals = self.app.decimals
  33. AppTool.__init__(self, app)
  34. self.tools_frame = QtWidgets.QFrame()
  35. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  36. self.layout.addWidget(self.tools_frame)
  37. self.tools_box = QtWidgets.QVBoxLayout()
  38. self.tools_box.setContentsMargins(0, 0, 0, 0)
  39. self.tools_frame.setLayout(self.tools_box)
  40. # Title
  41. title_label = QtWidgets.QLabel("%s" % self.toolName)
  42. title_label.setStyleSheet("""
  43. QLabel
  44. {
  45. font-size: 16px;
  46. font-weight: bold;
  47. }
  48. """)
  49. self.tools_box.addWidget(title_label)
  50. # Form Layout
  51. form_layout = QtWidgets.QFormLayout()
  52. self.tools_box.addLayout(form_layout)
  53. self.gerber_title = QtWidgets.QLabel("<b>%s</b>" % _("GERBER"))
  54. form_layout.addRow(self.gerber_title)
  55. # Target Gerber Object
  56. self.target_gerber_combo = FCComboBox()
  57. self.target_gerber_combo.setModel(self.app.collection)
  58. self.target_gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  59. # self.target_gerber_combo.setCurrentIndex(1)
  60. self.target_gerber_combo.is_last = True
  61. self.target_gerber_combo.obj_type = "Gerber"
  62. self.target_gerber_label = QtWidgets.QLabel('%s:' % _("Target"))
  63. self.target_gerber_label.setToolTip(
  64. _("Gerber object from which to subtract\n"
  65. "the subtractor Gerber object.")
  66. )
  67. form_layout.addRow(self.target_gerber_label, self.target_gerber_combo)
  68. # Substractor Gerber Object
  69. self.sub_gerber_combo = FCComboBox()
  70. self.sub_gerber_combo.setModel(self.app.collection)
  71. self.sub_gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  72. self.sub_gerber_combo.is_last = True
  73. self.sub_gerber_combo.obj_type = "Gerber"
  74. self.sub_gerber_label = QtWidgets.QLabel('%s:' % _("Subtractor"))
  75. self.sub_gerber_label.setToolTip(
  76. _("Gerber object that will be subtracted\n"
  77. "from the target Gerber object.")
  78. )
  79. e_lab_1 = QtWidgets.QLabel('')
  80. form_layout.addRow(self.sub_gerber_label, self.sub_gerber_combo)
  81. self.intersect_btn = FCButton(_('Subtract Gerber'))
  82. self.intersect_btn.setToolTip(
  83. _("Will remove the area occupied by the subtractor\n"
  84. "Gerber from the Target Gerber.\n"
  85. "Can be used to remove the overlapping silkscreen\n"
  86. "over the soldermask.")
  87. )
  88. self.intersect_btn.setStyleSheet("""
  89. QPushButton
  90. {
  91. font-weight: bold;
  92. }
  93. """)
  94. self.tools_box.addWidget(self.intersect_btn)
  95. self.tools_box.addWidget(e_lab_1)
  96. # Form Layout
  97. form_geo_layout = QtWidgets.QFormLayout()
  98. self.tools_box.addLayout(form_geo_layout)
  99. self.geo_title = QtWidgets.QLabel("<b>%s</b>" % _("GEOMETRY"))
  100. form_geo_layout.addRow(self.geo_title)
  101. # Target Geometry Object
  102. self.target_geo_combo = FCComboBox()
  103. self.target_geo_combo.setModel(self.app.collection)
  104. self.target_geo_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  105. # self.target_geo_combo.setCurrentIndex(1)
  106. self.target_geo_combo.is_last = True
  107. self.target_geo_combo.obj_type = "Geometry"
  108. self.target_geo_label = QtWidgets.QLabel('%s:' % _("Target"))
  109. self.target_geo_label.setToolTip(
  110. _("Geometry object from which to subtract\n"
  111. "the subtractor Geometry object.")
  112. )
  113. form_geo_layout.addRow(self.target_geo_label, self.target_geo_combo)
  114. # Substractor Geometry Object
  115. self.sub_geo_combo = FCComboBox()
  116. self.sub_geo_combo.setModel(self.app.collection)
  117. self.sub_geo_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  118. self.sub_geo_combo.is_last = True
  119. self.sub_geo_combo.obj_type = "Geometry"
  120. self.sub_geo_label = QtWidgets.QLabel('%s:' % _("Subtractor"))
  121. self.sub_geo_label.setToolTip(
  122. _("Geometry object that will be subtracted\n"
  123. "from the target Geometry object.")
  124. )
  125. e_lab_1 = QtWidgets.QLabel('')
  126. form_geo_layout.addRow(self.sub_geo_label, self.sub_geo_combo)
  127. self.close_paths_cb = FCCheckBox(_("Close paths"))
  128. self.close_paths_cb.setToolTip(_("Checking this will close the paths cut by the Geometry subtractor object."))
  129. self.tools_box.addWidget(self.close_paths_cb)
  130. self.intersect_geo_btn = FCButton(_('Subtract Geometry'))
  131. self.intersect_geo_btn.setToolTip(
  132. _("Will remove the area occupied by the subtractor\n"
  133. "Geometry from the Target Geometry.")
  134. )
  135. self.intersect_geo_btn.setStyleSheet("""
  136. QPushButton
  137. {
  138. font-weight: bold;
  139. }
  140. """)
  141. self.tools_box.addWidget(self.intersect_geo_btn)
  142. self.tools_box.addWidget(e_lab_1)
  143. self.tools_box.addStretch()
  144. # ## Reset Tool
  145. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  146. self.reset_button.setToolTip(
  147. _("Will reset the tool parameters.")
  148. )
  149. self.reset_button.setStyleSheet("""
  150. QPushButton
  151. {
  152. font-weight: bold;
  153. }
  154. """)
  155. self.tools_box.addWidget(self.reset_button)
  156. # QTimer for periodic check
  157. self.check_thread = QtCore.QTimer()
  158. # Every time an intersection job is started we add a promise; every time an intersection job is finished
  159. # we remove a promise.
  160. # When empty we start the layer rendering
  161. self.promises = []
  162. self.new_apertures = {}
  163. self.new_tools = {}
  164. self.new_solid_geometry = []
  165. self.sub_solid_union = None
  166. self.sub_follow_union = None
  167. self.sub_clear_union = None
  168. self.sub_grb_obj = None
  169. self.sub_grb_obj_name = None
  170. self.target_grb_obj = None
  171. self.target_grb_obj_name = None
  172. self.sub_geo_obj = None
  173. self.sub_geo_obj_name = None
  174. self.target_geo_obj = None
  175. self.target_geo_obj_name = None
  176. # signal which type of substraction to do: "geo" or "gerber"
  177. self.sub_type = None
  178. # store here the options from target_obj
  179. self.target_options = {}
  180. self.sub_union = []
  181. # multiprocessing
  182. self.pool = self.app.pool
  183. self.results = []
  184. self.intersect_btn.clicked.connect(self.on_grb_intersection_click)
  185. self.intersect_geo_btn.clicked.connect(self.on_geo_intersection_click)
  186. self.job_finished.connect(self.on_job_finished)
  187. self.aperture_processing_finished.connect(self.new_gerber_object)
  188. self.reset_button.clicked.connect(self.set_tool_ui)
  189. def install(self, icon=None, separator=None, **kwargs):
  190. AppTool.install(self, icon, separator, shortcut='Alt+W', **kwargs)
  191. def run(self, toggle=True):
  192. self.app.defaults.report_usage("ToolSub()")
  193. if toggle:
  194. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  195. if self.app.ui.splitter.sizes()[0] == 0:
  196. self.app.ui.splitter.setSizes([1, 1])
  197. else:
  198. try:
  199. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  200. # if tab is populated with the tool but it does not have the focus, focus on it
  201. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  202. # focus on Tool Tab
  203. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  204. else:
  205. self.app.ui.splitter.setSizes([0, 1])
  206. except AttributeError:
  207. pass
  208. else:
  209. if self.app.ui.splitter.sizes()[0] == 0:
  210. self.app.ui.splitter.setSizes([1, 1])
  211. AppTool.run(self)
  212. self.set_tool_ui()
  213. self.app.ui.notebook.setTabText(2, _("Sub Tool"))
  214. def set_tool_ui(self):
  215. self.new_apertures.clear()
  216. self.new_tools.clear()
  217. self.new_solid_geometry = []
  218. self.target_options.clear()
  219. self.tools_frame.show()
  220. self.close_paths_cb.setChecked(self.app.defaults["tools_sub_close_paths"])
  221. def on_grb_intersection_click(self):
  222. # reset previous values
  223. self.new_apertures.clear()
  224. self.new_solid_geometry = []
  225. self.sub_union = []
  226. self.sub_type = "gerber"
  227. self.target_grb_obj_name = self.target_gerber_combo.currentText()
  228. if self.target_grb_obj_name == '':
  229. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No Target object loaded."))
  230. return
  231. self.app.inform.emit('%s' % _("Loading geometry from Gerber objects."))
  232. # Get target object.
  233. try:
  234. self.target_grb_obj = self.app.collection.get_by_name(self.target_grb_obj_name)
  235. except Exception as e:
  236. log.debug("ToolSub.on_grb_intersection_click() --> %s" % str(e))
  237. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  238. return "Could not retrieve object: %s" % self.target_grb_obj_name
  239. self.sub_grb_obj_name = self.sub_gerber_combo.currentText()
  240. if self.sub_grb_obj_name == '':
  241. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No Subtractor object loaded."))
  242. return
  243. # Get substractor object.
  244. try:
  245. self.sub_grb_obj = self.app.collection.get_by_name(self.sub_grb_obj_name)
  246. except Exception as e:
  247. log.debug("ToolSub.on_grb_intersection_click() --> %s" % str(e))
  248. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  249. return "Could not retrieve object: %s" % self.sub_grb_obj_name
  250. # crate the new_apertures dict structure
  251. for apid in self.target_grb_obj.apertures:
  252. self.new_apertures[apid] = {}
  253. for key in self.target_grb_obj.apertures[apid]:
  254. if key == 'geometry':
  255. self.new_apertures[apid]['geometry'] = []
  256. else:
  257. self.new_apertures[apid][key] = self.target_grb_obj.apertures[apid][key]
  258. def worker_job(app_obj):
  259. for apid in self.target_grb_obj.apertures:
  260. target_geo = self.target_grb_obj.apertures[apid]['geometry']
  261. sub_geometry = {}
  262. sub_geometry['solid'] = []
  263. sub_geometry['clear'] = []
  264. for s_apid in self.sub_grb_obj.apertures:
  265. for s_el in self.sub_grb_obj.apertures[s_apid]['geometry']:
  266. if "solid" in s_el:
  267. sub_geometry['solid'].append(s_el["solid"])
  268. if "clear" in s_el:
  269. sub_geometry['clear'].append(s_el["clear"])
  270. self.results.append(
  271. self.pool.apply_async(self.aperture_intersection, args=(apid, target_geo, sub_geometry))
  272. )
  273. output = []
  274. for p in self.results:
  275. res = p.get()
  276. output.append(res)
  277. app_obj.inform.emit('%s: %s...' % (_("Finished parsing geometry for aperture"), str(res[0])))
  278. app_obj.inform.emit("%s" % _("Subtraction aperture processing finished."))
  279. outname = self.target_gerber_combo.currentText() + '_sub'
  280. self.aperture_processing_finished.emit(outname, output)
  281. self.app.worker_task.emit({'fcn': worker_job, 'params': [self.app]})
  282. @staticmethod
  283. def aperture_intersection(apid, target_geo, sub_geometry):
  284. """
  285. :param apid: the aperture id for which we process geometry
  286. :type apid: str
  287. :param target_geo: the geometry list that holds the geometry from which we subtract
  288. :type target_geo: list
  289. :param sub_geometry: the apertures dict that holds all the geometry that is subtracted
  290. :type sub_geometry: dict
  291. :return: (apid, unaffected_geometry lsit, affected_geometry list)
  292. :rtype: tuple
  293. """
  294. unafected_geo = []
  295. affected_geo = []
  296. is_modified = False
  297. for geo_el in target_geo:
  298. new_geo_el = {}
  299. if "solid" in geo_el:
  300. for sub_solid_geo in sub_geometry["solid"]:
  301. if geo_el["solid"].intersects(sub_solid_geo):
  302. new_geo = geo_el["solid"].difference(sub_solid_geo)
  303. if not new_geo.is_empty:
  304. geo_el["solid"] = new_geo
  305. is_modified = True
  306. new_geo_el["solid"] = deepcopy(geo_el["solid"])
  307. if "clear" in geo_el:
  308. for sub_solid_geo in sub_geometry["clear"]:
  309. if geo_el["clear"].intersects(sub_solid_geo):
  310. new_geo = geo_el["clear"].difference(sub_solid_geo)
  311. if not new_geo.is_empty:
  312. geo_el["clear"] = new_geo
  313. is_modified = True
  314. new_geo_el["clear"] = deepcopy(geo_el["clear"])
  315. if is_modified:
  316. affected_geo.append(new_geo_el)
  317. else:
  318. unafected_geo.append(geo_el)
  319. return apid, unafected_geo, affected_geo
  320. def new_gerber_object(self, outname, output):
  321. """
  322. :param outname: name for the new Gerber object
  323. :type outname: str
  324. :param output: a list made of tuples in format:
  325. (aperture id in the target Gerber, unaffected_geometry list, affected_geometry list)
  326. :type output: list
  327. :return:
  328. :rtype:
  329. """
  330. def obj_init(grb_obj, app_obj):
  331. grb_obj.apertures = deepcopy(self.new_apertures)
  332. if '0' not in grb_obj.apertures:
  333. grb_obj.apertures['0'] = {}
  334. grb_obj.apertures['0']['type'] = 'REG'
  335. grb_obj.apertures['0']['size'] = 0.0
  336. grb_obj.apertures['0']['geometry'] = []
  337. for apid, apid_val in list(grb_obj.apertures.items()):
  338. for t in output:
  339. new_apid = t[0]
  340. if apid == new_apid:
  341. surving_geo = t[1]
  342. modified_geo = t[2]
  343. if surving_geo:
  344. apid_val['geometry'] = deepcopy(surving_geo)
  345. else:
  346. grb_obj.apertures.pop(apid, None)
  347. if modified_geo:
  348. grb_obj.apertures['0']['geometry'] += modified_geo
  349. # delete the '0' aperture if it has no geometry
  350. if not grb_obj.apertures['0']['geometry']:
  351. grb_obj.apertures.pop('0', None)
  352. poly_buff = []
  353. follow_buff = []
  354. for ap in grb_obj.apertures:
  355. for elem in grb_obj.apertures[ap]['geometry']:
  356. if 'solid' in elem:
  357. solid_geo = elem['solid']
  358. poly_buff.append(solid_geo)
  359. if 'follow' in elem:
  360. follow_buff.append(elem['follow'])
  361. work_poly_buff = MultiPolygon(poly_buff)
  362. try:
  363. poly_buff = work_poly_buff.buffer(0.0000001)
  364. except ValueError:
  365. pass
  366. try:
  367. poly_buff = poly_buff.buffer(-0.0000001)
  368. except ValueError:
  369. pass
  370. grb_obj.solid_geometry = deepcopy(poly_buff)
  371. grb_obj.follow_geometry = deepcopy(follow_buff)
  372. grb_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  373. local_use=grb_obj, use_thread=False)
  374. with self.app.proc_container.new(_("Generating new object ...")):
  375. ret = self.app.app_obj.new_object('gerber', outname, obj_init, autoselected=False)
  376. if ret == 'fail':
  377. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Generating new object failed.'))
  378. return
  379. # GUI feedback
  380. self.app.inform.emit('[success] %s: %s' % (_("Created"), outname))
  381. # cleanup
  382. self.new_apertures.clear()
  383. self.new_solid_geometry[:] = []
  384. self.results = []
  385. def on_geo_intersection_click(self):
  386. # reset previous values
  387. self.new_tools.clear()
  388. self.target_options.clear()
  389. self.new_solid_geometry = []
  390. self.sub_union = []
  391. self.sub_type = "geo"
  392. self.target_geo_obj_name = self.target_geo_combo.currentText()
  393. if self.target_geo_obj_name == '':
  394. self.app.inform.emit('[ERROR_NOTCL] %s' %
  395. _("No Target object loaded."))
  396. return
  397. # Get target object.
  398. try:
  399. self.target_geo_obj = self.app.collection.get_by_name(self.target_geo_obj_name)
  400. except Exception as e:
  401. log.debug("ToolSub.on_geo_intersection_click() --> %s" % str(e))
  402. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  403. (_("Could not retrieve object"), self.target_geo_obj_name))
  404. return "Could not retrieve object: %s" % self.target_grb_obj_name
  405. self.sub_geo_obj_name = self.sub_geo_combo.currentText()
  406. if self.sub_geo_obj_name == '':
  407. self.app.inform.emit('[ERROR_NOTCL] %s' %
  408. _("No Subtractor object loaded."))
  409. return
  410. # Get substractor object.
  411. try:
  412. self.sub_geo_obj = self.app.collection.get_by_name(self.sub_geo_obj_name)
  413. except Exception as e:
  414. log.debug("ToolSub.on_geo_intersection_click() --> %s" % str(e))
  415. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  416. (_("Could not retrieve object"), self.sub_geo_obj_name))
  417. return "Could not retrieve object: %s" % self.sub_geo_obj_name
  418. if self.sub_geo_obj.multigeo:
  419. self.app.inform.emit('[ERROR_NOTCL] %s' %
  420. _("Currently, the Subtractor geometry cannot be of type Multigeo."))
  421. return
  422. # create the target_options obj
  423. # self.target_options = {}
  424. # for k, v in self.target_geo_obj.options.items():
  425. # if k != 'name':
  426. # self.target_options[k] = v
  427. # crate the new_tools dict structure
  428. for tool in self.target_geo_obj.tools:
  429. self.new_tools[tool] = {}
  430. for key in self.target_geo_obj.tools[tool]:
  431. if key == 'solid_geometry':
  432. self.new_tools[tool][key] = []
  433. else:
  434. self.new_tools[tool][key] = deepcopy(self.target_geo_obj.tools[tool][key])
  435. # add the promises
  436. if self.target_geo_obj.multigeo:
  437. for tool in self.target_geo_obj.tools:
  438. self.promises.append(tool)
  439. else:
  440. self.promises.append("single")
  441. self.sub_union = cascaded_union(self.sub_geo_obj.solid_geometry)
  442. # start the QTimer to check for promises with 0.5 second period check
  443. self.periodic_check(500, reset=True)
  444. if self.target_geo_obj.multigeo:
  445. for tool in self.target_geo_obj.tools:
  446. geo = self.target_geo_obj.tools[tool]['solid_geometry']
  447. self.app.worker_task.emit({'fcn': self.toolgeo_intersection,
  448. 'params': [tool, geo]})
  449. else:
  450. geo = self.target_geo_obj.solid_geometry
  451. self.app.worker_task.emit({'fcn': self.toolgeo_intersection,
  452. 'params': ["single", geo]})
  453. def toolgeo_intersection(self, tool, geo):
  454. new_geometry = []
  455. log.debug("Working on promise: %s" % str(tool))
  456. if tool == "single":
  457. text = _("Parsing solid_geometry ...")
  458. else:
  459. text = '%s: %s...' % (_("Parsing solid_geometry for tool"), str(tool))
  460. with self.app.proc_container.new(text):
  461. # resulting paths are closed resulting into Polygons
  462. if self.close_paths_cb.isChecked():
  463. new_geo = (cascaded_union(geo)).difference(self.sub_union)
  464. if new_geo:
  465. if not new_geo.is_empty:
  466. new_geometry.append(new_geo)
  467. # resulting paths are unclosed resulting in a multitude of rings
  468. else:
  469. try:
  470. for geo_elem in geo:
  471. if isinstance(geo_elem, Polygon):
  472. for ring in self.poly2rings(geo_elem):
  473. new_geo = ring.difference(self.sub_union)
  474. if new_geo and not new_geo.is_empty:
  475. new_geometry.append(new_geo)
  476. elif isinstance(geo_elem, MultiPolygon):
  477. for poly in geo_elem:
  478. for ring in self.poly2rings(poly):
  479. new_geo = ring.difference(self.sub_union)
  480. if new_geo and not new_geo.is_empty:
  481. new_geometry.append(new_geo)
  482. elif isinstance(geo_elem, LineString):
  483. new_geo = geo_elem.difference(self.sub_union)
  484. if new_geo:
  485. if not new_geo.is_empty:
  486. new_geometry.append(new_geo)
  487. elif isinstance(geo_elem, MultiLineString):
  488. for line_elem in geo_elem:
  489. new_geo = line_elem.difference(self.sub_union)
  490. if new_geo and not new_geo.is_empty:
  491. new_geometry.append(new_geo)
  492. except TypeError:
  493. if isinstance(geo, Polygon):
  494. for ring in self.poly2rings(geo):
  495. new_geo = ring.difference(self.sub_union)
  496. if new_geo:
  497. if not new_geo.is_empty:
  498. new_geometry.append(new_geo)
  499. elif isinstance(geo, LineString):
  500. new_geo = geo.difference(self.sub_union)
  501. if new_geo and not new_geo.is_empty:
  502. new_geometry.append(new_geo)
  503. elif isinstance(geo, MultiLineString):
  504. for line_elem in geo:
  505. new_geo = line_elem.difference(self.sub_union)
  506. if new_geo and not new_geo.is_empty:
  507. new_geometry.append(new_geo)
  508. if new_geometry:
  509. if tool == "single":
  510. while not self.new_solid_geometry:
  511. self.new_solid_geometry = deepcopy(new_geometry)
  512. time.sleep(0.5)
  513. else:
  514. while not self.new_tools[tool]['solid_geometry']:
  515. self.new_tools[tool]['solid_geometry'] = deepcopy(new_geometry)
  516. time.sleep(0.5)
  517. while True:
  518. # removal from list is done in a multithreaded way therefore not always the removal can be done
  519. # so we keep trying until it's done
  520. if tool not in self.promises:
  521. break
  522. self.promises.remove(tool)
  523. time.sleep(0.5)
  524. log.debug("Promise fulfilled: %s" % str(tool))
  525. def new_geo_object(self, outname):
  526. geo_name = outname
  527. def obj_init(geo_obj, app_obj):
  528. # geo_obj.options = self.target_options
  529. # create the target_options obj
  530. for k, v in self.target_geo_obj.options.items():
  531. geo_obj.options[k] = v
  532. geo_obj.options['name'] = geo_name
  533. if self.target_geo_obj.multigeo:
  534. geo_obj.tools = deepcopy(self.new_tools)
  535. # this turn on the FlatCAMCNCJob plot for multiple tools
  536. geo_obj.multigeo = True
  537. geo_obj.multitool = True
  538. else:
  539. geo_obj.solid_geometry = deepcopy(self.new_solid_geometry)
  540. try:
  541. geo_obj.tools = deepcopy(self.new_tools)
  542. for tool in geo_obj.tools:
  543. geo_obj.tools[tool]['solid_geometry'] = deepcopy(self.new_solid_geometry)
  544. except Exception as e:
  545. log.debug("ToolSub.new_geo_object() --> %s" % str(e))
  546. geo_obj.multigeo = False
  547. with self.app.proc_container.new(_("Generating new object ...")):
  548. ret = self.app.app_obj.new_object('geometry', outname, obj_init, autoselected=False)
  549. if ret == 'fail':
  550. self.app.inform.emit('[ERROR_NOTCL] %s' %
  551. _('Generating new object failed.'))
  552. return
  553. # Register recent file
  554. self.app.file_opened.emit('geometry', outname)
  555. # GUI feedback
  556. self.app.inform.emit('[success] %s: %s' %
  557. (_("Created"), outname))
  558. # cleanup
  559. self.new_tools.clear()
  560. self.new_solid_geometry[:] = []
  561. self.sub_union = []
  562. def periodic_check(self, check_period, reset=False):
  563. """
  564. This function starts an QTimer and it will periodically check if intersections are done
  565. :param check_period: time at which to check periodically
  566. :param reset: will reset the timer
  567. :return:
  568. """
  569. log.debug("ToolSub --> Periodic Check started.")
  570. try:
  571. self.check_thread.stop()
  572. except (TypeError, AttributeError):
  573. pass
  574. if reset:
  575. self.check_thread.setInterval(check_period)
  576. try:
  577. self.check_thread.timeout.disconnect(self.periodic_check_handler)
  578. except (TypeError, AttributeError):
  579. pass
  580. self.check_thread.timeout.connect(self.periodic_check_handler)
  581. self.check_thread.start(QtCore.QThread.HighPriority)
  582. def periodic_check_handler(self):
  583. """
  584. If the intersections workers finished then start creating the solid_geometry
  585. :return:
  586. """
  587. # log.debug("checking parsing --> %s" % str(self.parsing_promises))
  588. try:
  589. if not self.promises:
  590. self.check_thread.stop()
  591. self.job_finished.emit(True)
  592. # reset the type of substraction for next time
  593. self.sub_type = None
  594. log.debug("ToolSub --> Periodic check finished.")
  595. except Exception as e:
  596. self.job_finished.emit(False)
  597. log.debug("ToolSub().periodic_check_handler() --> %s" % str(e))
  598. traceback.print_exc()
  599. def on_job_finished(self, succcess):
  600. """
  601. :param succcess: boolean, this parameter signal if all the apertures were processed
  602. :return: None
  603. """
  604. if succcess is True:
  605. if self.sub_type == "gerber":
  606. outname = self.target_gerber_combo.currentText() + '_sub'
  607. # intersection jobs finished, start the creation of solid_geometry
  608. self.app.worker_task.emit({'fcn': self.new_gerber_object,
  609. 'params': [outname]})
  610. else:
  611. outname = self.target_geo_combo.currentText() + '_sub'
  612. # intersection jobs finished, start the creation of solid_geometry
  613. self.app.worker_task.emit({'fcn': self.new_geo_object, 'params': [outname]})
  614. else:
  615. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Generating new object failed.'))
  616. def reset_fields(self):
  617. self.target_gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  618. self.sub_gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  619. self.target_geo_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  620. self.sub_geo_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  621. @staticmethod
  622. def poly2rings(poly):
  623. return [poly.exterior] + [interior for interior in poly.interiors]
  624. # end of file