ToolPaint.py 53 KB

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