ToolPaint.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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. import builtins
  14. fcTranslate.apply_language('strings')
  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 = FCEntry2()
  101. # hlay.addWidget(self.addtool_label)
  102. # hlay.addStretch()
  103. hlay.addWidget(self.addtool_entry_lbl)
  104. hlay.addWidget(self.addtool_entry)
  105. grid2 = QtWidgets.QGridLayout()
  106. self.tools_box.addLayout(grid2)
  107. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  108. self.addtool_btn.setToolTip(
  109. _("Add a new tool to the Tool Table\n"
  110. "with the diameter specified above.")
  111. )
  112. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  113. # self.copytool_btn.setToolTip(
  114. # "Copy a selection of tools in the Tool Table\n"
  115. # "by first selecting a row in the Tool Table."
  116. # )
  117. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  118. self.deltool_btn.setToolTip(
  119. _("Delete a selection of tools in the Tool Table\n"
  120. "by first selecting a row(s) in the Tool Table.")
  121. )
  122. grid2.addWidget(self.addtool_btn, 0, 0)
  123. # grid2.addWidget(self.copytool_btn, 0, 1)
  124. grid2.addWidget(self.deltool_btn, 0, 2)
  125. self.empty_label_0 = QtWidgets.QLabel('')
  126. self.tools_box.addWidget(self.empty_label_0)
  127. grid3 = QtWidgets.QGridLayout()
  128. self.tools_box.addLayout(grid3)
  129. # Overlap
  130. ovlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  131. ovlabel.setToolTip(
  132. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  133. "Example:\n"
  134. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  135. "Adjust the value starting with lower values\n"
  136. "and increasing it if areas that should be painted are still \n"
  137. "not painted.\n"
  138. "Lower values = faster processing, faster execution on PCB.\n"
  139. "Higher values = slow processing and slow execution on CNC\n"
  140. "due of too many paths.")
  141. )
  142. grid3.addWidget(ovlabel, 1, 0)
  143. self.paintoverlap_entry = FCEntry()
  144. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  145. # Margin
  146. marginlabel = QtWidgets.QLabel(_('Margin:'))
  147. marginlabel.setToolTip(
  148. _("Distance by which to avoid\n"
  149. "the edges of the polygon to\n"
  150. "be painted.")
  151. )
  152. grid3.addWidget(marginlabel, 2, 0)
  153. self.paintmargin_entry = FCEntry()
  154. grid3.addWidget(self.paintmargin_entry, 2, 1)
  155. # Method
  156. methodlabel = QtWidgets.QLabel(_('Method:'))
  157. methodlabel.setToolTip(
  158. _("Algorithm for non-copper clearing:<BR>"
  159. "<B>Standard</B>: Fixed step inwards.<BR>"
  160. "<B>Seed-based</B>: Outwards from seed.<BR>"
  161. "<B>Line-based</B>: Parallel lines.")
  162. )
  163. grid3.addWidget(methodlabel, 3, 0)
  164. self.paintmethod_combo = RadioSet([
  165. {"label": _("Standard"), "value": "standard"},
  166. {"label": _("Seed-based"), "value": "seed"},
  167. {"label": _("Straight lines"), "value": "lines"}
  168. ], orientation='vertical', stretch=False)
  169. grid3.addWidget(self.paintmethod_combo, 3, 1)
  170. # Connect lines
  171. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  172. pathconnectlabel.setToolTip(
  173. _("Draw lines between resulting\n"
  174. "segments to minimize tool lifts.")
  175. )
  176. grid3.addWidget(pathconnectlabel, 4, 0)
  177. self.pathconnect_cb = FCCheckBox()
  178. grid3.addWidget(self.pathconnect_cb, 4, 1)
  179. contourlabel = QtWidgets.QLabel(_("Contour:"))
  180. contourlabel.setToolTip(
  181. _("Cut around the perimeter of the polygon\n"
  182. "to trim rough edges.")
  183. )
  184. grid3.addWidget(contourlabel, 5, 0)
  185. self.paintcontour_cb = FCCheckBox()
  186. grid3.addWidget(self.paintcontour_cb, 5, 1)
  187. restlabel = QtWidgets.QLabel(_("Rest M.:"))
  188. restlabel.setToolTip(
  189. _("If checked, use 'rest machining'.\n"
  190. "Basically it will clear copper outside PCB features,\n"
  191. "using the biggest tool and continue with the next tools,\n"
  192. "from bigger to smaller, to clear areas of copper that\n"
  193. "could not be cleared by previous tool, until there is\n"
  194. "no more copper to clear or there are no more tools.\n\n"
  195. "If not checked, use the standard algorithm.")
  196. )
  197. grid3.addWidget(restlabel, 6, 0)
  198. self.rest_cb = FCCheckBox()
  199. grid3.addWidget(self.rest_cb, 6, 1)
  200. # Polygon selection
  201. selectlabel = QtWidgets.QLabel(_('Selection:'))
  202. selectlabel.setToolTip(
  203. _("How to select the polygons to paint.<BR>"
  204. "Options:<BR>"
  205. "- <B>Single</B>: left mouse click on the polygon to be painted.<BR>"
  206. "- <B>All</B>: paint all polygons.")
  207. )
  208. grid3.addWidget(selectlabel, 7, 0)
  209. # grid3 = QtWidgets.QGridLayout()
  210. self.selectmethod_combo = RadioSet([
  211. {"label": _("Single"), "value": "single"},
  212. {"label": _("Area"), "value": "area"},
  213. {"label": _("All"), "value": "all"}
  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. self.first_click = False
  233. self.cursor_pos = None
  234. # store here the default data for Geometry Data
  235. self.default_data = {}
  236. self.default_data.update({
  237. "name": '_paint',
  238. "plot": self.app.defaults["geometry_plot"],
  239. "cutz": self.app.defaults["geometry_cutz"],
  240. "vtipdia": 0.1,
  241. "vtipangle": 30,
  242. "travelz": self.app.defaults["geometry_travelz"],
  243. "feedrate": self.app.defaults["geometry_feedrate"],
  244. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  245. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  246. "dwell": self.app.defaults["geometry_dwell"],
  247. "dwelltime": self.app.defaults["geometry_dwelltime"],
  248. "multidepth": self.app.defaults["geometry_multidepth"],
  249. "ppname_g": self.app.defaults["geometry_ppname_g"],
  250. "depthperpass": self.app.defaults["geometry_depthperpass"],
  251. "extracut": self.app.defaults["geometry_extracut"],
  252. "toolchange": self.app.defaults["geometry_toolchange"],
  253. "toolchangez": self.app.defaults["geometry_toolchangez"],
  254. "endz": self.app.defaults["geometry_endz"],
  255. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  256. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  257. "startz": self.app.defaults["geometry_startz"],
  258. "tooldia": self.app.defaults["tools_painttooldia"],
  259. "paintmargin": self.app.defaults["tools_paintmargin"],
  260. "paintmethod": self.app.defaults["tools_paintmethod"],
  261. "selectmethod": self.app.defaults["tools_selectmethod"],
  262. "pathconnect": self.app.defaults["tools_pathconnect"],
  263. "paintcontour": self.app.defaults["tools_paintcontour"],
  264. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  265. })
  266. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  267. # ## Signals
  268. self.addtool_btn.clicked.connect(self.on_tool_add)
  269. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  270. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  271. self.tools_table.itemChanged.connect(self.on_tool_edit)
  272. self.deltool_btn.clicked.connect(self.on_tool_delete)
  273. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  274. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  275. def install(self, icon=None, separator=None, **kwargs):
  276. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  277. def run(self, toggle=True):
  278. self.app.report_usage("ToolPaint()")
  279. if toggle:
  280. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  281. if self.app.ui.splitter.sizes()[0] == 0:
  282. self.app.ui.splitter.setSizes([1, 1])
  283. else:
  284. try:
  285. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  286. self.app.ui.splitter.setSizes([0, 1])
  287. except AttributeError:
  288. pass
  289. else:
  290. if self.app.ui.splitter.sizes()[0] == 0:
  291. self.app.ui.splitter.setSizes([1, 1])
  292. FlatCAMTool.run(self)
  293. self.set_tool_ui()
  294. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  295. def on_radio_selection(self):
  296. if self.selectmethod_combo.get_value() == 'single':
  297. # disable rest-machining for single polygon painting
  298. self.rest_cb.set_value(False)
  299. self.rest_cb.setDisabled(True)
  300. # delete all tools except first row / tool for single polygon painting
  301. list_to_del = list(range(1, self.tools_table.rowCount()))
  302. if list_to_del:
  303. self.on_tool_delete(rows_to_delete=list_to_del)
  304. # disable addTool and delTool
  305. self.addtool_entry.setDisabled(True)
  306. self.addtool_btn.setDisabled(True)
  307. self.deltool_btn.setDisabled(True)
  308. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  309. if self.selectmethod_combo.get_value() == 'area':
  310. # disable rest-machining for single polygon painting
  311. self.rest_cb.set_value(False)
  312. self.rest_cb.setDisabled(True)
  313. else:
  314. self.rest_cb.setDisabled(False)
  315. self.addtool_entry.setDisabled(False)
  316. self.addtool_btn.setDisabled(False)
  317. self.deltool_btn.setDisabled(False)
  318. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  319. def set_tool_ui(self):
  320. self.tools_frame.show()
  321. self.reset_fields()
  322. # ## Init the GUI interface
  323. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  324. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  325. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  326. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  327. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  328. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  329. # updated units
  330. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  331. if self.units == "IN":
  332. self.addtool_entry.set_value(0.039)
  333. else:
  334. self.addtool_entry.set_value(1)
  335. self.tools_table.setupContextMenu()
  336. self.tools_table.addContextMenu(
  337. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  338. self.tools_table.addContextMenu(
  339. "Delete", lambda:
  340. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  341. # set the working variables to a known state
  342. self.paint_tools.clear()
  343. self.tooluid = 0
  344. self.default_data.clear()
  345. self.default_data.update({
  346. "name": '_paint',
  347. "plot": self.app.defaults["geometry_plot"],
  348. "cutz": self.app.defaults["geometry_cutz"],
  349. "vtipdia": 0.1,
  350. "vtipangle": 30,
  351. "travelz": self.app.defaults["geometry_travelz"],
  352. "feedrate": self.app.defaults["geometry_feedrate"],
  353. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  354. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  355. "dwell": self.app.defaults["geometry_dwell"],
  356. "dwelltime": self.app.defaults["geometry_dwelltime"],
  357. "multidepth": self.app.defaults["geometry_multidepth"],
  358. "ppname_g": self.app.defaults["geometry_ppname_g"],
  359. "depthperpass": self.app.defaults["geometry_depthperpass"],
  360. "extracut": self.app.defaults["geometry_extracut"],
  361. "toolchange": self.app.defaults["geometry_toolchange"],
  362. "toolchangez": self.app.defaults["geometry_toolchangez"],
  363. "endz": self.app.defaults["geometry_endz"],
  364. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  365. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  366. "startz": self.app.defaults["geometry_startz"],
  367. "tooldia": self.app.defaults["tools_painttooldia"],
  368. "paintmargin": self.app.defaults["tools_paintmargin"],
  369. "paintmethod": self.app.defaults["tools_paintmethod"],
  370. "selectmethod": self.app.defaults["tools_selectmethod"],
  371. "pathconnect": self.app.defaults["tools_pathconnect"],
  372. "paintcontour": self.app.defaults["tools_paintcontour"],
  373. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  374. })
  375. # call on self.on_tool_add() counts as an call to self.build_ui()
  376. # through this, we add a initial row / tool in the tool_table
  377. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  378. # if the Paint Method is "Single" disable the tool table context menu
  379. if self.default_data["selectmethod"] == "single":
  380. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  381. def build_ui(self):
  382. try:
  383. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  384. self.tools_table.itemChanged.disconnect()
  385. except (TypeError, AttributeError):
  386. pass
  387. # updated units
  388. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  389. sorted_tools = []
  390. for k, v in self.paint_tools.items():
  391. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  392. sorted_tools.sort()
  393. n = len(sorted_tools)
  394. self.tools_table.setRowCount(n)
  395. tool_id = 0
  396. for tool_sorted in sorted_tools:
  397. for tooluid_key, tooluid_value in self.paint_tools.items():
  398. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  399. tool_id += 1
  400. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  401. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  402. row_no = tool_id - 1
  403. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  404. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  405. # There are no drill bits in MM with more than 3 decimals diameter
  406. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  407. if self.units == 'MM':
  408. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  409. else:
  410. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  411. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  412. tool_type_item = QtWidgets.QComboBox()
  413. for item in self.tool_type_item_options:
  414. tool_type_item.addItem(item)
  415. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  416. idx = tool_type_item.findText(tooluid_value['tool_type'])
  417. tool_type_item.setCurrentIndex(idx)
  418. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  419. self.tools_table.setItem(row_no, 1, dia) # Diameter
  420. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  421. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  422. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  423. # make the diameter column editable
  424. for row in range(tool_id):
  425. self.tools_table.item(row, 1).setFlags(
  426. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  427. # all the tools are selected by default
  428. self.tools_table.selectColumn(0)
  429. #
  430. self.tools_table.resizeColumnsToContents()
  431. self.tools_table.resizeRowsToContents()
  432. vertical_header = self.tools_table.verticalHeader()
  433. vertical_header.hide()
  434. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  435. horizontal_header = self.tools_table.horizontalHeader()
  436. horizontal_header.setMinimumSectionSize(10)
  437. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  438. horizontal_header.resizeSection(0, 20)
  439. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  440. # self.tools_table.setSortingEnabled(True)
  441. # sort by tool diameter
  442. # self.tools_table.sortItems(1)
  443. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  444. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  445. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  446. self.tools_table.itemChanged.connect(self.on_tool_edit)
  447. def on_tool_add(self, dia=None, muted=None):
  448. try:
  449. self.tools_table.itemChanged.disconnect()
  450. except Exception as e:
  451. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  452. if dia:
  453. tool_dia = dia
  454. else:
  455. try:
  456. tool_dia = float(self.addtool_entry.get_value())
  457. except ValueError:
  458. # try to convert comma to decimal point. if it's still not working error message and return
  459. try:
  460. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  461. except ValueError:
  462. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  463. "use a number."))
  464. return
  465. if tool_dia is None:
  466. self.build_ui()
  467. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  468. return
  469. # construct a list of all 'tooluid' in the self.tools
  470. tool_uid_list = []
  471. for tooluid_key in self.paint_tools:
  472. tool_uid_item = int(tooluid_key)
  473. tool_uid_list.append(tool_uid_item)
  474. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  475. if not tool_uid_list:
  476. max_uid = 0
  477. else:
  478. max_uid = max(tool_uid_list)
  479. self.tooluid = int(max_uid + 1)
  480. tool_dias = []
  481. for k, v in self.paint_tools.items():
  482. for tool_v in v.keys():
  483. if tool_v == 'tooldia':
  484. tool_dias.append(float('%.4f' % v[tool_v]))
  485. if float('%.4f' % tool_dia) in tool_dias:
  486. if muted is None:
  487. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  488. self.tools_table.itemChanged.connect(self.on_tool_edit)
  489. return
  490. else:
  491. if muted is None:
  492. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  493. self.paint_tools.update({
  494. int(self.tooluid): {
  495. 'tooldia': float('%.4f' % tool_dia),
  496. 'offset': 'Path',
  497. 'offset_value': 0.0,
  498. 'type': 'Iso',
  499. 'tool_type': 'V',
  500. 'data': dict(self.default_data),
  501. 'solid_geometry': []
  502. }
  503. })
  504. self.build_ui()
  505. def on_tool_edit(self):
  506. old_tool_dia = ''
  507. try:
  508. self.tools_table.itemChanged.disconnect()
  509. except Exception as e:
  510. log.debug("ToolPaint.on_tool_edit() --> %s" % str(e))
  511. tool_dias = []
  512. for k, v in self.paint_tools.items():
  513. for tool_v in v.keys():
  514. if tool_v == 'tooldia':
  515. tool_dias.append(float('%.4f' % v[tool_v]))
  516. for row in range(self.tools_table.rowCount()):
  517. try:
  518. new_tool_dia = float(self.tools_table.item(row, 1).text())
  519. except ValueError:
  520. # try to convert comma to decimal point. if it's still not working error message and return
  521. try:
  522. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  523. except ValueError:
  524. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  525. "use a number."))
  526. return
  527. tooluid = int(self.tools_table.item(row, 3).text())
  528. # identify the tool that was edited and get it's tooluid
  529. if new_tool_dia not in tool_dias:
  530. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  531. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  532. self.build_ui()
  533. return
  534. else:
  535. # identify the old tool_dia and restore the text in tool table
  536. for k, v in self.paint_tools.items():
  537. if k == tooluid:
  538. old_tool_dia = v['tooldia']
  539. break
  540. restore_dia_item = self.tools_table.item(row, 1)
  541. restore_dia_item.setText(str(old_tool_dia))
  542. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  543. "New diameter value is already in the Tool Table."))
  544. self.build_ui()
  545. # def on_tool_copy(self, all=None):
  546. # try:
  547. # self.tools_table.itemChanged.disconnect()
  548. # except:
  549. # pass
  550. #
  551. # # find the tool_uid maximum value in the self.tools
  552. # uid_list = []
  553. # for key in self.paint_tools:
  554. # uid_list.append(int(key))
  555. # try:
  556. # max_uid = max(uid_list, key=int)
  557. # except ValueError:
  558. # max_uid = 0
  559. #
  560. # if all is None:
  561. # if self.tools_table.selectedItems():
  562. # for current_row in self.tools_table.selectedItems():
  563. # # sometime the header get selected and it has row number -1
  564. # # we don't want to do anything with the header :)
  565. # if current_row.row() < 0:
  566. # continue
  567. # try:
  568. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  569. # max_uid += 1
  570. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  571. # for td in self.paint_tools:
  572. # print("COPIED", self.paint_tools[td])
  573. # self.build_ui()
  574. # except AttributeError:
  575. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  576. # self.build_ui()
  577. # return
  578. # except Exception as e:
  579. # log.debug("on_tool_copy() --> " + str(e))
  580. # # deselect the table
  581. # # self.ui.geo_tools_table.clearSelection()
  582. # else:
  583. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  584. # self.build_ui()
  585. # return
  586. # else:
  587. # # we copy all tools in geo_tools_table
  588. # try:
  589. # temp_tools = dict(self.paint_tools)
  590. # max_uid += 1
  591. # for tooluid in temp_tools:
  592. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  593. # temp_tools.clear()
  594. # self.build_ui()
  595. # except Exception as e:
  596. # log.debug("on_tool_copy() --> " + str(e))
  597. #
  598. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  599. def on_tool_delete(self, rows_to_delete=None, all=None):
  600. try:
  601. self.tools_table.itemChanged.disconnect()
  602. except Exception as e:
  603. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  604. pass
  605. deleted_tools_list = []
  606. if all:
  607. self.paint_tools.clear()
  608. self.build_ui()
  609. return
  610. if rows_to_delete:
  611. try:
  612. for row in rows_to_delete:
  613. tooluid_del = int(self.tools_table.item(row, 3).text())
  614. deleted_tools_list.append(tooluid_del)
  615. except TypeError:
  616. deleted_tools_list.append(rows_to_delete)
  617. for t in deleted_tools_list:
  618. self.paint_tools.pop(t, None)
  619. self.build_ui()
  620. return
  621. try:
  622. if self.tools_table.selectedItems():
  623. for row_sel in self.tools_table.selectedItems():
  624. row = row_sel.row()
  625. if row < 0:
  626. continue
  627. tooluid_del = int(self.tools_table.item(row, 3).text())
  628. deleted_tools_list.append(tooluid_del)
  629. for t in deleted_tools_list:
  630. self.paint_tools.pop(t, None)
  631. except AttributeError:
  632. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  633. return
  634. except Exception as e:
  635. log.debug(str(e))
  636. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  637. self.build_ui()
  638. def on_paint_button_click(self):
  639. self.app.report_usage(_("geometry_on_paint_button"))
  640. # self.app.call_source = 'paint'
  641. try:
  642. overlap = float(self.paintoverlap_entry.get_value())
  643. except ValueError:
  644. # try to convert comma to decimal point. if it's still not working error message and return
  645. try:
  646. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  647. except ValueError:
  648. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  649. "use a number."))
  650. return
  651. if overlap >= 1 or overlap < 0:
  652. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  653. "0 (inclusive) and 1 (exclusive), "))
  654. return
  655. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  656. connect = self.pathconnect_cb.get_value()
  657. contour = self.paintcontour_cb.get_value()
  658. select_method = self.selectmethod_combo.get_value()
  659. self.obj_name = self.object_combo.currentText()
  660. # Get source object.
  661. try:
  662. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  663. except Exception as e:
  664. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  665. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  666. return
  667. if self.paint_obj is None:
  668. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  669. return
  670. # test if the Geometry Object is multigeo and return Fail if True because
  671. # for now Paint don't work on MultiGeo
  672. if self.paint_obj.multigeo is True:
  673. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  674. return 'Fail'
  675. o_name = '%s_multitool_paint' % self.obj_name
  676. if select_method == "all":
  677. self.paint_poly_all(self.paint_obj,
  678. outname=o_name,
  679. overlap=overlap,
  680. connect=connect,
  681. contour=contour)
  682. elif select_method == "single":
  683. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  684. # use the first tool in the tool table; get the diameter
  685. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  686. # To be called after clicking on the plot.
  687. def doit(event):
  688. # do paint single only for left mouse clicks
  689. if event.button == 1:
  690. self.app.inform.emit(_("Painting polygon..."))
  691. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  692. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  693. if self.app.grid_status() == True:
  694. pos = self.app.geo_editor.snap(pos[0], pos[1])
  695. self.paint_poly(self.paint_obj,
  696. inside_pt=[pos[0], pos[1]],
  697. tooldia=tooldia,
  698. overlap=overlap,
  699. connect=connect,
  700. contour=contour)
  701. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  702. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  703. self.app.plotcanvas.vis_connect('mouse_press', doit)
  704. elif select_method == "area":
  705. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the paint area."))
  706. # use the first tool in the tool table; get the diameter
  707. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  708. # To be called after clicking on the plot.
  709. def on_mouse_press(event):
  710. # do paint single only for left mouse clicks
  711. if event.button == 1:
  712. if not self.first_click:
  713. self.first_click = True
  714. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  715. self.cursor_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  716. if self.app.grid_status() == True:
  717. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  718. else:
  719. self.app.inform.emit(_("Done."))
  720. self.first_click = False
  721. self.app.delete_selection_shape()
  722. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  723. if self.app.grid_status() == True:
  724. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  725. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  726. x1, y1 = curr_pos[0], curr_pos[1]
  727. pt1 = (x0, y0)
  728. pt2 = (x1, y0)
  729. pt3 = (x1, y1)
  730. pt4 = (x0, y1)
  731. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  732. self.paint_poly_area(obj=self.paint_obj,
  733. sel_obj= sel_rect,
  734. outname=o_name,
  735. overlap=overlap,
  736. connect=connect,
  737. contour=contour)
  738. self.app.plotcanvas.vis_disconnect('mouse_press', on_mouse_press)
  739. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  740. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  741. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  742. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  743. # called on mouse move
  744. def on_mouse_move(event):
  745. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  746. self.app.app_cursor.enabled = False
  747. if self.app.grid_status() == True:
  748. self.app.app_cursor.enabled = True
  749. # Update cursor
  750. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  751. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  752. symbol='++', edge_color='black', size=20)
  753. if self.first_click:
  754. self.app.delete_selection_shape()
  755. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  756. coords=(curr_pos[0], curr_pos[1]),
  757. face_alpha=0.0)
  758. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  759. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  760. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  761. self.app.plotcanvas.vis_connect('mouse_press', on_mouse_press)
  762. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  763. def paint_poly(self, obj, inside_pt, tooldia, overlap, outname=None, connect=True, contour=True):
  764. """
  765. Paints a polygon selected by clicking on its interior.
  766. Note:
  767. * The margin is taken directly from the form.
  768. :param obj: painted object
  769. :param inside_pt: [x, y]
  770. :param tooldia: Diameter of the painting tool
  771. :param overlap: Overlap of the tool between passes.
  772. :param outname: Name of the resulting Geometry Object.
  773. :param connect: Connect lines to avoid tool lifts.
  774. :param contour: Paint around the edges.
  775. :return: None
  776. """
  777. # Which polygon.
  778. # poly = find_polygon(self.solid_geometry, inside_pt)
  779. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  780. paint_method = self.paintmethod_combo.get_value()
  781. try:
  782. paint_margin = float(self.paintmargin_entry.get_value())
  783. except ValueError:
  784. # try to convert comma to decimal point. if it's still not working error message and return
  785. try:
  786. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  787. except ValueError:
  788. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  789. "use a number."))
  790. return
  791. # No polygon?
  792. if poly is None:
  793. self.app.log.warning('No polygon found.')
  794. self.app.inform.emit(_('[WARNING] No polygon found.'))
  795. return
  796. proc = self.app.proc_container.new(_("Painting polygon."))
  797. name = outname if outname else self.obj_name + "_paint"
  798. # Initializes the new geometry object
  799. def gen_paintarea(geo_obj, app_obj):
  800. assert isinstance(geo_obj, FlatCAMGeometry), \
  801. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  802. # assert isinstance(app_obj, App)
  803. def paint_p(polyg):
  804. if paint_method == "seed":
  805. # Type(cp) == FlatCAMRTreeStorage | None
  806. cpoly = self.clear_polygon2(polyg,
  807. tooldia=tooldia,
  808. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  809. overlap=overlap,
  810. contour=contour,
  811. connect=connect)
  812. elif paint_method == "lines":
  813. # Type(cp) == FlatCAMRTreeStorage | None
  814. cpoly = self.clear_polygon3(polyg,
  815. tooldia=tooldia,
  816. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  817. overlap=overlap,
  818. contour=contour,
  819. connect=connect)
  820. else:
  821. # Type(cp) == FlatCAMRTreeStorage | None
  822. cpoly = self.clear_polygon(polyg,
  823. tooldia=tooldia,
  824. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  825. overlap=overlap,
  826. contour=contour,
  827. connect=connect)
  828. if cpoly is not None:
  829. geo_obj.solid_geometry += list(cpoly.get_objects())
  830. return cpoly
  831. else:
  832. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  833. return None
  834. geo_obj.solid_geometry = []
  835. try:
  836. a, b, c, d = poly.bounds
  837. geo_obj.options['xmin'] = a
  838. geo_obj.options['ymin'] = b
  839. geo_obj.options['xmax'] = c
  840. geo_obj.options['ymax'] = d
  841. except Exception as e:
  842. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  843. return
  844. try:
  845. poly_buf = poly.buffer(-paint_margin)
  846. if isinstance(poly_buf, MultiPolygon):
  847. cp = []
  848. for pp in poly_buf:
  849. cp.append(paint_p(pp))
  850. else:
  851. cp = paint_p(poly_buf)
  852. except Exception as e:
  853. log.debug("Could not Paint the polygons. %s" % str(e))
  854. self.app.inform.emit(
  855. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  856. "Or a different strategy of paint\n%s") % str(e))
  857. return
  858. if cp is not None:
  859. if isinstance(cp, list):
  860. for x in cp:
  861. geo_obj.solid_geometry += list(x.get_objects())
  862. else:
  863. geo_obj.solid_geometry = list(cp.get_objects())
  864. geo_obj.options["cnctooldia"] = str(tooldia)
  865. # this turn on the FlatCAMCNCJob plot for multiple tools
  866. geo_obj.multigeo = False
  867. geo_obj.multitool = True
  868. current_uid = int(self.tools_table.item(0, 3).text())
  869. for k, v in self.paint_tools.items():
  870. if k == current_uid:
  871. v['data']['name'] = name
  872. geo_obj.tools = dict(self.paint_tools)
  873. # Experimental...
  874. # print("Indexing...", end=' ')
  875. # geo_obj.make_index()
  876. # if errors == 0:
  877. # print("[success] Paint single polygon Done")
  878. # self.app.inform.emit("[success] Paint single polygon Done")
  879. # else:
  880. # print("[WARNING] Paint single polygon done with errors")
  881. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  882. # "%d area(s) could not be painted.\n"
  883. # "Use different paint parameters or edit the paint geometry and correct"
  884. # "the issue."
  885. # % errors)
  886. def job_thread(app_obj):
  887. try:
  888. app_obj.new_object("geometry", name, gen_paintarea)
  889. except Exception as e:
  890. proc.done()
  891. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  892. return
  893. proc.done()
  894. # focus on Selected Tab
  895. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  896. self.app.inform.emit(_("Polygon Paint started ..."))
  897. # Promise object with the new name
  898. self.app.collection.promise(name)
  899. # Background
  900. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  901. def paint_poly_all(self, obj, overlap, outname=None, connect=True, contour=True):
  902. """
  903. Paints all polygons in this object.
  904. :param obj: painted object
  905. :param overlap:
  906. :param outname:
  907. :param connect: Connect lines to avoid tool lifts.
  908. :param contour: Paint around the edges.
  909. :return:
  910. """
  911. paint_method = self.paintmethod_combo.get_value()
  912. try:
  913. paint_margin = float(self.paintmargin_entry.get_value())
  914. except ValueError:
  915. # try to convert comma to decimal point. if it's still not working error message and return
  916. try:
  917. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  918. except ValueError:
  919. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  920. "use a number."))
  921. return
  922. proc = self.app.proc_container.new(_("Painting polygon..."))
  923. name = outname if outname else self.obj_name + "_paint"
  924. over = overlap
  925. conn = connect
  926. cont = contour
  927. # This is a recursive generator of individual Polygons.
  928. # Note: Double check correct implementation. Might exit
  929. # early if it finds something that is not a Polygon?
  930. # def recurse(geo):
  931. # try:
  932. # for subg in geo:
  933. # for subsubg in recurse(subg):
  934. # yield subsubg
  935. # except TypeError:
  936. # if isinstance(geo, Polygon):
  937. # yield geo
  938. #
  939. # raise StopIteration
  940. def recurse(geometry, reset=True):
  941. """
  942. Creates a list of non-iterable linear geometry objects.
  943. Results are placed in self.flat_geometry
  944. :param geometry: Shapely type or list or list of list of such.
  945. :param reset: Clears the contents of self.flat_geometry.
  946. """
  947. if geometry is None:
  948. return
  949. if reset:
  950. self.flat_geometry = []
  951. # ## If iterable, expand recursively.
  952. try:
  953. for geo in geometry:
  954. if geo is not None:
  955. recurse(geometry=geo, reset=False)
  956. # ## Not iterable, do the actual indexing and add.
  957. except TypeError:
  958. if isinstance(geometry, LinearRing):
  959. g = Polygon(geometry)
  960. self.flat_geometry.append(g)
  961. else:
  962. self.flat_geometry.append(geometry)
  963. return self.flat_geometry
  964. # Initializes the new geometry object
  965. def gen_paintarea(geo_obj, app_obj):
  966. assert isinstance(geo_obj, FlatCAMGeometry), \
  967. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  968. tool_dia = None
  969. sorted_tools = []
  970. for row in range(self.tools_table.rowCount()):
  971. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  972. sorted_tools.sort(reverse=True)
  973. try:
  974. a, b, c, d = obj.bounds()
  975. geo_obj.options['xmin'] = a
  976. geo_obj.options['ymin'] = b
  977. geo_obj.options['xmax'] = c
  978. geo_obj.options['ymax'] = d
  979. except Exception as e:
  980. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  981. return
  982. total_geometry = []
  983. current_uid = int(1)
  984. geo_obj.solid_geometry = []
  985. for tool_dia in sorted_tools:
  986. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  987. for k, v in self.paint_tools.items():
  988. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  989. current_uid = int(k)
  990. break
  991. for geo in recurse(obj.solid_geometry):
  992. try:
  993. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  994. if not isinstance(geo, Polygon):
  995. continue
  996. poly_buf = geo.buffer(-paint_margin)
  997. if paint_method == "seed":
  998. # Type(cp) == FlatCAMRTreeStorage | None
  999. cp = self.clear_polygon2(poly_buf,
  1000. tooldia=tool_dia,
  1001. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1002. overlap=over,
  1003. contour=cont,
  1004. connect=conn)
  1005. elif paint_method == "lines":
  1006. # Type(cp) == FlatCAMRTreeStorage | None
  1007. cp = self.clear_polygon3(poly_buf,
  1008. tooldia=tool_dia,
  1009. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1010. overlap=over,
  1011. contour=cont,
  1012. connect=conn)
  1013. else:
  1014. # Type(cp) == FlatCAMRTreeStorage | None
  1015. cp = self.clear_polygon(poly_buf,
  1016. tooldia=tool_dia,
  1017. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1018. overlap=over,
  1019. contour=cont,
  1020. connect=conn)
  1021. if cp is not None:
  1022. total_geometry += list(cp.get_objects())
  1023. except Exception as e:
  1024. log.debug("Could not Paint the polygons. %s" % str(e))
  1025. self.app.inform.emit(
  1026. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1027. "Or a different Method of paint\n%s") % str(e))
  1028. return
  1029. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1030. # temporary list that stored that solid_geometry
  1031. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1032. self.paint_tools[current_uid]['data']['name'] = name
  1033. total_geometry[:] = []
  1034. geo_obj.options["cnctooldia"] = str(tool_dia)
  1035. # this turn on the FlatCAMCNCJob plot for multiple tools
  1036. geo_obj.multigeo = True
  1037. geo_obj.multitool = True
  1038. geo_obj.tools.clear()
  1039. geo_obj.tools = dict(self.paint_tools)
  1040. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1041. has_solid_geo = 0
  1042. for tooluid in geo_obj.tools:
  1043. if geo_obj.tools[tooluid]['solid_geometry']:
  1044. has_solid_geo += 1
  1045. if has_solid_geo == 0:
  1046. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1047. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1048. "Change the painting parameters and try again."))
  1049. return
  1050. # Experimental...
  1051. # print("Indexing...", end=' ')
  1052. # geo_obj.make_index()
  1053. self.app.inform.emit(_("[success] Paint All Done."))
  1054. # Initializes the new geometry object
  1055. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1056. assert isinstance(geo_obj, FlatCAMGeometry), \
  1057. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1058. tool_dia = None
  1059. sorted_tools = []
  1060. for row in range(self.tools_table.rowCount()):
  1061. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1062. sorted_tools.sort(reverse=True)
  1063. cleared_geo = []
  1064. current_uid = int(1)
  1065. geo_obj.solid_geometry = []
  1066. try:
  1067. a, b, c, d = obj.bounds()
  1068. geo_obj.options['xmin'] = a
  1069. geo_obj.options['ymin'] = b
  1070. geo_obj.options['xmax'] = c
  1071. geo_obj.options['ymax'] = d
  1072. except Exception as e:
  1073. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1074. return
  1075. for tool_dia in sorted_tools:
  1076. for geo in recurse(obj.solid_geometry):
  1077. try:
  1078. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1079. poly_buf = geo.buffer(-paint_margin)
  1080. cp = None
  1081. if paint_method == "standard":
  1082. # Type(cp) == FlatCAMRTreeStorage | None
  1083. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1084. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1085. overlap=over, contour=cont, connect=conn)
  1086. elif paint_method == "seed":
  1087. # Type(cp) == FlatCAMRTreeStorage | None
  1088. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1089. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1090. overlap=over, contour=cont, connect=conn)
  1091. elif paint_method == "lines":
  1092. # Type(cp) == FlatCAMRTreeStorage | None
  1093. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1094. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1095. overlap=over, contour=cont, connect=conn)
  1096. if cp is not None:
  1097. cleared_geo += list(cp.get_objects())
  1098. except Exception as e:
  1099. log.debug("Could not Paint the polygons. %s" % str(e))
  1100. self.app.inform.emit(
  1101. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1102. "Or a different Method of paint\n%s") % str(e))
  1103. return
  1104. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1105. for k, v in self.paint_tools.items():
  1106. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1107. current_uid = int(k)
  1108. break
  1109. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1110. # temporary list that stored that solid_geometry
  1111. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1112. self.paint_tools[current_uid]['data']['name'] = name
  1113. cleared_geo[:] = []
  1114. geo_obj.options["cnctooldia"] = str(tool_dia)
  1115. # this turn on the FlatCAMCNCJob plot for multiple tools
  1116. geo_obj.multigeo = True
  1117. geo_obj.multitool = True
  1118. geo_obj.tools.clear()
  1119. geo_obj.tools = dict(self.paint_tools)
  1120. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1121. has_solid_geo = 0
  1122. for tooluid in geo_obj.tools:
  1123. if geo_obj.tools[tooluid]['solid_geometry']:
  1124. has_solid_geo += 1
  1125. if has_solid_geo == 0:
  1126. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1127. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1128. "Change the painting parameters and try again."))
  1129. return
  1130. # Experimental...
  1131. # print("Indexing...", end=' ')
  1132. # geo_obj.make_index()
  1133. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1134. def job_thread(app_obj):
  1135. try:
  1136. if self.rest_cb.isChecked():
  1137. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1138. else:
  1139. app_obj.new_object("geometry", name, gen_paintarea)
  1140. except Exception as e:
  1141. proc.done()
  1142. traceback.print_stack()
  1143. return
  1144. proc.done()
  1145. # focus on Selected Tab
  1146. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1147. self.app.inform.emit(_("Polygon Paint started ..."))
  1148. # Promise object with the new name
  1149. self.app.collection.promise(name)
  1150. # Background
  1151. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1152. def paint_poly_area(self, obj, sel_obj, overlap, outname=None, connect=True, contour=True):
  1153. """
  1154. Paints all polygons in this object that are within the sel_obj object
  1155. :param obj: painted object
  1156. :param sel_obj: paint only what is inside this object bounds
  1157. :param overlap:
  1158. :param outname:
  1159. :param connect: Connect lines to avoid tool lifts.
  1160. :param contour: Paint around the edges.
  1161. :return:
  1162. """
  1163. paint_method = self.paintmethod_combo.get_value()
  1164. try:
  1165. paint_margin = float(self.paintmargin_entry.get_value())
  1166. except ValueError:
  1167. # try to convert comma to decimal point. if it's still not working error message and return
  1168. try:
  1169. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1170. except ValueError:
  1171. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1172. "use a number."))
  1173. return
  1174. proc = self.app.proc_container.new(_("Painting polygon..."))
  1175. name = outname if outname else self.obj_name + "_paint"
  1176. over = overlap
  1177. conn = connect
  1178. cont = contour
  1179. def recurse(geometry, reset=True):
  1180. """
  1181. Creates a list of non-iterable linear geometry objects.
  1182. Results are placed in self.flat_geometry
  1183. :param geometry: Shapely type or list or list of list of such.
  1184. :param reset: Clears the contents of self.flat_geometry.
  1185. """
  1186. if geometry is None:
  1187. return
  1188. if reset:
  1189. self.flat_geometry = []
  1190. # ## If iterable, expand recursively.
  1191. try:
  1192. for geo in geometry:
  1193. if geo is not None:
  1194. recurse(geometry=geo, reset=False)
  1195. # ## Not iterable, do the actual indexing and add.
  1196. except TypeError:
  1197. if isinstance(geometry, LinearRing):
  1198. g = Polygon(geometry)
  1199. self.flat_geometry.append(g)
  1200. else:
  1201. self.flat_geometry.append(geometry)
  1202. return self.flat_geometry
  1203. # Initializes the new geometry object
  1204. def gen_paintarea(geo_obj, app_obj):
  1205. assert isinstance(geo_obj, FlatCAMGeometry), \
  1206. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1207. tool_dia = None
  1208. sorted_tools = []
  1209. for row in range(self.tools_table.rowCount()):
  1210. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1211. sorted_tools.sort(reverse=True)
  1212. geo_to_paint = []
  1213. for poly in obj.solid_geometry:
  1214. new_pol = poly.intersection(sel_obj)
  1215. geo_to_paint.append(new_pol)
  1216. try:
  1217. a, b, c, d = self.paint_bounds(geo_to_paint)
  1218. geo_obj.options['xmin'] = a
  1219. geo_obj.options['ymin'] = b
  1220. geo_obj.options['xmax'] = c
  1221. geo_obj.options['ymax'] = d
  1222. except Exception as e:
  1223. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1224. return
  1225. total_geometry = []
  1226. current_uid = int(1)
  1227. geo_obj.solid_geometry = []
  1228. for tool_dia in sorted_tools:
  1229. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1230. for k, v in self.paint_tools.items():
  1231. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1232. current_uid = int(k)
  1233. break
  1234. for geo in recurse(geo_to_paint):
  1235. try:
  1236. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1237. if not isinstance(geo, Polygon):
  1238. continue
  1239. poly_buf = geo.buffer(-paint_margin)
  1240. if paint_method == "seed":
  1241. # Type(cp) == FlatCAMRTreeStorage | None
  1242. cp = self.clear_polygon2(poly_buf,
  1243. tooldia=tool_dia,
  1244. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1245. overlap=over,
  1246. contour=cont,
  1247. connect=conn)
  1248. elif paint_method == "lines":
  1249. # Type(cp) == FlatCAMRTreeStorage | None
  1250. cp = self.clear_polygon3(poly_buf,
  1251. tooldia=tool_dia,
  1252. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1253. overlap=over,
  1254. contour=cont,
  1255. connect=conn)
  1256. else:
  1257. # Type(cp) == FlatCAMRTreeStorage | None
  1258. cp = self.clear_polygon(poly_buf,
  1259. tooldia=tool_dia,
  1260. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1261. overlap=over,
  1262. contour=cont,
  1263. connect=conn)
  1264. if cp is not None:
  1265. total_geometry += list(cp.get_objects())
  1266. except Exception as e:
  1267. log.debug("Could not Paint the polygons. %s" % str(e))
  1268. self.app.inform.emit(
  1269. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1270. "Or a different Method of paint\n%s") % str(e))
  1271. return
  1272. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1273. # temporary list that stored that solid_geometry
  1274. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1275. self.paint_tools[current_uid]['data']['name'] = name
  1276. total_geometry[:] = []
  1277. geo_obj.options["cnctooldia"] = str(tool_dia)
  1278. # this turn on the FlatCAMCNCJob plot for multiple tools
  1279. geo_obj.multigeo = True
  1280. geo_obj.multitool = True
  1281. geo_obj.tools.clear()
  1282. geo_obj.tools = dict(self.paint_tools)
  1283. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1284. has_solid_geo = 0
  1285. for tooluid in geo_obj.tools:
  1286. if geo_obj.tools[tooluid]['solid_geometry']:
  1287. has_solid_geo += 1
  1288. if has_solid_geo == 0:
  1289. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1290. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1291. "Change the painting parameters and try again."))
  1292. return
  1293. # Experimental...
  1294. # print("Indexing...", end=' ')
  1295. # geo_obj.make_index()
  1296. self.app.inform.emit(_("[success] Paint All Done."))
  1297. # Initializes the new geometry object
  1298. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1299. assert isinstance(geo_obj, FlatCAMGeometry), \
  1300. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1301. tool_dia = None
  1302. sorted_tools = []
  1303. for row in range(self.tools_table.rowCount()):
  1304. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1305. sorted_tools.sort(reverse=True)
  1306. cleared_geo = []
  1307. current_uid = int(1)
  1308. geo_obj.solid_geometry = []
  1309. try:
  1310. a, b, c, d = obj.bounds()
  1311. geo_obj.options['xmin'] = a
  1312. geo_obj.options['ymin'] = b
  1313. geo_obj.options['xmax'] = c
  1314. geo_obj.options['ymax'] = d
  1315. except Exception as e:
  1316. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1317. return
  1318. for tool_dia in sorted_tools:
  1319. for geo in recurse(obj.solid_geometry):
  1320. try:
  1321. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1322. poly_buf = geo.buffer(-paint_margin)
  1323. cp = None
  1324. if paint_method == "standard":
  1325. # Type(cp) == FlatCAMRTreeStorage | None
  1326. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1327. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1328. overlap=over, contour=cont, connect=conn)
  1329. elif paint_method == "seed":
  1330. # Type(cp) == FlatCAMRTreeStorage | None
  1331. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1332. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1333. overlap=over, contour=cont, connect=conn)
  1334. elif paint_method == "lines":
  1335. # Type(cp) == FlatCAMRTreeStorage | None
  1336. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1337. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1338. overlap=over, contour=cont, connect=conn)
  1339. if cp is not None:
  1340. cleared_geo += list(cp.get_objects())
  1341. except Exception as e:
  1342. log.debug("Could not Paint the polygons. %s" % str(e))
  1343. self.app.inform.emit(
  1344. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1345. "Or a different Method of paint\n%s") % str(e))
  1346. return
  1347. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1348. for k, v in self.paint_tools.items():
  1349. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1350. current_uid = int(k)
  1351. break
  1352. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1353. # temporary list that stored that solid_geometry
  1354. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1355. self.paint_tools[current_uid]['data']['name'] = name
  1356. cleared_geo[:] = []
  1357. geo_obj.options["cnctooldia"] = str(tool_dia)
  1358. # this turn on the FlatCAMCNCJob plot for multiple tools
  1359. geo_obj.multigeo = True
  1360. geo_obj.multitool = True
  1361. geo_obj.tools.clear()
  1362. geo_obj.tools = dict(self.paint_tools)
  1363. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1364. has_solid_geo = 0
  1365. for tooluid in geo_obj.tools:
  1366. if geo_obj.tools[tooluid]['solid_geometry']:
  1367. has_solid_geo += 1
  1368. if has_solid_geo == 0:
  1369. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1370. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1371. "Change the painting parameters and try again."))
  1372. return
  1373. # Experimental...
  1374. # print("Indexing...", end=' ')
  1375. # geo_obj.make_index()
  1376. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1377. def job_thread(app_obj):
  1378. try:
  1379. if self.rest_cb.isChecked():
  1380. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1381. else:
  1382. app_obj.new_object("geometry", name, gen_paintarea)
  1383. except Exception as e:
  1384. proc.done()
  1385. traceback.print_stack()
  1386. return
  1387. proc.done()
  1388. # focus on Selected Tab
  1389. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1390. self.app.inform.emit(_("Polygon Paint started ..."))
  1391. # Promise object with the new name
  1392. self.app.collection.promise(name)
  1393. # Background
  1394. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1395. @staticmethod
  1396. def paint_bounds(geometry):
  1397. def bounds_rec(o):
  1398. if type(o) is list:
  1399. minx = Inf
  1400. miny = Inf
  1401. maxx = -Inf
  1402. maxy = -Inf
  1403. for k in o:
  1404. try:
  1405. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1406. except Exception as e:
  1407. log.debug("ToolPaint.bounds() --> %s" % str(e))
  1408. return
  1409. minx = min(minx, minx_)
  1410. miny = min(miny, miny_)
  1411. maxx = max(maxx, maxx_)
  1412. maxy = max(maxy, maxy_)
  1413. return minx, miny, maxx, maxy
  1414. else:
  1415. # it's a Shapely object, return it's bounds
  1416. return o.bounds
  1417. return bounds_rec(geometry)
  1418. def reset_fields(self):
  1419. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))