ToolPaint.py 52 KB

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