ToolPaint.py 53 KB

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