ToolPaint.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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. # if the splitter us hidden, display it
  259. if self.app.ui.splitter.sizes()[0] == 0:
  260. self.app.ui.splitter.setSizes([1, 1])
  261. self.app.ui.notebook.setTabText(2, "Paint Tool")
  262. def on_radio_selection(self):
  263. if self.selectmethod_combo.get_value() == 'single':
  264. # disable rest-machining for single polygon painting
  265. self.rest_cb.set_value(False)
  266. self.rest_cb.setDisabled(True)
  267. # delete all tools except first row / tool for single polygon painting
  268. list_to_del = list(range(1, self.tools_table.rowCount()))
  269. if list_to_del:
  270. self.on_tool_delete(rows_to_delete=list_to_del)
  271. # disable addTool and delTool
  272. self.addtool_entry.setDisabled(True)
  273. self.addtool_btn.setDisabled(True)
  274. self.deltool_btn.setDisabled(True)
  275. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  276. else:
  277. self.rest_cb.setDisabled(False)
  278. self.addtool_entry.setDisabled(False)
  279. self.addtool_btn.setDisabled(False)
  280. self.deltool_btn.setDisabled(False)
  281. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  282. def set_tool_ui(self):
  283. self.tools_frame.show()
  284. self.reset_fields()
  285. ## Init the GUI interface
  286. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  287. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  288. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  289. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  290. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  291. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  292. # updated units
  293. self.units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  294. if self.units == "IN":
  295. self.addtool_entry.set_value(0.039)
  296. else:
  297. self.addtool_entry.set_value(1)
  298. self.tools_table.setupContextMenu()
  299. self.tools_table.addContextMenu(
  300. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  301. self.tools_table.addContextMenu(
  302. "Delete", lambda:
  303. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  304. # set the working variables to a known state
  305. self.paint_tools.clear()
  306. self.tooluid = 0
  307. self.default_data.clear()
  308. self.default_data.update({
  309. "name": '_paint',
  310. "plot": self.app.defaults["geometry_plot"],
  311. "cutz": self.app.defaults["geometry_cutz"],
  312. "vtipdia": 0.1,
  313. "vtipangle": 30,
  314. "travelz": self.app.defaults["geometry_travelz"],
  315. "feedrate": self.app.defaults["geometry_feedrate"],
  316. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  317. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  318. "dwell": self.app.defaults["geometry_dwell"],
  319. "dwelltime": self.app.defaults["geometry_dwelltime"],
  320. "multidepth": self.app.defaults["geometry_multidepth"],
  321. "ppname_g": self.app.defaults["geometry_ppname_g"],
  322. "depthperpass": self.app.defaults["geometry_depthperpass"],
  323. "extracut": self.app.defaults["geometry_extracut"],
  324. "toolchange": self.app.defaults["geometry_toolchange"],
  325. "toolchangez": self.app.defaults["geometry_toolchangez"],
  326. "endz": self.app.defaults["geometry_endz"],
  327. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  328. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  329. "startz": self.app.defaults["geometry_startz"],
  330. "tooldia": self.app.defaults["tools_painttooldia"],
  331. "paintmargin": self.app.defaults["tools_paintmargin"],
  332. "paintmethod": self.app.defaults["tools_paintmethod"],
  333. "selectmethod": self.app.defaults["tools_selectmethod"],
  334. "pathconnect": self.app.defaults["tools_pathconnect"],
  335. "paintcontour": self.app.defaults["tools_paintcontour"],
  336. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  337. })
  338. # call on self.on_tool_add() counts as an call to self.build_ui()
  339. # through this, we add a initial row / tool in the tool_table
  340. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  341. # if the Paint Method is "Single" disable the tool table context menu
  342. if self.default_data["selectmethod"] == "single":
  343. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  344. def build_ui(self):
  345. try:
  346. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  347. self.tools_table.itemChanged.disconnect()
  348. except:
  349. pass
  350. # updated units
  351. self.units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  352. sorted_tools = []
  353. for k, v in self.paint_tools.items():
  354. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  355. sorted_tools.sort()
  356. n = len(sorted_tools)
  357. self.tools_table.setRowCount(n)
  358. tool_id = 0
  359. for tool_sorted in sorted_tools:
  360. for tooluid_key, tooluid_value in self.paint_tools.items():
  361. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  362. tool_id += 1
  363. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  364. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  365. row_no = tool_id - 1
  366. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  367. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  368. # There are no drill bits in MM with more than 3 decimals diameter
  369. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  370. if self.units == 'MM':
  371. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  372. else:
  373. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  374. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  375. tool_type_item = QtWidgets.QComboBox()
  376. for item in self.tool_type_item_options:
  377. tool_type_item.addItem(item)
  378. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  379. idx = tool_type_item.findText(tooluid_value['tool_type'])
  380. tool_type_item.setCurrentIndex(idx)
  381. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  382. self.tools_table.setItem(row_no, 1, dia) # Diameter
  383. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  384. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  385. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  386. # make the diameter column editable
  387. for row in range(tool_id):
  388. self.tools_table.item(row, 1).setFlags(
  389. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  390. # all the tools are selected by default
  391. self.tools_table.selectColumn(0)
  392. #
  393. self.tools_table.resizeColumnsToContents()
  394. self.tools_table.resizeRowsToContents()
  395. vertical_header = self.tools_table.verticalHeader()
  396. vertical_header.hide()
  397. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  398. horizontal_header = self.tools_table.horizontalHeader()
  399. horizontal_header.setMinimumSectionSize(10)
  400. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  401. horizontal_header.resizeSection(0, 20)
  402. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  403. # self.tools_table.setSortingEnabled(True)
  404. # sort by tool diameter
  405. # self.tools_table.sortItems(1)
  406. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  407. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  408. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  409. self.tools_table.itemChanged.connect(self.on_tool_edit)
  410. def on_tool_add(self, dia=None, muted=None):
  411. try:
  412. self.tools_table.itemChanged.disconnect()
  413. except:
  414. pass
  415. if dia:
  416. tool_dia = dia
  417. else:
  418. try:
  419. tool_dia = float(self.addtool_entry.get_value())
  420. except ValueError:
  421. # try to convert comma to decimal point. if it's still not working error message and return
  422. try:
  423. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  424. except ValueError:
  425. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  426. "use a number.")
  427. return
  428. if tool_dia is None:
  429. self.build_ui()
  430. self.app.inform.emit("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format.")
  431. return
  432. # construct a list of all 'tooluid' in the self.tools
  433. tool_uid_list = []
  434. for tooluid_key in self.paint_tools:
  435. tool_uid_item = int(tooluid_key)
  436. tool_uid_list.append(tool_uid_item)
  437. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  438. if not tool_uid_list:
  439. max_uid = 0
  440. else:
  441. max_uid = max(tool_uid_list)
  442. self.tooluid = int(max_uid + 1)
  443. tool_dias = []
  444. for k, v in self.paint_tools.items():
  445. for tool_v in v.keys():
  446. if tool_v == 'tooldia':
  447. tool_dias.append(float('%.4f' % v[tool_v]))
  448. if float('%.4f' % tool_dia) in tool_dias:
  449. if muted is None:
  450. self.app.inform.emit("[WARNING_NOTCL]Adding tool cancelled. Tool already in Tool Table.")
  451. self.tools_table.itemChanged.connect(self.on_tool_edit)
  452. return
  453. else:
  454. if muted is None:
  455. self.app.inform.emit("[success] New tool added to Tool Table.")
  456. self.paint_tools.update({
  457. int(self.tooluid): {
  458. 'tooldia': float('%.4f' % tool_dia),
  459. 'offset': 'Path',
  460. 'offset_value': 0.0,
  461. 'type': 'Iso',
  462. 'tool_type': 'V',
  463. 'data': dict(self.default_data),
  464. 'solid_geometry': []
  465. }
  466. })
  467. self.build_ui()
  468. def on_tool_edit(self):
  469. try:
  470. self.tools_table.itemChanged.disconnect()
  471. except:
  472. pass
  473. tool_dias = []
  474. for k, v in self.paint_tools.items():
  475. for tool_v in v.keys():
  476. if tool_v == 'tooldia':
  477. tool_dias.append(float('%.4f' % v[tool_v]))
  478. for row in range(self.tools_table.rowCount()):
  479. try:
  480. new_tool_dia = float(self.tools_table.item(row, 1).text())
  481. except ValueError:
  482. # try to convert comma to decimal point. if it's still not working error message and return
  483. try:
  484. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  485. except ValueError:
  486. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  487. "use a number.")
  488. return
  489. tooluid = int(self.tools_table.item(row, 3).text())
  490. # identify the tool that was edited and get it's tooluid
  491. if new_tool_dia not in tool_dias:
  492. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  493. self.app.inform.emit("[success] Tool from Tool Table was edited.")
  494. self.build_ui()
  495. return
  496. else:
  497. # identify the old tool_dia and restore the text in tool table
  498. for k, v in self.paint_tools.items():
  499. if k == tooluid:
  500. old_tool_dia = v['tooldia']
  501. break
  502. restore_dia_item = self.tools_table.item(row, 1)
  503. restore_dia_item.setText(str(old_tool_dia))
  504. self.app.inform.emit("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table.")
  505. self.build_ui()
  506. # def on_tool_copy(self, all=None):
  507. # try:
  508. # self.tools_table.itemChanged.disconnect()
  509. # except:
  510. # pass
  511. #
  512. # # find the tool_uid maximum value in the self.tools
  513. # uid_list = []
  514. # for key in self.paint_tools:
  515. # uid_list.append(int(key))
  516. # try:
  517. # max_uid = max(uid_list, key=int)
  518. # except ValueError:
  519. # max_uid = 0
  520. #
  521. # if all is None:
  522. # if self.tools_table.selectedItems():
  523. # for current_row in self.tools_table.selectedItems():
  524. # # sometime the header get selected and it has row number -1
  525. # # we don't want to do anything with the header :)
  526. # if current_row.row() < 0:
  527. # continue
  528. # try:
  529. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  530. # max_uid += 1
  531. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  532. # for td in self.paint_tools:
  533. # print("COPIED", self.paint_tools[td])
  534. # self.build_ui()
  535. # except AttributeError:
  536. # self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  537. # self.build_ui()
  538. # return
  539. # except Exception as e:
  540. # log.debug("on_tool_copy() --> " + str(e))
  541. # # deselect the table
  542. # # self.ui.geo_tools_table.clearSelection()
  543. # else:
  544. # self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  545. # self.build_ui()
  546. # return
  547. # else:
  548. # # we copy all tools in geo_tools_table
  549. # try:
  550. # temp_tools = dict(self.paint_tools)
  551. # max_uid += 1
  552. # for tooluid in temp_tools:
  553. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  554. # temp_tools.clear()
  555. # self.build_ui()
  556. # except Exception as e:
  557. # log.debug("on_tool_copy() --> " + str(e))
  558. #
  559. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  560. def on_tool_delete(self, rows_to_delete=None, all=None):
  561. try:
  562. self.tools_table.itemChanged.disconnect()
  563. except:
  564. pass
  565. deleted_tools_list = []
  566. if all:
  567. self.paint_tools.clear()
  568. self.build_ui()
  569. return
  570. if rows_to_delete:
  571. try:
  572. for row in rows_to_delete:
  573. tooluid_del = int(self.tools_table.item(row, 3).text())
  574. deleted_tools_list.append(tooluid_del)
  575. except TypeError:
  576. deleted_tools_list.append(rows_to_delete)
  577. for t in deleted_tools_list:
  578. self.paint_tools.pop(t, None)
  579. self.build_ui()
  580. return
  581. try:
  582. if self.tools_table.selectedItems():
  583. for row_sel in self.tools_table.selectedItems():
  584. row = row_sel.row()
  585. if row < 0:
  586. continue
  587. tooluid_del = int(self.tools_table.item(row, 3).text())
  588. deleted_tools_list.append(tooluid_del)
  589. for t in deleted_tools_list:
  590. self.paint_tools.pop(t, None)
  591. except AttributeError:
  592. self.app.inform.emit("[WARNING_NOTCL]Delete failed. Select a tool to delete.")
  593. return
  594. except Exception as e:
  595. log.debug(str(e))
  596. self.app.inform.emit("[success] Tool(s) deleted from Tool Table.")
  597. self.build_ui()
  598. def on_paint_button_click(self):
  599. self.app.report_usage("geometry_on_paint_button")
  600. self.app.inform.emit("[WARNING_NOTCL]Click inside the desired polygon.")
  601. try:
  602. overlap = float(self.paintoverlap_entry.get_value())
  603. except ValueError:
  604. # try to convert comma to decimal point. if it's still not working error message and return
  605. try:
  606. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  607. except ValueError:
  608. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  609. "use a number.")
  610. return
  611. connect = self.pathconnect_cb.get_value()
  612. contour = self.paintcontour_cb.get_value()
  613. select_method = self.selectmethod_combo.get_value()
  614. self.obj_name = self.object_combo.currentText()
  615. # Get source object.
  616. try:
  617. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  618. except:
  619. self.app.inform.emit("[ERROR_NOTCL]Could not retrieve object: %s" % self.obj_name)
  620. return
  621. if self.paint_obj is None:
  622. self.app.inform.emit("[ERROR_NOTCL]Object not found: %s" % self.paint_obj)
  623. return
  624. o_name = '%s_multitool_paint' % (self.obj_name)
  625. if select_method == "all":
  626. self.paint_poly_all(self.paint_obj,
  627. outname=o_name,
  628. overlap=overlap,
  629. connect=connect,
  630. contour=contour)
  631. if select_method == "single":
  632. self.app.inform.emit("[WARNING_NOTCL]Click inside the desired polygon.")
  633. # use the first tool in the tool table; get the diameter
  634. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  635. # To be called after clicking on the plot.
  636. def doit(event):
  637. # do paint single only for left mouse clicks
  638. if event.button == 1:
  639. self.app.inform.emit("Painting polygon...")
  640. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  641. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  642. self.paint_poly(self.paint_obj,
  643. inside_pt=[pos[0], pos[1]],
  644. tooldia=tooldia,
  645. overlap=overlap,
  646. connect=connect,
  647. contour=contour)
  648. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  649. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  650. self.app.plotcanvas.vis_connect('mouse_press', doit)
  651. def paint_poly(self, obj, inside_pt, tooldia, overlap,
  652. outname=None, connect=True,
  653. contour=True):
  654. """
  655. Paints a polygon selected by clicking on its interior.
  656. Note:
  657. * The margin is taken directly from the form.
  658. :param inside_pt: [x, y]
  659. :param tooldia: Diameter of the painting tool
  660. :param overlap: Overlap of the tool between passes.
  661. :param outname: Name of the resulting Geometry Object.
  662. :param connect: Connect lines to avoid tool lifts.
  663. :param contour: Paint around the edges.
  664. :return: None
  665. """
  666. # Which polygon.
  667. # poly = find_polygon(self.solid_geometry, inside_pt)
  668. poly = obj.find_polygon(inside_pt)
  669. paint_method = self.paintmethod_combo.get_value()
  670. try:
  671. paint_margin = float(self.paintmargin_entry.get_value())
  672. except ValueError:
  673. # try to convert comma to decimal point. if it's still not working error message and return
  674. try:
  675. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  676. except ValueError:
  677. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  678. "use a number.")
  679. return
  680. # No polygon?
  681. if poly is None:
  682. self.app.log.warning('No polygon found.')
  683. self.app.inform.emit('[WARNING] No polygon found.')
  684. return
  685. proc = self.app.proc_container.new("Painting polygon.")
  686. name = outname if outname else self.obj_name + "_paint"
  687. # Initializes the new geometry object
  688. def gen_paintarea(geo_obj, app_obj):
  689. assert isinstance(geo_obj, FlatCAMGeometry), \
  690. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  691. # assert isinstance(app_obj, App)
  692. def paint_p(polyg):
  693. if paint_method == "seed":
  694. # Type(cp) == FlatCAMRTreeStorage | None
  695. cp = self.clear_polygon2(polyg,
  696. tooldia=tooldia,
  697. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  698. overlap=overlap,
  699. contour=contour,
  700. connect=connect)
  701. elif paint_method == "lines":
  702. # Type(cp) == FlatCAMRTreeStorage | None
  703. cp = self.clear_polygon3(polyg,
  704. tooldia=tooldia,
  705. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  706. overlap=overlap,
  707. contour=contour,
  708. connect=connect)
  709. else:
  710. # Type(cp) == FlatCAMRTreeStorage | None
  711. cp = self.clear_polygon(polyg,
  712. tooldia=tooldia,
  713. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  714. overlap=overlap,
  715. contour=contour,
  716. connect=connect)
  717. if cp is not None:
  718. geo_obj.solid_geometry += list(cp.get_objects())
  719. return cp
  720. else:
  721. self.app.inform.emit('[ERROR_NOTCL] Geometry could not be painted completely')
  722. return None
  723. geo_obj.solid_geometry = []
  724. try:
  725. a, b, c, d = poly.bounds()
  726. geo_obj.options['xmin'] = a
  727. geo_obj.options['ymin'] = b
  728. geo_obj.options['xmax'] = c
  729. geo_obj.options['ymax'] = d
  730. except Exception as e:
  731. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  732. return
  733. try:
  734. poly_buf = poly.buffer(-paint_margin)
  735. if isinstance(poly_buf, MultiPolygon):
  736. cp = []
  737. for pp in poly_buf:
  738. cp.append(paint_p(pp))
  739. else:
  740. cp = paint_p(poly_buf)
  741. except Exception as e:
  742. log.debug("Could not Paint the polygons. %s" % str(e))
  743. self.app.inform.emit(
  744. "[ERROR] Could not do Paint. Try a different combination of parameters. "
  745. "Or a different strategy of paint\n%s" % str(e))
  746. return
  747. if cp is not None:
  748. if isinstance(cp, list):
  749. for x in cp:
  750. geo_obj.solid_geometry += list(x.get_objects())
  751. else:
  752. geo_obj.solid_geometry = list(cp.get_objects())
  753. geo_obj.options["cnctooldia"] = tooldia
  754. # this turn on the FlatCAMCNCJob plot for multiple tools
  755. geo_obj.multigeo = False
  756. geo_obj.multitool = True
  757. current_uid = int(self.tools_table.item(0, 3).text())
  758. for k, v in self.paint_tools.items():
  759. if k == current_uid:
  760. v['data']['name'] = name
  761. geo_obj.tools = dict(self.paint_tools)
  762. # Experimental...
  763. # print("Indexing...", end=' ')
  764. # geo_obj.make_index()
  765. # if errors == 0:
  766. # print("[success] Paint single polygon Done")
  767. # self.app.inform.emit("[success] Paint single polygon Done")
  768. # else:
  769. # print("[WARNING] Paint single polygon done with errors")
  770. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  771. # "%d area(s) could not be painted.\n"
  772. # "Use different paint parameters or edit the paint geometry and correct"
  773. # "the issue."
  774. # % errors)
  775. def job_thread(app_obj):
  776. try:
  777. app_obj.new_object("geometry", name, gen_paintarea)
  778. except Exception as e:
  779. proc.done()
  780. self.app.inform.emit('[ERROR_NOTCL] PaintTool.paint_poly() --> %s' % str(e))
  781. return
  782. proc.done()
  783. # focus on Selected Tab
  784. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  785. self.app.inform.emit("Polygon Paint started ...")
  786. # Promise object with the new name
  787. self.app.collection.promise(name)
  788. # Background
  789. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  790. def paint_poly_all(self, obj, overlap, outname=None,
  791. connect=True, contour=True):
  792. """
  793. Paints all polygons in this object.
  794. :param tooldia:
  795. :param overlap:
  796. :param outname:
  797. :param connect: Connect lines to avoid tool lifts.
  798. :param contour: Paint around the edges.
  799. :return:
  800. """
  801. paint_method = self.paintmethod_combo.get_value()
  802. try:
  803. paint_margin = float(self.paintmargin_entry.get_value())
  804. except ValueError:
  805. # try to convert comma to decimal point. if it's still not working error message and return
  806. try:
  807. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  808. except ValueError:
  809. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  810. "use a number.")
  811. return
  812. proc = self.app.proc_container.new("Painting polygon.")
  813. name = outname if outname else self.obj_name + "_paint"
  814. over = overlap
  815. conn = connect
  816. cont = contour
  817. # This is a recursive generator of individual Polygons.
  818. # Note: Double check correct implementation. Might exit
  819. # early if it finds something that is not a Polygon?
  820. # def recurse(geo):
  821. # try:
  822. # for subg in geo:
  823. # for subsubg in recurse(subg):
  824. # yield subsubg
  825. # except TypeError:
  826. # if isinstance(geo, Polygon):
  827. # yield geo
  828. #
  829. # raise StopIteration
  830. def recurse(geometry, reset=True):
  831. """
  832. Creates a list of non-iterable linear geometry objects.
  833. Results are placed in self.flat_geometry
  834. :param geometry: Shapely type or list or list of list of such.
  835. :param reset: Clears the contents of self.flat_geometry.
  836. """
  837. if geometry is None:
  838. return
  839. if reset:
  840. self.flat_geometry = []
  841. ## If iterable, expand recursively.
  842. try:
  843. for geo in geometry:
  844. if geo is not None:
  845. recurse(geometry=geo, reset=False)
  846. ## Not iterable, do the actual indexing and add.
  847. except TypeError:
  848. self.flat_geometry.append(geometry)
  849. return self.flat_geometry
  850. # Initializes the new geometry object
  851. def gen_paintarea(geo_obj, app_obj):
  852. assert isinstance(geo_obj, FlatCAMGeometry), \
  853. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  854. sorted_tools = []
  855. for row in range(self.tools_table.rowCount()):
  856. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  857. sorted_tools.sort(reverse=True)
  858. try:
  859. a, b, c, d = obj.bounds()
  860. geo_obj.options['xmin'] = a
  861. geo_obj.options['ymin'] = b
  862. geo_obj.options['xmax'] = c
  863. geo_obj.options['ymax'] = d
  864. except Exception as e:
  865. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  866. return
  867. total_geometry = []
  868. current_uid = int(1)
  869. geo_obj.solid_geometry = []
  870. for tool_dia in sorted_tools:
  871. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  872. for k, v in self.paint_tools.items():
  873. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  874. current_uid = int(k)
  875. break
  876. for geo in recurse(obj.solid_geometry):
  877. try:
  878. if not isinstance(geo, Polygon):
  879. geo = Polygon(geo)
  880. poly_buf = geo.buffer(-paint_margin)
  881. if paint_method == "seed":
  882. # Type(cp) == FlatCAMRTreeStorage | None
  883. cp = self.clear_polygon2(poly_buf,
  884. tooldia=tool_dia,
  885. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  886. overlap=over,
  887. contour=cont,
  888. connect=conn)
  889. elif paint_method == "lines":
  890. # Type(cp) == FlatCAMRTreeStorage | None
  891. cp = self.clear_polygon3(poly_buf,
  892. tooldia=tool_dia,
  893. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  894. overlap=over,
  895. contour=cont,
  896. connect=conn)
  897. else:
  898. # Type(cp) == FlatCAMRTreeStorage | None
  899. cp = self.clear_polygon(poly_buf,
  900. tooldia=tool_dia,
  901. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  902. overlap=over,
  903. contour=cont,
  904. connect=conn)
  905. if cp is not None:
  906. total_geometry += list(cp.get_objects())
  907. except Exception as e:
  908. log.debug("Could not Paint the polygons. %s" % str(e))
  909. self.app.inform.emit(
  910. "[ERROR] Could not do Paint All. Try a different combination of parameters. "
  911. "Or a different Method of paint\n%s" % str(e))
  912. return
  913. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  914. # temporary list that stored that solid_geometry
  915. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  916. self.paint_tools[current_uid]['data']['name'] = name
  917. total_geometry[:] = []
  918. geo_obj.options["cnctooldia"] = tool_dia
  919. # this turn on the FlatCAMCNCJob plot for multiple tools
  920. geo_obj.multigeo = True
  921. geo_obj.multitool = True
  922. geo_obj.tools.clear()
  923. geo_obj.tools = dict(self.paint_tools)
  924. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  925. has_solid_geo = 0
  926. for tooluid in geo_obj.tools:
  927. if geo_obj.tools[tooluid]['solid_geometry']:
  928. has_solid_geo += 1
  929. if has_solid_geo == 0:
  930. self.app.inform.emit("[ERROR] There is no Painting Geometry in the file.\n"
  931. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  932. "Change the painting parameters and try again.")
  933. return
  934. # Experimental...
  935. # print("Indexing...", end=' ')
  936. # geo_obj.make_index()
  937. self.app.inform.emit("[success] Paint All Done.")
  938. # Initializes the new geometry object
  939. def gen_paintarea_rest_machining(geo_obj, app_obj):
  940. assert isinstance(geo_obj, FlatCAMGeometry), \
  941. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  942. sorted_tools = []
  943. for row in range(self.tools_table.rowCount()):
  944. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  945. sorted_tools.sort(reverse=True)
  946. cleared_geo = []
  947. current_uid = int(1)
  948. geo_obj.solid_geometry = []
  949. try:
  950. a, b, c, d = obj.bounds()
  951. geo_obj.options['xmin'] = a
  952. geo_obj.options['ymin'] = b
  953. geo_obj.options['xmax'] = c
  954. geo_obj.options['ymax'] = d
  955. except Exception as e:
  956. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  957. return
  958. for tool_dia in sorted_tools:
  959. for geo in recurse(obj.solid_geometry):
  960. try:
  961. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  962. poly_buf = geo.buffer(-paint_margin)
  963. if paint_method == "standard":
  964. # Type(cp) == FlatCAMRTreeStorage | None
  965. cp = self.clear_polygon(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 == "seed":
  969. # Type(cp) == FlatCAMRTreeStorage | None
  970. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  971. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  972. overlap=over, contour=cont, connect=conn)
  973. elif paint_method == "lines":
  974. # Type(cp) == FlatCAMRTreeStorage | None
  975. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  976. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  977. overlap=over, contour=cont, connect=conn)
  978. if cp is not None:
  979. cleared_geo += list(cp.get_objects())
  980. except Exception as e:
  981. log.debug("Could not Paint the polygons. %s" % str(e))
  982. self.app.inform.emit(
  983. "[ERROR] Could not do Paint All. Try a different combination of parameters. "
  984. "Or a different Method of paint\n%s" % str(e))
  985. return
  986. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  987. for k, v in self.paint_tools.items():
  988. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  989. current_uid = int(k)
  990. break
  991. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  992. # temporary list that stored that solid_geometry
  993. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  994. self.paint_tools[current_uid]['data']['name'] = name
  995. cleared_geo[:] = []
  996. geo_obj.options["cnctooldia"] = tool_dia
  997. # this turn on the FlatCAMCNCJob plot for multiple tools
  998. geo_obj.multigeo = True
  999. geo_obj.multitool = True
  1000. geo_obj.tools.clear()
  1001. geo_obj.tools = dict(self.paint_tools)
  1002. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1003. has_solid_geo = 0
  1004. for tooluid in geo_obj.tools:
  1005. if geo_obj.tools[tooluid]['solid_geometry']:
  1006. has_solid_geo += 1
  1007. if has_solid_geo == 0:
  1008. self.app.inform.emit("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1009. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1010. "Change the painting parameters and try again.")
  1011. return
  1012. # Experimental...
  1013. # print("Indexing...", end=' ')
  1014. # geo_obj.make_index()
  1015. self.app.inform.emit("[success] Paint All with Rest-Machining Done.")
  1016. def job_thread(app_obj):
  1017. try:
  1018. if self.rest_cb.isChecked():
  1019. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1020. else:
  1021. app_obj.new_object("geometry", name, gen_paintarea)
  1022. except Exception as e:
  1023. proc.done()
  1024. traceback.print_stack()
  1025. return
  1026. proc.done()
  1027. # focus on Selected Tab
  1028. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1029. self.app.inform.emit("Polygon Paint started ...")
  1030. # Promise object with the new name
  1031. self.app.collection.promise(name)
  1032. # Background
  1033. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1034. def reset_fields(self):
  1035. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))