ToolPaint.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. from FlatCAMTool import FlatCAMTool
  2. from copy import copy,deepcopy
  3. from ObjectCollection import *
  4. class ToolPaint(FlatCAMTool, Gerber):
  5. toolName = "Paint Area"
  6. def __init__(self, app):
  7. self.app = app
  8. FlatCAMTool.__init__(self, app)
  9. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  10. ## Title
  11. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % self.toolName)
  12. self.layout.addWidget(title_label)
  13. self.tools_frame = QtWidgets.QFrame()
  14. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  15. self.layout.addWidget(self.tools_frame)
  16. self.tools_box = QtWidgets.QVBoxLayout()
  17. self.tools_box.setContentsMargins(0, 0, 0, 0)
  18. self.tools_frame.setLayout(self.tools_box)
  19. ## Form Layout
  20. form_layout = QtWidgets.QFormLayout()
  21. self.tools_box.addLayout(form_layout)
  22. ## Object
  23. self.object_combo = QtWidgets.QComboBox()
  24. self.object_combo.setModel(self.app.collection)
  25. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  26. self.object_combo.setCurrentIndex(1)
  27. self.object_label = QtWidgets.QLabel("Geometry:")
  28. self.object_label.setToolTip(
  29. "Geometry object to be painted. "
  30. )
  31. e_lab_0 = QtWidgets.QLabel('')
  32. form_layout.addRow(self.object_label, self.object_combo)
  33. form_layout.addRow(e_lab_0)
  34. #### Tools ####
  35. self.tools_table_label = QtWidgets.QLabel('<b>Tools Table</b>')
  36. self.tools_table_label.setToolTip(
  37. "Tools pool from which the algorithm\n"
  38. "will pick the ones used for painting."
  39. )
  40. self.tools_box.addWidget(self.tools_table_label)
  41. self.tools_table = FCTable()
  42. self.tools_box.addWidget(self.tools_table)
  43. self.tools_table.setColumnCount(4)
  44. self.tools_table.setHorizontalHeaderLabels(['#', 'Diameter', 'TT', ''])
  45. self.tools_table.setColumnHidden(3, True)
  46. # self.tools_table.setSortingEnabled(False)
  47. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  48. self.tools_table.horizontalHeaderItem(0).setToolTip(
  49. "This is the Tool Number.\n"
  50. "Painting will start with the tool with the biggest diameter,\n"
  51. "continuing until there are no more tools.\n"
  52. "Only tools that create painting geometry will still be present\n"
  53. "in the resulting geometry. This is because with some tools\n"
  54. "this function will not be able to create painting geometry."
  55. )
  56. self.tools_table.horizontalHeaderItem(1).setToolTip(
  57. "Tool Diameter. It's value (in current FlatCAM units) \n"
  58. "is the cut width into the material.")
  59. self.tools_table.horizontalHeaderItem(2).setToolTip(
  60. "The Tool Type (TT) can be:<BR>"
  61. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  62. "the cut width in material is exactly the tool diameter.<BR>"
  63. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  64. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  65. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  66. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  67. "as the cut width into material will be equal with the value in the Tool Diameter "
  68. "column of this table.<BR>"
  69. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  70. "in the resulting geometry as Isolation.")
  71. self.empty_label = QtWidgets.QLabel('')
  72. self.tools_box.addWidget(self.empty_label)
  73. #### Add a new Tool ####
  74. hlay = QtWidgets.QHBoxLayout()
  75. self.tools_box.addLayout(hlay)
  76. self.addtool_entry_lbl = QtWidgets.QLabel('<b>Tool Dia:</b>')
  77. self.addtool_entry_lbl.setToolTip(
  78. "Diameter for the new tool."
  79. )
  80. self.addtool_entry = FCEntry()
  81. # hlay.addWidget(self.addtool_label)
  82. # hlay.addStretch()
  83. hlay.addWidget(self.addtool_entry_lbl)
  84. hlay.addWidget(self.addtool_entry)
  85. grid2 = QtWidgets.QGridLayout()
  86. self.tools_box.addLayout(grid2)
  87. self.addtool_btn = QtWidgets.QPushButton('Add')
  88. self.addtool_btn.setToolTip(
  89. "Add a new tool to the Tool Table\n"
  90. "with the diameter specified above."
  91. )
  92. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  93. # self.copytool_btn.setToolTip(
  94. # "Copy a selection of tools in the Tool Table\n"
  95. # "by first selecting a row in the Tool Table."
  96. # )
  97. self.deltool_btn = QtWidgets.QPushButton('Delete')
  98. self.deltool_btn.setToolTip(
  99. "Delete a selection of tools in the Tool Table\n"
  100. "by first selecting a row(s) in the Tool Table."
  101. )
  102. grid2.addWidget(self.addtool_btn, 0, 0)
  103. # grid2.addWidget(self.copytool_btn, 0, 1)
  104. grid2.addWidget(self.deltool_btn, 0,2)
  105. self.empty_label_0 = QtWidgets.QLabel('')
  106. self.tools_box.addWidget(self.empty_label_0)
  107. grid3 = QtWidgets.QGridLayout()
  108. self.tools_box.addLayout(grid3)
  109. # Overlap
  110. ovlabel = QtWidgets.QLabel('Overlap:')
  111. ovlabel.setToolTip(
  112. "How much (fraction) of the tool width to overlap each tool pass.\n"
  113. "Example:\n"
  114. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  115. "Adjust the value starting with lower values\n"
  116. "and increasing it if areas that should be painted are still \n"
  117. "not painted.\n"
  118. "Lower values = faster processing, faster execution on PCB.\n"
  119. "Higher values = slow processing and slow execution on CNC\n"
  120. "due of too many paths."
  121. )
  122. grid3.addWidget(ovlabel, 1, 0)
  123. self.paintoverlap_entry = FCEntry()
  124. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  125. # Margin
  126. marginlabel = QtWidgets.QLabel('Margin:')
  127. marginlabel.setToolTip(
  128. "Distance by which to avoid\n"
  129. "the edges of the polygon to\n"
  130. "be painted."
  131. )
  132. grid3.addWidget(marginlabel, 2, 0)
  133. self.paintmargin_entry = FCEntry()
  134. grid3.addWidget(self.paintmargin_entry, 2, 1)
  135. # Method
  136. methodlabel = QtWidgets.QLabel('Method:')
  137. methodlabel.setToolTip(
  138. "Algorithm for non-copper clearing:<BR>"
  139. "<B>Standard</B>: Fixed step inwards.<BR>"
  140. "<B>Seed-based</B>: Outwards from seed.<BR>"
  141. "<B>Line-based</B>: Parallel lines."
  142. )
  143. grid3.addWidget(methodlabel, 3, 0)
  144. self.paintmethod_combo = RadioSet([
  145. {"label": "Standard", "value": "standard"},
  146. {"label": "Seed-based", "value": "seed"},
  147. {"label": "Straight lines", "value": "lines"}
  148. ], orientation='vertical', stretch=False)
  149. grid3.addWidget(self.paintmethod_combo, 3, 1)
  150. # Connect lines
  151. pathconnectlabel = QtWidgets.QLabel("Connect:")
  152. pathconnectlabel.setToolTip(
  153. "Draw lines between resulting\n"
  154. "segments to minimize tool lifts."
  155. )
  156. grid3.addWidget(pathconnectlabel, 4, 0)
  157. self.pathconnect_cb = FCCheckBox()
  158. grid3.addWidget(self.pathconnect_cb, 4, 1)
  159. contourlabel = QtWidgets.QLabel("Contour:")
  160. contourlabel.setToolTip(
  161. "Cut around the perimeter of the polygon\n"
  162. "to trim rough edges."
  163. )
  164. grid3.addWidget(contourlabel, 5, 0)
  165. self.paintcontour_cb = FCCheckBox()
  166. grid3.addWidget(self.paintcontour_cb, 5, 1)
  167. restlabel = QtWidgets.QLabel("Rest M.:")
  168. restlabel.setToolTip(
  169. "If checked, use 'rest machining'.\n"
  170. "Basically it will clear copper outside PCB features,\n"
  171. "using the biggest tool and continue with the next tools,\n"
  172. "from bigger to smaller, to clear areas of copper that\n"
  173. "could not be cleared by previous tool, until there is\n"
  174. "no more copper to clear or there are no more tools.\n\n"
  175. "If not checked, use the standard algorithm."
  176. )
  177. grid3.addWidget(restlabel, 6, 0)
  178. self.rest_cb = FCCheckBox()
  179. grid3.addWidget(self.rest_cb, 6, 1)
  180. # Polygon selection
  181. selectlabel = QtWidgets.QLabel('Selection:')
  182. selectlabel.setToolTip(
  183. "How to select the polygons to paint.<BR>"
  184. "Options:<BR>"
  185. "- <B>Single</B>: left mouse click on the polygon to be painted.<BR>"
  186. "- <B>All</B>: paint all polygons."
  187. )
  188. grid3.addWidget(selectlabel, 7, 0)
  189. # grid3 = QtWidgets.QGridLayout()
  190. self.selectmethod_combo = RadioSet([
  191. {"label": "Single", "value": "single"},
  192. {"label": "All", "value": "all"},
  193. # {"label": "Rectangle", "value": "rectangle"}
  194. ])
  195. grid3.addWidget(self.selectmethod_combo, 7, 1)
  196. # GO Button
  197. self.generate_paint_button = QtWidgets.QPushButton('Create Paint Geometry')
  198. self.generate_paint_button.setToolTip(
  199. "After clicking here, click inside<BR>"
  200. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  201. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  202. "A new Geometry object with the tool<BR>"
  203. "paths will be created."
  204. )
  205. self.tools_box.addWidget(self.generate_paint_button)
  206. self.tools_box.addStretch()
  207. self.obj_name = ""
  208. self.paint_obj = None
  209. self.units = ''
  210. self.paint_tools = {}
  211. self.tooluid = 0
  212. # store here the default data for Geometry Data
  213. self.default_data = {}
  214. self.default_data.update({
  215. "name": '_paint',
  216. "plot": self.app.defaults["geometry_plot"],
  217. "cutz": self.app.defaults["geometry_cutz"],
  218. "vtipdia": 0.1,
  219. "vtipangle": 30,
  220. "travelz": self.app.defaults["geometry_travelz"],
  221. "feedrate": self.app.defaults["geometry_feedrate"],
  222. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  223. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  224. "dwell": self.app.defaults["geometry_dwell"],
  225. "dwelltime": self.app.defaults["geometry_dwelltime"],
  226. "multidepth": self.app.defaults["geometry_multidepth"],
  227. "ppname_g": self.app.defaults["geometry_ppname_g"],
  228. "depthperpass": self.app.defaults["geometry_depthperpass"],
  229. "extracut": self.app.defaults["geometry_extracut"],
  230. "toolchange": self.app.defaults["geometry_toolchange"],
  231. "toolchangez": self.app.defaults["geometry_toolchangez"],
  232. "endz": self.app.defaults["geometry_endz"],
  233. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  234. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  235. "startz": self.app.defaults["geometry_startz"],
  236. "tooldia": self.app.defaults["tools_painttooldia"],
  237. "paintmargin": self.app.defaults["tools_paintmargin"],
  238. "paintmethod": self.app.defaults["tools_paintmethod"],
  239. "selectmethod": self.app.defaults["tools_selectmethod"],
  240. "pathconnect": self.app.defaults["tools_pathconnect"],
  241. "paintcontour": self.app.defaults["tools_paintcontour"],
  242. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  243. })
  244. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  245. ## Signals
  246. self.addtool_btn.clicked.connect(self.on_tool_add)
  247. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  248. self.tools_table.itemChanged.connect(self.on_tool_edit)
  249. self.deltool_btn.clicked.connect(self.on_tool_delete)
  250. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  251. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  252. def install(self, icon=None, separator=None, **kwargs):
  253. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  254. def run(self):
  255. self.app.report_usage("ToolPaint()")
  256. FlatCAMTool.run(self)
  257. self.set_tool_ui()
  258. self.app.ui.notebook.setTabText(2, "Paint Tool")
  259. def on_radio_selection(self):
  260. if self.selectmethod_combo.get_value() == 'single':
  261. # disable rest-machining for single polygon painting
  262. self.rest_cb.set_value(False)
  263. self.rest_cb.setDisabled(True)
  264. # delete all tools except first row / tool for single polygon painting
  265. list_to_del = list(range(1, self.tools_table.rowCount()))
  266. if list_to_del:
  267. self.on_tool_delete(rows_to_delete=list_to_del)
  268. # disable addTool and delTool
  269. self.addtool_entry.setDisabled(True)
  270. self.addtool_btn.setDisabled(True)
  271. self.deltool_btn.setDisabled(True)
  272. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  273. else:
  274. self.rest_cb.setDisabled(False)
  275. self.addtool_entry.setDisabled(False)
  276. self.addtool_btn.setDisabled(False)
  277. self.deltool_btn.setDisabled(False)
  278. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  279. def set_tool_ui(self):
  280. self.tools_frame.show()
  281. self.reset_fields()
  282. ## Init the GUI interface
  283. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  284. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  285. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  286. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  287. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  288. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  289. # updated units
  290. self.units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  291. if self.units == "IN":
  292. self.addtool_entry.set_value(0.039)
  293. else:
  294. self.addtool_entry.set_value(1)
  295. self.tools_table.setupContextMenu()
  296. self.tools_table.addContextMenu(
  297. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  298. self.tools_table.addContextMenu(
  299. "Delete", lambda:
  300. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  301. # set the working variables to a known state
  302. self.paint_tools.clear()
  303. self.tooluid = 0
  304. self.default_data.clear()
  305. self.default_data.update({
  306. "name": '_paint',
  307. "plot": self.app.defaults["geometry_plot"],
  308. "cutz": self.app.defaults["geometry_cutz"],
  309. "vtipdia": 0.1,
  310. "vtipangle": 30,
  311. "travelz": self.app.defaults["geometry_travelz"],
  312. "feedrate": self.app.defaults["geometry_feedrate"],
  313. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  314. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  315. "dwell": self.app.defaults["geometry_dwell"],
  316. "dwelltime": self.app.defaults["geometry_dwelltime"],
  317. "multidepth": self.app.defaults["geometry_multidepth"],
  318. "ppname_g": self.app.defaults["geometry_ppname_g"],
  319. "depthperpass": self.app.defaults["geometry_depthperpass"],
  320. "extracut": self.app.defaults["geometry_extracut"],
  321. "toolchange": self.app.defaults["geometry_toolchange"],
  322. "toolchangez": self.app.defaults["geometry_toolchangez"],
  323. "endz": self.app.defaults["geometry_endz"],
  324. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  325. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  326. "startz": self.app.defaults["geometry_startz"],
  327. "tooldia": self.app.defaults["tools_painttooldia"],
  328. "paintmargin": self.app.defaults["tools_paintmargin"],
  329. "paintmethod": self.app.defaults["tools_paintmethod"],
  330. "selectmethod": self.app.defaults["tools_selectmethod"],
  331. "pathconnect": self.app.defaults["tools_pathconnect"],
  332. "paintcontour": self.app.defaults["tools_paintcontour"],
  333. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  334. })
  335. # call on self.on_tool_add() counts as an call to self.build_ui()
  336. # through this, we add a initial row / tool in the tool_table
  337. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  338. # if the Paint Method is "Single" disable the tool table context menu
  339. if self.default_data["selectmethod"] == "single":
  340. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  341. def build_ui(self):
  342. try:
  343. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  344. self.tools_table.itemChanged.disconnect()
  345. except:
  346. pass
  347. # updated units
  348. self.units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  349. sorted_tools = []
  350. for k, v in self.paint_tools.items():
  351. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  352. sorted_tools.sort()
  353. n = len(sorted_tools)
  354. self.tools_table.setRowCount(n)
  355. tool_id = 0
  356. for tool_sorted in sorted_tools:
  357. for tooluid_key, tooluid_value in self.paint_tools.items():
  358. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  359. tool_id += 1
  360. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  361. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  362. row_no = tool_id - 1
  363. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  364. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  365. # There are no drill bits in MM with more than 3 decimals diameter
  366. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  367. if self.units == 'MM':
  368. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  369. else:
  370. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  371. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  372. tool_type_item = QtWidgets.QComboBox()
  373. for item in self.tool_type_item_options:
  374. tool_type_item.addItem(item)
  375. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  376. idx = tool_type_item.findText(tooluid_value['tool_type'])
  377. tool_type_item.setCurrentIndex(idx)
  378. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  379. self.tools_table.setItem(row_no, 1, dia) # Diameter
  380. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  381. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  382. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  383. # make the diameter column editable
  384. for row in range(tool_id):
  385. self.tools_table.item(row, 1).setFlags(
  386. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  387. # all the tools are selected by default
  388. self.tools_table.selectColumn(0)
  389. #
  390. self.tools_table.resizeColumnsToContents()
  391. self.tools_table.resizeRowsToContents()
  392. vertical_header = self.tools_table.verticalHeader()
  393. vertical_header.hide()
  394. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  395. horizontal_header = self.tools_table.horizontalHeader()
  396. horizontal_header.setMinimumSectionSize(10)
  397. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  398. horizontal_header.resizeSection(0, 20)
  399. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  400. # self.tools_table.setSortingEnabled(True)
  401. # sort by tool diameter
  402. # self.tools_table.sortItems(1)
  403. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  404. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  405. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  406. self.tools_table.itemChanged.connect(self.on_tool_edit)
  407. def on_tool_add(self, dia=None, muted=None):
  408. try:
  409. self.tools_table.itemChanged.disconnect()
  410. except:
  411. pass
  412. if dia:
  413. tool_dia = dia
  414. else:
  415. try:
  416. tool_dia = float(self.addtool_entry.get_value())
  417. except ValueError:
  418. # try to convert comma to decimal point. if it's still not working error message and return
  419. try:
  420. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  421. except ValueError:
  422. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  423. "use a number.")
  424. return
  425. if tool_dia is None:
  426. self.build_ui()
  427. self.app.inform.emit("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format.")
  428. return
  429. # construct a list of all 'tooluid' in the self.tools
  430. tool_uid_list = []
  431. for tooluid_key in self.paint_tools:
  432. tool_uid_item = int(tooluid_key)
  433. tool_uid_list.append(tool_uid_item)
  434. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  435. if not tool_uid_list:
  436. max_uid = 0
  437. else:
  438. max_uid = max(tool_uid_list)
  439. self.tooluid = int(max_uid + 1)
  440. tool_dias = []
  441. for k, v in self.paint_tools.items():
  442. for tool_v in v.keys():
  443. if tool_v == 'tooldia':
  444. tool_dias.append(float('%.4f' % v[tool_v]))
  445. if float('%.4f' % tool_dia) in tool_dias:
  446. if muted is None:
  447. self.app.inform.emit("[WARNING_NOTCL]Adding tool cancelled. Tool already in Tool Table.")
  448. self.tools_table.itemChanged.connect(self.on_tool_edit)
  449. return
  450. else:
  451. if muted is None:
  452. self.app.inform.emit("[success] New tool added to Tool Table.")
  453. self.paint_tools.update({
  454. int(self.tooluid): {
  455. 'tooldia': float('%.4f' % tool_dia),
  456. 'offset': 'Path',
  457. 'offset_value': 0.0,
  458. 'type': 'Iso',
  459. 'tool_type': 'V',
  460. 'data': dict(self.default_data),
  461. 'solid_geometry': []
  462. }
  463. })
  464. self.build_ui()
  465. def on_tool_edit(self):
  466. try:
  467. self.tools_table.itemChanged.disconnect()
  468. except:
  469. pass
  470. tool_dias = []
  471. for k, v in self.paint_tools.items():
  472. for tool_v in v.keys():
  473. if tool_v == 'tooldia':
  474. tool_dias.append(float('%.4f' % v[tool_v]))
  475. for row in range(self.tools_table.rowCount()):
  476. try:
  477. new_tool_dia = float(self.tools_table.item(row, 1).text())
  478. except ValueError:
  479. # try to convert comma to decimal point. if it's still not working error message and return
  480. try:
  481. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  482. except ValueError:
  483. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  484. "use a number.")
  485. return
  486. tooluid = int(self.tools_table.item(row, 3).text())
  487. # identify the tool that was edited and get it's tooluid
  488. if new_tool_dia not in tool_dias:
  489. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  490. self.app.inform.emit("[success] Tool from Tool Table was edited.")
  491. self.build_ui()
  492. return
  493. else:
  494. # identify the old tool_dia and restore the text in tool table
  495. for k, v in self.paint_tools.items():
  496. if k == tooluid:
  497. old_tool_dia = v['tooldia']
  498. break
  499. restore_dia_item = self.tools_table.item(row, 1)
  500. restore_dia_item.setText(str(old_tool_dia))
  501. self.app.inform.emit("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table.")
  502. self.build_ui()
  503. # def on_tool_copy(self, all=None):
  504. # try:
  505. # self.tools_table.itemChanged.disconnect()
  506. # except:
  507. # pass
  508. #
  509. # # find the tool_uid maximum value in the self.tools
  510. # uid_list = []
  511. # for key in self.paint_tools:
  512. # uid_list.append(int(key))
  513. # try:
  514. # max_uid = max(uid_list, key=int)
  515. # except ValueError:
  516. # max_uid = 0
  517. #
  518. # if all is None:
  519. # if self.tools_table.selectedItems():
  520. # for current_row in self.tools_table.selectedItems():
  521. # # sometime the header get selected and it has row number -1
  522. # # we don't want to do anything with the header :)
  523. # if current_row.row() < 0:
  524. # continue
  525. # try:
  526. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  527. # max_uid += 1
  528. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  529. # for td in self.paint_tools:
  530. # print("COPIED", self.paint_tools[td])
  531. # self.build_ui()
  532. # except AttributeError:
  533. # self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  534. # self.build_ui()
  535. # return
  536. # except Exception as e:
  537. # log.debug("on_tool_copy() --> " + str(e))
  538. # # deselect the table
  539. # # self.ui.geo_tools_table.clearSelection()
  540. # else:
  541. # self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  542. # self.build_ui()
  543. # return
  544. # else:
  545. # # we copy all tools in geo_tools_table
  546. # try:
  547. # temp_tools = dict(self.paint_tools)
  548. # max_uid += 1
  549. # for tooluid in temp_tools:
  550. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  551. # temp_tools.clear()
  552. # self.build_ui()
  553. # except Exception as e:
  554. # log.debug("on_tool_copy() --> " + str(e))
  555. #
  556. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  557. def on_tool_delete(self, rows_to_delete=None, all=None):
  558. try:
  559. self.tools_table.itemChanged.disconnect()
  560. except:
  561. pass
  562. deleted_tools_list = []
  563. if all:
  564. self.paint_tools.clear()
  565. self.build_ui()
  566. return
  567. if rows_to_delete:
  568. try:
  569. for row in rows_to_delete:
  570. tooluid_del = int(self.tools_table.item(row, 3).text())
  571. deleted_tools_list.append(tooluid_del)
  572. except TypeError:
  573. deleted_tools_list.append(rows_to_delete)
  574. for t in deleted_tools_list:
  575. self.paint_tools.pop(t, None)
  576. self.build_ui()
  577. return
  578. try:
  579. if self.tools_table.selectedItems():
  580. for row_sel in self.tools_table.selectedItems():
  581. row = row_sel.row()
  582. if row < 0:
  583. continue
  584. tooluid_del = int(self.tools_table.item(row, 3).text())
  585. deleted_tools_list.append(tooluid_del)
  586. for t in deleted_tools_list:
  587. self.paint_tools.pop(t, None)
  588. except AttributeError:
  589. self.app.inform.emit("[WARNING_NOTCL]Delete failed. Select a tool to delete.")
  590. return
  591. except Exception as e:
  592. log.debug(str(e))
  593. self.app.inform.emit("[success] Tool(s) deleted from Tool Table.")
  594. self.build_ui()
  595. def on_paint_button_click(self):
  596. self.app.report_usage("geometry_on_paint_button")
  597. self.app.inform.emit("[WARNING_NOTCL]Click inside the desired polygon.")
  598. try:
  599. overlap = float(self.paintoverlap_entry.get_value())
  600. except ValueError:
  601. # try to convert comma to decimal point. if it's still not working error message and return
  602. try:
  603. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  604. except ValueError:
  605. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  606. "use a number.")
  607. return
  608. connect = self.pathconnect_cb.get_value()
  609. contour = self.paintcontour_cb.get_value()
  610. select_method = self.selectmethod_combo.get_value()
  611. self.obj_name = self.object_combo.currentText()
  612. # Get source object.
  613. try:
  614. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  615. except:
  616. self.app.inform.emit("[ERROR_NOTCL]Could not retrieve object: %s" % self.obj_name)
  617. return
  618. if self.paint_obj is None:
  619. self.app.inform.emit("[ERROR_NOTCL]Object not found: %s" % self.paint_obj)
  620. return
  621. o_name = '%s_multitool_paint' % (self.obj_name)
  622. if select_method == "all":
  623. self.paint_poly_all(self.paint_obj,
  624. outname=o_name,
  625. overlap=overlap,
  626. connect=connect,
  627. contour=contour)
  628. if select_method == "single":
  629. self.app.inform.emit("[WARNING_NOTCL]Click inside the desired polygon.")
  630. # use the first tool in the tool table; get the diameter
  631. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  632. # To be called after clicking on the plot.
  633. def doit(event):
  634. # do paint single only for left mouse clicks
  635. if event.button == 1:
  636. self.app.inform.emit("Painting polygon...")
  637. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  638. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  639. self.paint_poly(self.paint_obj,
  640. inside_pt=[pos[0], pos[1]],
  641. tooldia=tooldia,
  642. overlap=overlap,
  643. connect=connect,
  644. contour=contour)
  645. self.app.plotcanvas.vis_connect('mouse_press', doit)
  646. def paint_poly(self, obj, inside_pt, tooldia, overlap,
  647. outname=None, connect=True,
  648. contour=True):
  649. """
  650. Paints a polygon selected by clicking on its interior.
  651. Note:
  652. * The margin is taken directly from the form.
  653. :param inside_pt: [x, y]
  654. :param tooldia: Diameter of the painting tool
  655. :param overlap: Overlap of the tool between passes.
  656. :param outname: Name of the resulting Geometry Object.
  657. :param connect: Connect lines to avoid tool lifts.
  658. :param contour: Paint around the edges.
  659. :return: None
  660. """
  661. # Which polygon.
  662. # poly = find_polygon(self.solid_geometry, inside_pt)
  663. poly = obj.find_polygon(inside_pt)
  664. paint_method = self.paintmethod_combo.get_value()
  665. try:
  666. paint_margin = float(self.paintmargin_entry.get_value())
  667. except ValueError:
  668. # try to convert comma to decimal point. if it's still not working error message and return
  669. try:
  670. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  671. except ValueError:
  672. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  673. "use a number.")
  674. return
  675. # No polygon?
  676. if poly is None:
  677. self.app.log.warning('No polygon found.')
  678. self.app.inform.emit('[WARNING] No polygon found.')
  679. return
  680. proc = self.app.proc_container.new("Painting polygon.")
  681. name = outname if outname else self.obj_name + "_paint"
  682. # Initializes the new geometry object
  683. def gen_paintarea(geo_obj, app_obj):
  684. assert isinstance(geo_obj, FlatCAMGeometry), \
  685. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  686. # assert isinstance(app_obj, App)
  687. def paint_p(polyg):
  688. if paint_method == "seed":
  689. # Type(cp) == FlatCAMRTreeStorage | None
  690. cp = self.clear_polygon2(polyg,
  691. tooldia=tooldia,
  692. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  693. overlap=overlap,
  694. contour=contour,
  695. connect=connect)
  696. elif paint_method == "lines":
  697. # Type(cp) == FlatCAMRTreeStorage | None
  698. cp = self.clear_polygon3(polyg,
  699. tooldia=tooldia,
  700. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  701. overlap=overlap,
  702. contour=contour,
  703. connect=connect)
  704. else:
  705. # Type(cp) == FlatCAMRTreeStorage | None
  706. cp = self.clear_polygon(polyg,
  707. tooldia=tooldia,
  708. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  709. overlap=overlap,
  710. contour=contour,
  711. connect=connect)
  712. if cp is not None:
  713. geo_obj.solid_geometry += list(cp.get_objects())
  714. return cp
  715. else:
  716. self.app.inform.emit('[ERROR_NOTCL] Geometry could not be painted completely')
  717. return None
  718. geo_obj.solid_geometry = []
  719. try:
  720. a, b, c, d = poly.bounds()
  721. geo_obj.options['xmin'] = a
  722. geo_obj.options['ymin'] = b
  723. geo_obj.options['xmax'] = c
  724. geo_obj.options['ymax'] = d
  725. except Exception as e:
  726. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  727. return
  728. try:
  729. poly_buf = poly.buffer(-paint_margin)
  730. if isinstance(poly_buf, MultiPolygon):
  731. cp = []
  732. for pp in poly_buf:
  733. cp.append(paint_p(pp))
  734. else:
  735. cp = paint_p(poly_buf)
  736. except Exception as e:
  737. log.debug("Could not Paint the polygons. %s" % str(e))
  738. self.app.inform.emit(
  739. "[ERROR] Could not do Paint. Try a different combination of parameters. "
  740. "Or a different strategy of paint\n%s" % str(e))
  741. return
  742. if cp is not None:
  743. if isinstance(cp, list):
  744. for x in cp:
  745. geo_obj.solid_geometry += list(x.get_objects())
  746. else:
  747. geo_obj.solid_geometry = list(cp.get_objects())
  748. geo_obj.options["cnctooldia"] = tooldia
  749. # this turn on the FlatCAMCNCJob plot for multiple tools
  750. geo_obj.multigeo = False
  751. geo_obj.multitool = True
  752. current_uid = int(self.tools_table.item(0, 3).text())
  753. for k, v in self.paint_tools.items():
  754. if k == current_uid:
  755. v['data']['name'] = name
  756. geo_obj.tools = dict(self.paint_tools)
  757. # Experimental...
  758. # print("Indexing...", end=' ')
  759. # geo_obj.make_index()
  760. # if errors == 0:
  761. # print("[success] Paint single polygon Done")
  762. # self.app.inform.emit("[success] Paint single polygon Done")
  763. # else:
  764. # print("[WARNING] Paint single polygon done with errors")
  765. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  766. # "%d area(s) could not be painted.\n"
  767. # "Use different paint parameters or edit the paint geometry and correct"
  768. # "the issue."
  769. # % errors)
  770. def job_thread(app_obj):
  771. try:
  772. app_obj.new_object("geometry", name, gen_paintarea)
  773. except Exception as e:
  774. proc.done()
  775. self.app.inform.emit('[ERROR_NOTCL] PaintTool.paint_poly() --> %s' % str(e))
  776. return
  777. proc.done()
  778. # focus on Selected Tab
  779. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  780. self.app.inform.emit("Polygon Paint started ...")
  781. # Promise object with the new name
  782. self.app.collection.promise(name)
  783. # Background
  784. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  785. def paint_poly_all(self, obj, overlap, outname=None,
  786. connect=True, contour=True):
  787. """
  788. Paints all polygons in this object.
  789. :param tooldia:
  790. :param overlap:
  791. :param outname:
  792. :param connect: Connect lines to avoid tool lifts.
  793. :param contour: Paint around the edges.
  794. :return:
  795. """
  796. paint_method = self.paintmethod_combo.get_value()
  797. try:
  798. paint_margin = float(self.paintmargin_entry.get_value())
  799. except ValueError:
  800. # try to convert comma to decimal point. if it's still not working error message and return
  801. try:
  802. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  803. except ValueError:
  804. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  805. "use a number.")
  806. return
  807. proc = self.app.proc_container.new("Painting polygon.")
  808. name = outname if outname else self.obj_name + "_paint"
  809. over = overlap
  810. conn = connect
  811. cont = contour
  812. # This is a recursive generator of individual Polygons.
  813. # Note: Double check correct implementation. Might exit
  814. # early if it finds something that is not a Polygon?
  815. # def recurse(geo):
  816. # try:
  817. # for subg in geo:
  818. # for subsubg in recurse(subg):
  819. # yield subsubg
  820. # except TypeError:
  821. # if isinstance(geo, Polygon):
  822. # yield geo
  823. #
  824. # raise StopIteration
  825. def recurse(geometry, reset=True):
  826. """
  827. Creates a list of non-iterable linear geometry objects.
  828. Results are placed in self.flat_geometry
  829. :param geometry: Shapely type or list or list of list of such.
  830. :param reset: Clears the contents of self.flat_geometry.
  831. """
  832. if geometry is None:
  833. return
  834. if reset:
  835. self.flat_geometry = []
  836. ## If iterable, expand recursively.
  837. try:
  838. for geo in geometry:
  839. if geo is not None:
  840. recurse(geometry=geo, reset=False)
  841. ## Not iterable, do the actual indexing and add.
  842. except TypeError:
  843. self.flat_geometry.append(geometry)
  844. return self.flat_geometry
  845. # Initializes the new geometry object
  846. def gen_paintarea(geo_obj, app_obj):
  847. assert isinstance(geo_obj, FlatCAMGeometry), \
  848. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  849. sorted_tools = []
  850. for row in range(self.tools_table.rowCount()):
  851. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  852. sorted_tools.sort(reverse=True)
  853. try:
  854. a, b, c, d = obj.bounds()
  855. geo_obj.options['xmin'] = a
  856. geo_obj.options['ymin'] = b
  857. geo_obj.options['xmax'] = c
  858. geo_obj.options['ymax'] = d
  859. except Exception as e:
  860. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  861. return
  862. total_geometry = []
  863. current_uid = int(1)
  864. geo_obj.solid_geometry = []
  865. for tool_dia in sorted_tools:
  866. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  867. for k, v in self.paint_tools.items():
  868. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  869. current_uid = int(k)
  870. break
  871. for geo in recurse(obj.solid_geometry):
  872. try:
  873. if not isinstance(geo, Polygon):
  874. geo = Polygon(geo)
  875. poly_buf = geo.buffer(-paint_margin)
  876. if paint_method == "seed":
  877. # Type(cp) == FlatCAMRTreeStorage | None
  878. cp = self.clear_polygon2(poly_buf,
  879. tooldia=tool_dia,
  880. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  881. overlap=over,
  882. contour=cont,
  883. connect=conn)
  884. elif paint_method == "lines":
  885. # Type(cp) == FlatCAMRTreeStorage | None
  886. cp = self.clear_polygon3(poly_buf,
  887. tooldia=tool_dia,
  888. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  889. overlap=over,
  890. contour=cont,
  891. connect=conn)
  892. else:
  893. # Type(cp) == FlatCAMRTreeStorage | None
  894. cp = self.clear_polygon(poly_buf,
  895. tooldia=tool_dia,
  896. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  897. overlap=over,
  898. contour=cont,
  899. connect=conn)
  900. if cp is not None:
  901. total_geometry += list(cp.get_objects())
  902. except Exception as e:
  903. log.debug("Could not Paint the polygons. %s" % str(e))
  904. self.app.inform.emit(
  905. "[ERROR] Could not do Paint All. Try a different combination of parameters. "
  906. "Or a different Method of paint\n%s" % str(e))
  907. return
  908. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  909. # temporary list that stored that solid_geometry
  910. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  911. self.paint_tools[current_uid]['data']['name'] = name
  912. total_geometry[:] = []
  913. geo_obj.options["cnctooldia"] = tool_dia
  914. # this turn on the FlatCAMCNCJob plot for multiple tools
  915. geo_obj.multigeo = True
  916. geo_obj.multitool = True
  917. geo_obj.tools.clear()
  918. geo_obj.tools = dict(self.paint_tools)
  919. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  920. has_solid_geo = 0
  921. for tooluid in geo_obj.tools:
  922. if geo_obj.tools[tooluid]['solid_geometry']:
  923. has_solid_geo += 1
  924. if has_solid_geo == 0:
  925. self.app.inform.emit("[ERROR] There is no Painting Geometry in the file.\n"
  926. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  927. "Change the painting parameters and try again.")
  928. return
  929. # Experimental...
  930. # print("Indexing...", end=' ')
  931. # geo_obj.make_index()
  932. self.app.inform.emit("[success] Paint All Done.")
  933. # Initializes the new geometry object
  934. def gen_paintarea_rest_machining(geo_obj, app_obj):
  935. assert isinstance(geo_obj, FlatCAMGeometry), \
  936. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  937. sorted_tools = []
  938. for row in range(self.tools_table.rowCount()):
  939. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  940. sorted_tools.sort(reverse=True)
  941. cleared_geo = []
  942. current_uid = int(1)
  943. geo_obj.solid_geometry = []
  944. try:
  945. a, b, c, d = obj.bounds()
  946. geo_obj.options['xmin'] = a
  947. geo_obj.options['ymin'] = b
  948. geo_obj.options['xmax'] = c
  949. geo_obj.options['ymax'] = d
  950. except Exception as e:
  951. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  952. return
  953. for tool_dia in sorted_tools:
  954. for geo in recurse(obj.solid_geometry):
  955. try:
  956. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  957. poly_buf = geo.buffer(-paint_margin)
  958. if paint_method == "standard":
  959. # Type(cp) == FlatCAMRTreeStorage | None
  960. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  961. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  962. overlap=over, contour=cont, connect=conn)
  963. elif paint_method == "seed":
  964. # Type(cp) == FlatCAMRTreeStorage | None
  965. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  966. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  967. overlap=over, contour=cont, connect=conn)
  968. elif paint_method == "lines":
  969. # Type(cp) == FlatCAMRTreeStorage | None
  970. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  971. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  972. overlap=over, contour=cont, connect=conn)
  973. if cp is not None:
  974. cleared_geo += list(cp.get_objects())
  975. except Exception as e:
  976. log.debug("Could not Paint the polygons. %s" % str(e))
  977. self.app.inform.emit(
  978. "[ERROR] Could not do Paint All. Try a different combination of parameters. "
  979. "Or a different Method of paint\n%s" % str(e))
  980. return
  981. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  982. for k, v in self.paint_tools.items():
  983. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  984. current_uid = int(k)
  985. break
  986. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  987. # temporary list that stored that solid_geometry
  988. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  989. self.paint_tools[current_uid]['data']['name'] = name
  990. cleared_geo[:] = []
  991. geo_obj.options["cnctooldia"] = tool_dia
  992. # this turn on the FlatCAMCNCJob plot for multiple tools
  993. geo_obj.multigeo = True
  994. geo_obj.multitool = True
  995. geo_obj.tools.clear()
  996. geo_obj.tools = dict(self.paint_tools)
  997. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  998. has_solid_geo = 0
  999. for tooluid in geo_obj.tools:
  1000. if geo_obj.tools[tooluid]['solid_geometry']:
  1001. has_solid_geo += 1
  1002. if has_solid_geo == 0:
  1003. self.app.inform.emit("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1004. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1005. "Change the painting parameters and try again.")
  1006. return
  1007. # Experimental...
  1008. # print("Indexing...", end=' ')
  1009. # geo_obj.make_index()
  1010. self.app.inform.emit("[success] Paint All with Rest-Machining Done.")
  1011. def job_thread(app_obj):
  1012. try:
  1013. if self.rest_cb.isChecked():
  1014. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1015. else:
  1016. app_obj.new_object("geometry", name, gen_paintarea)
  1017. except Exception as e:
  1018. proc.done()
  1019. traceback.print_stack()
  1020. return
  1021. proc.done()
  1022. # focus on Selected Tab
  1023. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1024. self.app.inform.emit("Polygon Paint started ...")
  1025. # Promise object with the new name
  1026. self.app.collection.promise(name)
  1027. # Background
  1028. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1029. def reset_fields(self):
  1030. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))