ToolNonCopperClear.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Modified by: Marius Adrian Stanciu (c) #
  5. # Date: 3/10/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 NonCopperClear(FlatCAMTool, Gerber):
  20. toolName = _("Non-Copper Clearing")
  21. def __init__(self, app):
  22. self.app = app
  23. FlatCAMTool.__init__(self, app)
  24. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  25. self.tools_frame = QtWidgets.QFrame()
  26. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  27. self.layout.addWidget(self.tools_frame)
  28. self.tools_box = QtWidgets.QVBoxLayout()
  29. self.tools_box.setContentsMargins(0, 0, 0, 0)
  30. self.tools_frame.setLayout(self.tools_box)
  31. # ## Title
  32. title_label = QtWidgets.QLabel("%s" % self.toolName)
  33. title_label.setStyleSheet("""
  34. QLabel
  35. {
  36. font-size: 16px;
  37. font-weight: bold;
  38. }
  39. """)
  40. self.tools_box.addWidget(title_label)
  41. # ## Form Layout
  42. form_layout = QtWidgets.QFormLayout()
  43. self.tools_box.addLayout(form_layout)
  44. # ## Object
  45. self.object_combo = QtWidgets.QComboBox()
  46. self.object_combo.setModel(self.app.collection)
  47. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  48. self.object_combo.setCurrentIndex(1)
  49. self.object_label = QtWidgets.QLabel("Gerber:")
  50. self.object_label.setToolTip(
  51. _("Gerber object to be cleared of excess copper. ")
  52. )
  53. e_lab_0 = QtWidgets.QLabel('')
  54. form_layout.addRow(self.object_label, self.object_combo)
  55. form_layout.addRow(e_lab_0)
  56. #### Tools ## ##
  57. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  58. self.tools_table_label.setToolTip(
  59. _("Tools pool from which the algorithm\n"
  60. "will pick the ones used for copper clearing.")
  61. )
  62. self.tools_box.addWidget(self.tools_table_label)
  63. self.tools_table = FCTable()
  64. self.tools_box.addWidget(self.tools_table)
  65. self.tools_table.setColumnCount(4)
  66. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  67. self.tools_table.setColumnHidden(3, True)
  68. self.tools_table.setSortingEnabled(False)
  69. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  70. self.tools_table.horizontalHeaderItem(0).setToolTip(
  71. _("This is the Tool Number.\n"
  72. "Non copper clearing will start with the tool with the biggest \n"
  73. "diameter, continuing until there are no more tools.\n"
  74. "Only tools that create NCC clearing geometry will still be present\n"
  75. "in the resulting geometry. This is because with some tools\n"
  76. "this function will not be able to create painting geometry.")
  77. )
  78. self.tools_table.horizontalHeaderItem(1).setToolTip(
  79. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  80. "is the cut width into the material."))
  81. self.tools_table.horizontalHeaderItem(2).setToolTip(
  82. _("The Tool Type (TT) can be:<BR>"
  83. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  84. "the cut width in material is exactly the tool diameter.<BR>"
  85. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  86. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  87. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  88. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  89. "as the cut width into material will be equal with the value in the Tool Diameter "
  90. "column of this table.<BR>"
  91. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  92. "in the resulting geometry as Isolation."))
  93. self.empty_label = QtWidgets.QLabel('')
  94. self.tools_box.addWidget(self.empty_label)
  95. # ### Add a new Tool ####
  96. hlay = QtWidgets.QHBoxLayout()
  97. self.tools_box.addLayout(hlay)
  98. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  99. self.addtool_entry_lbl.setToolTip(
  100. _("Diameter for the new tool to add in the Tool Table")
  101. )
  102. self.addtool_entry = FCEntry2()
  103. # hlay.addWidget(self.addtool_label)
  104. # hlay.addStretch()
  105. hlay.addWidget(self.addtool_entry_lbl)
  106. hlay.addWidget(self.addtool_entry)
  107. grid2 = QtWidgets.QGridLayout()
  108. self.tools_box.addLayout(grid2)
  109. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  110. self.addtool_btn.setToolTip(
  111. _("Add a new tool to the Tool Table\n"
  112. "with the diameter specified above.")
  113. )
  114. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  115. # self.copytool_btn.setToolTip(
  116. # "Copy a selection of tools in the Tool Table\n"
  117. # "by first selecting a row in the Tool Table."
  118. # )
  119. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  120. self.deltool_btn.setToolTip(
  121. _("Delete a selection of tools in the Tool Table\n"
  122. "by first selecting a row(s) in the Tool Table.")
  123. )
  124. grid2.addWidget(self.addtool_btn, 0, 0)
  125. # grid2.addWidget(self.copytool_btn, 0, 1)
  126. grid2.addWidget(self.deltool_btn, 0, 2)
  127. self.empty_label_0 = QtWidgets.QLabel('')
  128. self.tools_box.addWidget(self.empty_label_0)
  129. grid3 = QtWidgets.QGridLayout()
  130. self.tools_box.addLayout(grid3)
  131. e_lab_1 = QtWidgets.QLabel('')
  132. grid3.addWidget(e_lab_1, 0, 0)
  133. nccoverlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  134. nccoverlabel.setToolTip(
  135. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  136. "Example:\n"
  137. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  138. "Adjust the value starting with lower values\n"
  139. "and increasing it if areas that should be cleared are still \n"
  140. "not cleared.\n"
  141. "Lower values = faster processing, faster execution on PCB.\n"
  142. "Higher values = slow processing and slow execution on CNC\n"
  143. "due of too many paths.")
  144. )
  145. grid3.addWidget(nccoverlabel, 1, 0)
  146. self.ncc_overlap_entry = FCEntry()
  147. grid3.addWidget(self.ncc_overlap_entry, 1, 1)
  148. nccmarginlabel = QtWidgets.QLabel(_('Margin:'))
  149. nccmarginlabel.setToolTip(
  150. _("Bounding box margin.")
  151. )
  152. grid3.addWidget(nccmarginlabel, 2, 0)
  153. self.ncc_margin_entry = FCEntry()
  154. grid3.addWidget(self.ncc_margin_entry, 2, 1)
  155. # Method
  156. methodlabel = QtWidgets.QLabel(_('Method:'))
  157. methodlabel.setToolTip(
  158. _("Algorithm for non-copper clearing:<BR>"
  159. "<B>Standard</B>: Fixed step inwards.<BR>"
  160. "<B>Seed-based</B>: Outwards from seed.<BR>"
  161. "<B>Line-based</B>: Parallel lines.")
  162. )
  163. grid3.addWidget(methodlabel, 3, 0)
  164. self.ncc_method_radio = RadioSet([
  165. {"label": _("Standard"), "value": "standard"},
  166. {"label": _("Seed-based"), "value": "seed"},
  167. {"label": _("Straight lines"), "value": "lines"}
  168. ], orientation='vertical', stretch=False)
  169. grid3.addWidget(self.ncc_method_radio, 3, 1)
  170. # Connect lines
  171. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  172. pathconnectlabel.setToolTip(
  173. _("Draw lines between resulting\n"
  174. "segments to minimize tool lifts.")
  175. )
  176. grid3.addWidget(pathconnectlabel, 4, 0)
  177. self.ncc_connect_cb = FCCheckBox()
  178. grid3.addWidget(self.ncc_connect_cb, 4, 1)
  179. contourlabel = QtWidgets.QLabel(_("Contour:"))
  180. contourlabel.setToolTip(
  181. _("Cut around the perimeter of the polygon\n"
  182. "to trim rough edges.")
  183. )
  184. grid3.addWidget(contourlabel, 5, 0)
  185. self.ncc_contour_cb = FCCheckBox()
  186. grid3.addWidget(self.ncc_contour_cb, 5, 1)
  187. restlabel = QtWidgets.QLabel(_("Rest M.:"))
  188. restlabel.setToolTip(
  189. _("If checked, use 'rest machining'.\n"
  190. "Basically it will clear copper outside PCB features,\n"
  191. "using the biggest tool and continue with the next tools,\n"
  192. "from bigger to smaller, to clear areas of copper that\n"
  193. "could not be cleared by previous tool, until there is\n"
  194. "no more copper to clear or there are no more tools.\n"
  195. "If not checked, use the standard algorithm.")
  196. )
  197. grid3.addWidget(restlabel, 6, 0)
  198. self.ncc_rest_cb = FCCheckBox()
  199. grid3.addWidget(self.ncc_rest_cb, 6, 1)
  200. # ## NCC Offset choice
  201. self.ncc_offset_choice_label = QtWidgets.QLabel(_("Offset:"))
  202. self.ncc_offset_choice_label.setToolTip(
  203. _("If used, it will add an offset to the copper features.\n"
  204. "The copper clearing will finish to a distance\n"
  205. "from the copper features.\n"
  206. "The value can be between 0 and 10 FlatCAM units.")
  207. )
  208. grid3.addWidget(self.ncc_offset_choice_label, 7, 0)
  209. self.ncc_choice_offset_cb = FCCheckBox()
  210. grid3.addWidget(self.ncc_choice_offset_cb, 7, 1)
  211. # ## NCC Offset value
  212. self.ncc_offset_label = QtWidgets.QLabel(_("Offset value:"))
  213. self.ncc_offset_label.setToolTip(
  214. _("If used, it will add an offset to the copper features.\n"
  215. "The copper clearing will finish to a distance\n"
  216. "from the copper features.\n"
  217. "The value can be between 0 and 10 FlatCAM units.")
  218. )
  219. grid3.addWidget(self.ncc_offset_label, 8, 0)
  220. self.ncc_offset_spinner = FCDoubleSpinner()
  221. self.ncc_offset_spinner.set_range(0.00, 10.00)
  222. self.ncc_offset_spinner.set_precision(4)
  223. self.ncc_offset_spinner.setWrapping(True)
  224. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  225. if units == 'MM':
  226. self.ncc_offset_spinner.setSingleStep(0.1)
  227. else:
  228. self.ncc_offset_spinner.setSingleStep(0.01)
  229. grid3.addWidget(self.ncc_offset_spinner, 8, 1)
  230. self.ncc_offset_label.hide()
  231. self.ncc_offset_spinner.hide()
  232. # ## Reference
  233. self.reference_radio = RadioSet([{'label': _('Itself'), 'value': 'itself'},
  234. {'label': _('Box'), 'value': 'box'}])
  235. self.reference_label = QtWidgets.QLabel(_("Reference:"))
  236. self.reference_label.setToolTip(
  237. _("- 'Itself': the non copper clearing extent\n"
  238. "is based on the object that is copper cleared.\n "
  239. "- 'Box': will do non copper clearing within the box\n"
  240. "specified by the object selected in the Ref. Object combobox.")
  241. )
  242. grid3.addWidget(self.reference_label, 9, 0)
  243. grid3.addWidget(self.reference_radio, 9, 1)
  244. grid4 = QtWidgets.QGridLayout()
  245. self.tools_box.addLayout(grid4)
  246. self.box_combo_type_label = QtWidgets.QLabel(_("Ref. Type:"))
  247. self.box_combo_type_label.setToolTip(
  248. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  249. "It can be Gerber, Excellon or Geometry.")
  250. )
  251. self.box_combo_type = QtWidgets.QComboBox()
  252. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  253. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  254. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  255. grid4.addWidget(self.box_combo_type_label, 0, 0)
  256. grid4.addWidget(self.box_combo_type, 0, 1)
  257. self.box_combo_label = QtWidgets.QLabel(_("Ref. Object:"))
  258. self.box_combo_label.setToolTip(
  259. _("The FlatCAM object to be used as non copper clearing reference.")
  260. )
  261. self.box_combo = QtWidgets.QComboBox()
  262. self.box_combo.setModel(self.app.collection)
  263. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  264. self.box_combo.setCurrentIndex(1)
  265. grid4.addWidget(self.box_combo_label, 1, 0)
  266. grid4.addWidget(self.box_combo, 1, 1)
  267. self.box_combo.hide()
  268. self.box_combo_label.hide()
  269. self.box_combo_type.hide()
  270. self.box_combo_type_label.hide()
  271. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  272. self.generate_ncc_button.setToolTip(
  273. _("Create the Geometry Object\n"
  274. "for non-copper routing.")
  275. )
  276. self.tools_box.addWidget(self.generate_ncc_button)
  277. self.units = ''
  278. self.ncc_tools = {}
  279. self.tooluid = 0
  280. # store here the default data for Geometry Data
  281. self.default_data = {}
  282. self.obj_name = ""
  283. self.ncc_obj = None
  284. self.bound_obj_name = ""
  285. self.bound_obj = None
  286. self.tools_box.addStretch()
  287. self.addtool_btn.clicked.connect(self.on_tool_add)
  288. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  289. self.deltool_btn.clicked.connect(self.on_tool_delete)
  290. self.generate_ncc_button.clicked.connect(self.on_ncc)
  291. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  292. self.reference_radio.group_toggle_fn = self.on_toggle_reference
  293. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  294. def install(self, icon=None, separator=None, **kwargs):
  295. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  296. def run(self, toggle=True):
  297. self.app.report_usage("ToolNonCopperClear()")
  298. if toggle:
  299. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  300. if self.app.ui.splitter.sizes()[0] == 0:
  301. self.app.ui.splitter.setSizes([1, 1])
  302. else:
  303. try:
  304. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  305. self.app.ui.splitter.setSizes([0, 1])
  306. except AttributeError:
  307. pass
  308. else:
  309. if self.app.ui.splitter.sizes()[0] == 0:
  310. self.app.ui.splitter.setSizes([1, 1])
  311. FlatCAMTool.run(self)
  312. self.set_tool_ui()
  313. # reset those objects on a new run
  314. self.ncc_obj = None
  315. self.bound_obj = None
  316. self.obj_name = ''
  317. self.bound_obj_name = ''
  318. self.build_ui()
  319. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  320. def set_tool_ui(self):
  321. self.tools_frame.show()
  322. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  323. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  324. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  325. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  326. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  327. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  328. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  329. self.tools_table.setupContextMenu()
  330. self.tools_table.addContextMenu(
  331. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  332. self.tools_table.addContextMenu(
  333. "Delete", lambda:
  334. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  335. # init the working variables
  336. self.default_data.clear()
  337. self.default_data.update({
  338. "name": '_ncc',
  339. "plot": self.app.defaults["geometry_plot"],
  340. "cutz": self.app.defaults["geometry_cutz"],
  341. "vtipdia": 0.1,
  342. "vtipangle": 30,
  343. "travelz": self.app.defaults["geometry_travelz"],
  344. "feedrate": self.app.defaults["geometry_feedrate"],
  345. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  346. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  347. "dwell": self.app.defaults["geometry_dwell"],
  348. "dwelltime": self.app.defaults["geometry_dwelltime"],
  349. "multidepth": self.app.defaults["geometry_multidepth"],
  350. "ppname_g": self.app.defaults["geometry_ppname_g"],
  351. "depthperpass": self.app.defaults["geometry_depthperpass"],
  352. "extracut": self.app.defaults["geometry_extracut"],
  353. "toolchange": self.app.defaults["geometry_toolchange"],
  354. "toolchangez": self.app.defaults["geometry_toolchangez"],
  355. "endz": self.app.defaults["geometry_endz"],
  356. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  357. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  358. "startz": self.app.defaults["geometry_startz"],
  359. "tooldia": self.app.defaults["tools_painttooldia"],
  360. "paintmargin": self.app.defaults["tools_paintmargin"],
  361. "paintmethod": self.app.defaults["tools_paintmethod"],
  362. "selectmethod": self.app.defaults["tools_selectmethod"],
  363. "pathconnect": self.app.defaults["tools_pathconnect"],
  364. "paintcontour": self.app.defaults["tools_paintcontour"],
  365. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  366. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  367. "nccmargin": self.app.defaults["tools_nccmargin"],
  368. "nccmethod": self.app.defaults["tools_nccmethod"],
  369. "nccconnect": self.app.defaults["tools_nccconnect"],
  370. "ncccontour": self.app.defaults["tools_ncccontour"],
  371. "nccrest": self.app.defaults["tools_nccrest"]
  372. })
  373. try:
  374. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  375. except Exception as e:
  376. log.error("At least one tool diameter needed. "
  377. "Verify in Edit -> Preferences -> TOOLS -> NCC Tools. %s" % str(e))
  378. return
  379. self.tooluid = 0
  380. self.ncc_tools.clear()
  381. for tool_dia in dias:
  382. self.tooluid += 1
  383. self.ncc_tools.update({
  384. int(self.tooluid): {
  385. 'tooldia': float('%.4f' % tool_dia),
  386. 'offset': 'Path',
  387. 'offset_value': 0.0,
  388. 'type': 'Iso',
  389. 'tool_type': 'V',
  390. 'data': dict(self.default_data),
  391. 'solid_geometry': []
  392. }
  393. })
  394. self.obj_name = ""
  395. self.ncc_obj = None
  396. self.bound_obj_name = ""
  397. self.bound_obj = None
  398. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  399. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  400. def build_ui(self):
  401. self.ui_disconnect()
  402. # updated units
  403. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  404. if self.units == "IN":
  405. self.addtool_entry.set_value(0.039)
  406. else:
  407. self.addtool_entry.set_value(1)
  408. sorted_tools = []
  409. for k, v in self.ncc_tools.items():
  410. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  411. sorted_tools.sort()
  412. n = len(sorted_tools)
  413. self.tools_table.setRowCount(n)
  414. tool_id = 0
  415. for tool_sorted in sorted_tools:
  416. for tooluid_key, tooluid_value in self.ncc_tools.items():
  417. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  418. tool_id += 1
  419. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  420. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  421. row_no = tool_id - 1
  422. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  423. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  424. # There are no drill bits in MM with more than 3 decimals diameter
  425. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  426. if self.units == 'MM':
  427. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  428. else:
  429. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  430. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  431. tool_type_item = QtWidgets.QComboBox()
  432. for item in self.tool_type_item_options:
  433. tool_type_item.addItem(item)
  434. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  435. idx = tool_type_item.findText(tooluid_value['tool_type'])
  436. tool_type_item.setCurrentIndex(idx)
  437. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  438. self.tools_table.setItem(row_no, 1, dia) # Diameter
  439. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  440. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  441. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  442. # make the diameter column editable
  443. for row in range(tool_id):
  444. self.tools_table.item(row, 1).setFlags(
  445. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  446. # all the tools are selected by default
  447. self.tools_table.selectColumn(0)
  448. #
  449. self.tools_table.resizeColumnsToContents()
  450. self.tools_table.resizeRowsToContents()
  451. vertical_header = self.tools_table.verticalHeader()
  452. vertical_header.hide()
  453. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  454. horizontal_header = self.tools_table.horizontalHeader()
  455. horizontal_header.setMinimumSectionSize(10)
  456. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  457. horizontal_header.resizeSection(0, 20)
  458. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  459. # self.tools_table.setSortingEnabled(True)
  460. # sort by tool diameter
  461. # self.tools_table.sortItems(1)
  462. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  463. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  464. self.ui_connect()
  465. def ui_connect(self):
  466. self.tools_table.itemChanged.connect(self.on_tool_edit)
  467. def ui_disconnect(self):
  468. try:
  469. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  470. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  471. except (TypeError, AttributeError):
  472. pass
  473. def on_combo_box_type(self):
  474. obj_type = self.box_combo_type.currentIndex()
  475. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  476. self.box_combo.setCurrentIndex(0)
  477. def on_toggle_reference(self):
  478. if self.reference_radio.get_value() == "itself":
  479. self.box_combo.hide()
  480. self.box_combo_label.hide()
  481. self.box_combo_type.hide()
  482. self.box_combo_type_label.hide()
  483. else:
  484. self.box_combo.show()
  485. self.box_combo_label.show()
  486. self.box_combo_type.show()
  487. self.box_combo_type_label.show()
  488. def on_offset_choice(self, state):
  489. if state:
  490. self.ncc_offset_label.show()
  491. self.ncc_offset_spinner.show()
  492. else:
  493. self.ncc_offset_label.hide()
  494. self.ncc_offset_spinner.hide()
  495. def on_tool_add(self, dia=None, muted=None):
  496. self.ui_disconnect()
  497. if dia:
  498. tool_dia = dia
  499. else:
  500. try:
  501. tool_dia = float(self.addtool_entry.get_value())
  502. except ValueError:
  503. # try to convert comma to decimal point. if it's still not working error message and return
  504. try:
  505. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  506. except ValueError:
  507. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  508. "use a number."))
  509. return
  510. if tool_dia is None:
  511. self.build_ui()
  512. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  513. return
  514. if tool_dia == 0:
  515. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, "
  516. "in Float format."))
  517. return
  518. # construct a list of all 'tooluid' in the self.tools
  519. tool_uid_list = []
  520. for tooluid_key in self.ncc_tools:
  521. tool_uid_item = int(tooluid_key)
  522. tool_uid_list.append(tool_uid_item)
  523. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  524. if not tool_uid_list:
  525. max_uid = 0
  526. else:
  527. max_uid = max(tool_uid_list)
  528. self.tooluid = int(max_uid + 1)
  529. tool_dias = []
  530. for k, v in self.ncc_tools.items():
  531. for tool_v in v.keys():
  532. if tool_v == 'tooldia':
  533. tool_dias.append(float('%.4f' % v[tool_v]))
  534. if float('%.4f' % tool_dia) in tool_dias:
  535. if muted is None:
  536. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  537. self.tools_table.itemChanged.connect(self.on_tool_edit)
  538. return
  539. else:
  540. if muted is None:
  541. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  542. self.ncc_tools.update({
  543. int(self.tooluid): {
  544. 'tooldia': float('%.4f' % tool_dia),
  545. 'offset': 'Path',
  546. 'offset_value': 0.0,
  547. 'type': 'Iso',
  548. 'tool_type': 'V',
  549. 'data': dict(self.default_data),
  550. 'solid_geometry': []
  551. }
  552. })
  553. self.build_ui()
  554. def on_tool_edit(self):
  555. self.ui_disconnect()
  556. tool_dias = []
  557. for k, v in self.ncc_tools.items():
  558. for tool_v in v.keys():
  559. if tool_v == 'tooldia':
  560. tool_dias.append(float('%.4f' % v[tool_v]))
  561. for row in range(self.tools_table.rowCount()):
  562. try:
  563. new_tool_dia = float(self.tools_table.item(row, 1).text())
  564. except ValueError:
  565. # try to convert comma to decimal point. if it's still not working error message and return
  566. try:
  567. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  568. except ValueError:
  569. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  570. "use a number."))
  571. return
  572. tooluid = int(self.tools_table.item(row, 3).text())
  573. # identify the tool that was edited and get it's tooluid
  574. if new_tool_dia not in tool_dias:
  575. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  576. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  577. self.build_ui()
  578. return
  579. else:
  580. # identify the old tool_dia and restore the text in tool table
  581. for k, v in self.ncc_tools.items():
  582. if k == tooluid:
  583. old_tool_dia = v['tooldia']
  584. break
  585. restore_dia_item = self.tools_table.item(row, 1)
  586. restore_dia_item.setText(str(old_tool_dia))
  587. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  588. "New diameter value is already in the Tool Table."))
  589. self.build_ui()
  590. def on_tool_delete(self, rows_to_delete=None, all=None):
  591. self.ui_disconnect()
  592. deleted_tools_list = []
  593. if all:
  594. self.paint_tools.clear()
  595. self.build_ui()
  596. return
  597. if rows_to_delete:
  598. try:
  599. for row in rows_to_delete:
  600. tooluid_del = int(self.tools_table.item(row, 3).text())
  601. deleted_tools_list.append(tooluid_del)
  602. except TypeError:
  603. deleted_tools_list.append(rows_to_delete)
  604. for t in deleted_tools_list:
  605. self.ncc_tools.pop(t, None)
  606. self.build_ui()
  607. return
  608. try:
  609. if self.tools_table.selectedItems():
  610. for row_sel in self.tools_table.selectedItems():
  611. row = row_sel.row()
  612. if row < 0:
  613. continue
  614. tooluid_del = int(self.tools_table.item(row, 3).text())
  615. deleted_tools_list.append(tooluid_del)
  616. for t in deleted_tools_list:
  617. self.ncc_tools.pop(t, None)
  618. except AttributeError:
  619. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  620. return
  621. except Exception as e:
  622. log.debug(str(e))
  623. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  624. self.build_ui()
  625. def on_ncc(self):
  626. self.bound_obj = None
  627. self.ncc_obj = None
  628. try:
  629. over = float(self.ncc_overlap_entry.get_value())
  630. except ValueError:
  631. # try to convert comma to decimal point. if it's still not working error message and return
  632. try:
  633. over = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  634. except ValueError:
  635. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  636. "use a number."))
  637. return
  638. over = over if over else self.app.defaults["tools_nccoverlap"]
  639. if over >= 1 or over < 0:
  640. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  641. "0 (inclusive) and 1 (exclusive), "))
  642. return
  643. try:
  644. margin = float(self.ncc_margin_entry.get_value())
  645. except ValueError:
  646. # try to convert comma to decimal point. if it's still not working error message and return
  647. try:
  648. margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  649. except ValueError:
  650. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  651. "use a number."))
  652. return
  653. margin = margin if margin is not None else float(self.app.defaults["tools_nccmargin"])
  654. try:
  655. ncc_offset_value = float(self.ncc_offset_spinner.get_value())
  656. except ValueError:
  657. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  658. "use a number."))
  659. return
  660. ncc_offset_value = ncc_offset_value if ncc_offset_value is not None \
  661. else float(self.app.defaults["tools_ncc_offset_value"])
  662. connect = self.ncc_connect_cb.get_value()
  663. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  664. contour = self.ncc_contour_cb.get_value()
  665. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  666. clearing_method = self.ncc_rest_cb.get_value()
  667. clearing_method = clearing_method if clearing_method else self.app.defaults["tools_nccrest"]
  668. pol_method = self.ncc_method_radio.get_value()
  669. pol_method = pol_method if pol_method else self.app.defaults["tools_nccmethod"]
  670. if self.reference_radio.get_value() == 'itself':
  671. self.bound_obj_name = self.object_combo.currentText()
  672. # Get source object.
  673. try:
  674. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  675. except Exception as e:
  676. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  677. return "Could not retrieve object: %s" % self.obj_name
  678. else:
  679. self.bound_obj_name = self.box_combo.currentText()
  680. # Get source object.
  681. try:
  682. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  683. except Exception as e:
  684. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  685. return "Could not retrieve object: %s" % self.obj_name
  686. self.obj_name = self.object_combo.currentText()
  687. # Get source object.
  688. try:
  689. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  690. except Exception as e:
  691. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  692. return "Could not retrieve object: %s" % self.obj_name
  693. # Prepare non-copper polygons
  694. try:
  695. if not isinstance(self.bound_obj.solid_geometry, MultiPolygon):
  696. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  697. env_obj = env_obj.convex_hull
  698. else:
  699. env_obj = self.bound_obj.solid_geometry.convex_hull
  700. bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  701. except Exception as e:
  702. log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  703. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  704. return
  705. # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  706. if self.ncc_choice_offset_cb.isChecked():
  707. self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  708. offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  709. self.app.inform.emit(_("[success] Buffering finished ..."))
  710. empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  711. else:
  712. empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  713. if type(empty) is Polygon:
  714. empty = MultiPolygon([empty])
  715. if empty.is_empty:
  716. self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  717. return
  718. # clear non copper using standard algorithm
  719. if clearing_method is False:
  720. self.clear_non_copper(
  721. empty=empty,
  722. over=over,
  723. pol_method=pol_method,
  724. connect=connect,
  725. contour=contour
  726. )
  727. # clear non copper using rest machining algorithm
  728. else:
  729. self.clear_non_copper_rest(
  730. empty=empty,
  731. over=over,
  732. pol_method=pol_method,
  733. connect=connect,
  734. contour=contour
  735. )
  736. def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  737. name = outname if outname else self.obj_name + "_ncc"
  738. # Sort tools in descending order
  739. sorted_tools = []
  740. for k, v in self.ncc_tools.items():
  741. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  742. sorted_tools.sort(reverse=True)
  743. # Do job in background
  744. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  745. def initialize(geo_obj, app_obj):
  746. assert isinstance(geo_obj, FlatCAMGeometry), \
  747. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  748. cleared_geo = []
  749. # Already cleared area
  750. cleared = MultiPolygon()
  751. # flag for polygons not cleared
  752. app_obj.poly_not_cleared = False
  753. # Generate area for each tool
  754. offset = sum(sorted_tools)
  755. current_uid = int(1)
  756. for tool in sorted_tools:
  757. self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  758. cleared_geo[:] = []
  759. # Get remaining tools offset
  760. offset -= (tool - 1e-12)
  761. # Area to clear
  762. area = empty.buffer(-offset)
  763. try:
  764. area = area.difference(cleared)
  765. except Exception as e:
  766. continue
  767. # Transform area to MultiPolygon
  768. if type(area) is Polygon:
  769. area = MultiPolygon([area])
  770. if area.geoms:
  771. if len(area.geoms) > 0:
  772. for p in area.geoms:
  773. try:
  774. if pol_method == 'standard':
  775. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  776. overlap=over, contour=contour, connect=connect)
  777. elif pol_method == 'seed':
  778. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  779. overlap=over, contour=contour, connect=connect)
  780. else:
  781. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  782. overlap=over, contour=contour, connect=connect)
  783. if cp:
  784. cleared_geo += list(cp.get_objects())
  785. except Exception as e:
  786. log.warning("Polygon can not be cleared. %s" % str(e))
  787. app_obj.poly_not_cleared = True
  788. continue
  789. # check if there is a geometry at all in the cleared geometry
  790. if cleared_geo:
  791. # Overall cleared area
  792. cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  793. tool / 1.999999)
  794. # clean-up cleared geo
  795. cleared = cleared.buffer(0)
  796. # find the tooluid associated with the current tool_dia so we know where to add the tool
  797. # solid_geometry
  798. for k, v in self.ncc_tools.items():
  799. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  800. current_uid = int(k)
  801. # add the solid_geometry to the current too in self.paint_tools dictionary
  802. # and then reset the temporary list that stored that solid_geometry
  803. v['solid_geometry'] = deepcopy(cleared_geo)
  804. v['data']['name'] = name
  805. break
  806. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  807. else:
  808. log.debug("There are no geometries in the cleared polygon.")
  809. geo_obj.options["cnctooldia"] = str(tool)
  810. geo_obj.multigeo = True
  811. def job_thread(app_obj):
  812. try:
  813. app_obj.new_object("geometry", name, initialize)
  814. except Exception as e:
  815. proc.done()
  816. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  817. return
  818. proc.done()
  819. if app_obj.poly_not_cleared is False:
  820. self.app.inform.emit(_('[success] NCC Tool finished.'))
  821. else:
  822. self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  823. 'Check the result.'))
  824. # reset the variable for next use
  825. app_obj.poly_not_cleared = False
  826. # focus on Selected Tab
  827. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  828. self.tools_frame.hide()
  829. self.app.ui.notebook.setTabText(2, _("Tools"))
  830. # Promise object with the new name
  831. self.app.collection.promise(name)
  832. # Background
  833. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  834. # clear copper with 'rest-machining' algorithm
  835. def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  836. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  837. # Sort tools in descending order
  838. sorted_tools = []
  839. for k, v in self.ncc_tools.items():
  840. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  841. sorted_tools.sort(reverse=True)
  842. # Do job in background
  843. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  844. def initialize_rm(geo_obj, app_obj):
  845. assert isinstance(geo_obj, FlatCAMGeometry), \
  846. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  847. cleared_geo = []
  848. cleared_by_last_tool = []
  849. rest_geo = []
  850. current_uid = 1
  851. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  852. app_obj.poly_not_cleared = True
  853. area = empty.buffer(0)
  854. # Generate area for each tool
  855. while sorted_tools:
  856. tool = sorted_tools.pop(0)
  857. self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  858. tool_used = tool - 1e-12
  859. cleared_geo[:] = []
  860. # Area to clear
  861. for poly in cleared_by_last_tool:
  862. try:
  863. area = area.difference(poly)
  864. except Exception as e:
  865. pass
  866. cleared_by_last_tool[:] = []
  867. # Transform area to MultiPolygon
  868. if type(area) is Polygon:
  869. area = MultiPolygon([area])
  870. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  871. # and rest_geo it's a list
  872. allparts = [p.buffer(0) for p in area.geoms]
  873. allparts += deepcopy(rest_geo)
  874. rest_geo[:] = []
  875. area = MultiPolygon(deepcopy(allparts))
  876. allparts[:] = []
  877. if area.geoms:
  878. if len(area.geoms) > 0:
  879. for p in area.geoms:
  880. try:
  881. if pol_method == 'standard':
  882. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  883. overlap=over, contour=contour, connect=connect)
  884. elif pol_method == 'seed':
  885. cp = self.clear_polygon2(p, tool_used,
  886. self.app.defaults["gerber_circle_steps"],
  887. overlap=over, contour=contour, connect=connect)
  888. else:
  889. cp = self.clear_polygon3(p, tool_used,
  890. self.app.defaults["gerber_circle_steps"],
  891. overlap=over, contour=contour, connect=connect)
  892. cleared_geo.append(list(cp.get_objects()))
  893. except:
  894. log.warning("Polygon can't be cleared.")
  895. # this polygon should be added to a list and then try clear it with a smaller tool
  896. rest_geo.append(p)
  897. # check if there is a geometry at all in the cleared geometry
  898. if cleared_geo:
  899. # Overall cleared area
  900. cleared_area = list(self.flatten_list(cleared_geo))
  901. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  902. # for p in cleared_area])
  903. # here we store the poly's already processed in the original geometry by the current tool
  904. # into cleared_by_last_tool list
  905. # this will be sustracted from the original geometry_to_be_cleared and make data for
  906. # the next tool
  907. buffer_value = tool_used / 2
  908. for p in cleared_area:
  909. poly = p.buffer(buffer_value)
  910. cleared_by_last_tool.append(poly)
  911. # find the tooluid associated with the current tool_dia so we know
  912. # where to add the tool solid_geometry
  913. for k, v in self.ncc_tools.items():
  914. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  915. current_uid = int(k)
  916. # add the solid_geometry to the current too in self.paint_tools dictionary
  917. # and then reset the temporary list that stored that solid_geometry
  918. v['solid_geometry'] = deepcopy(cleared_area)
  919. v['data']['name'] = name
  920. cleared_area[:] = []
  921. break
  922. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  923. else:
  924. log.debug("There are no geometries in the cleared polygon.")
  925. geo_obj.multigeo = True
  926. geo_obj.options["cnctooldia"] = str(tool)
  927. # check to see if geo_obj.tools is empty
  928. # it will be updated only if there is a solid_geometry for tools
  929. if geo_obj.tools:
  930. return
  931. else:
  932. # I will use this variable for this purpose although it was meant for something else
  933. # signal that we have no geo in the object therefore don't create it
  934. app_obj.poly_not_cleared = False
  935. return "fail"
  936. def job_thread(app_obj):
  937. try:
  938. app_obj.new_object("geometry", name, initialize_rm)
  939. except Exception as e:
  940. proc.done()
  941. app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  942. return
  943. if app_obj.poly_not_cleared is True:
  944. app_obj.inform.emit('[success] NCC Tool finished.')
  945. # focus on Selected Tab
  946. app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  947. else:
  948. app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  949. 'with current settings.'))
  950. # focus on Project Tab
  951. app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  952. proc.done()
  953. # reset the variable for next use
  954. app_obj.poly_not_cleared = False
  955. self.tools_frame.hide()
  956. app_obj.ui.notebook.setTabText(2, "Tools")
  957. # Promise object with the new name
  958. self.app.collection.promise(name)
  959. # Background
  960. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  961. @staticmethod
  962. def get_ncc_empty_area(target, boundary=None):
  963. """
  964. Returns the complement of target geometry within
  965. the given boundary polygon. If not specified, it defaults to
  966. the rectangular bounding box of target geometry.
  967. """
  968. if boundary is None:
  969. boundary = target.envelope
  970. return boundary.difference(target)
  971. def reset_fields(self):
  972. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))