ToolPaint.py 53 KB

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