ToolPaint.py 54 KB

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