ToolPaint.py 53 KB

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