ToolPaint.py 53 KB

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