ToolPaint.py 52 KB

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