ToolPaint.py 48 KB

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