ToolPaint.py 52 KB

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