ToolPaint.py 48 KB

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