ToolPaint.py 50 KB

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