ToolProperties.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtGui, QtCore, QtWidgets
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import FCTree
  10. from shapely.geometry import MultiPolygon, Polygon
  11. from shapely.ops import cascaded_union
  12. from copy import deepcopy
  13. import math
  14. import logging
  15. import gettext
  16. import FlatCAMTranslation as fcTranslate
  17. import builtins
  18. fcTranslate.apply_language('strings')
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. log = logging.getLogger('base')
  22. class Properties(FlatCAMTool):
  23. toolName = _("Properties")
  24. calculations_finished = QtCore.pyqtSignal(float, float, float, float, float, object)
  25. def __init__(self, app):
  26. FlatCAMTool.__init__(self, app)
  27. self.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
  28. self.decimals = self.app.decimals
  29. # this way I can hide/show the frame
  30. self.properties_frame = QtWidgets.QFrame()
  31. self.properties_frame.setContentsMargins(0, 0, 0, 0)
  32. self.layout.addWidget(self.properties_frame)
  33. self.properties_box = QtWidgets.QVBoxLayout()
  34. self.properties_box.setContentsMargins(0, 0, 0, 0)
  35. self.properties_frame.setLayout(self.properties_box)
  36. # ## Title
  37. title_label = QtWidgets.QLabel("%s" % self.toolName)
  38. title_label.setStyleSheet("""
  39. QLabel
  40. {
  41. font-size: 16px;
  42. font-weight: bold;
  43. }
  44. """)
  45. self.properties_box.addWidget(title_label)
  46. # self.layout.setMargin(0) # PyQt4
  47. self.properties_box.setContentsMargins(0, 0, 0, 0) # PyQt5
  48. self.vlay = QtWidgets.QVBoxLayout()
  49. self.properties_box.addLayout(self.vlay)
  50. self.treeWidget = FCTree(columns=2)
  51. self.vlay.addWidget(self.treeWidget)
  52. self.vlay.setStretch(0, 0)
  53. self.calculations_finished.connect(self.show_area_chull)
  54. def run(self, toggle=True):
  55. self.app.report_usage("ToolProperties()")
  56. if self.app.tool_tab_locked is True:
  57. return
  58. if toggle:
  59. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  60. if self.app.ui.splitter.sizes()[0] == 0:
  61. self.app.ui.splitter.setSizes([1, 1])
  62. else:
  63. try:
  64. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  65. # if tab is populated with the tool but it does not have the focus, focus on it
  66. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  67. # focus on Tool Tab
  68. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  69. else:
  70. self.app.ui.splitter.setSizes([0, 1])
  71. except AttributeError:
  72. pass
  73. else:
  74. if self.app.ui.splitter.sizes()[0] == 0:
  75. self.app.ui.splitter.setSizes([1, 1])
  76. FlatCAMTool.run(self)
  77. self.set_tool_ui()
  78. self.properties()
  79. def install(self, icon=None, separator=None, **kwargs):
  80. FlatCAMTool.install(self, icon, separator, shortcut='P', **kwargs)
  81. def set_tool_ui(self):
  82. # this reset the TreeWidget
  83. self.treeWidget.clear()
  84. self.properties_frame.show()
  85. def properties(self):
  86. obj_list = self.app.collection.get_selected()
  87. if not obj_list:
  88. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Properties Tool was not displayed. No object selected."))
  89. self.app.ui.notebook.setTabText(2, _("Tools"))
  90. self.properties_frame.hide()
  91. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  92. return
  93. # delete the selection shape, if any
  94. try:
  95. self.app.delete_selection_shape()
  96. except Exception as e:
  97. log.debug("ToolProperties.Properties.properties() --> %s" % str(e))
  98. # populate the properties items
  99. for obj in obj_list:
  100. self.addItems(obj)
  101. self.app.inform.emit('[success] %s' % _("Object Properties are displayed."))
  102. self.app.ui.notebook.setTabText(2, _("Properties Tool"))
  103. def addItems(self, obj):
  104. parent = self.treeWidget.invisibleRootItem()
  105. apertures = ''
  106. tools = ''
  107. drills = ''
  108. slots = ''
  109. others = ''
  110. font = QtGui.QFont()
  111. font.setBold(True)
  112. # main Items categories
  113. obj_type = self.treeWidget.addParent(parent, _('TYPE'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  114. obj_name = self.treeWidget.addParent(parent, _('NAME'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  115. dims = self.treeWidget.addParent(
  116. parent, _('Dimensions'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  117. units = self.treeWidget.addParent(parent, _('Units'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  118. options = self.treeWidget.addParent(parent, _('Options'), color=QtGui.QColor("#000000"), font=font)
  119. if obj.kind.lower() == 'gerber':
  120. apertures = self.treeWidget.addParent(
  121. parent, _('Apertures'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  122. else:
  123. tools = self.treeWidget.addParent(
  124. parent, _('Tools'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  125. if obj.kind.lower() == 'excellon':
  126. drills = self.treeWidget.addParent(
  127. parent, _('Drills'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  128. slots = self.treeWidget.addParent(
  129. parent, _('Slots'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  130. if obj.kind.lower() == 'cncjob':
  131. others = self.treeWidget.addParent(
  132. parent, _('Others'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  133. separator = self.treeWidget.addParent(parent, '')
  134. self.treeWidget.addChild(
  135. obj_type, ['%s:' % _('Object Type'), ('%s' % (obj.kind.upper()))], True, font=font, font_items=1)
  136. try:
  137. self.treeWidget.addChild(obj_type,
  138. [
  139. '%s:' % _('Geo Type'),
  140. ('%s' % (
  141. {
  142. False: _("Single-Geo"),
  143. True: _("Multi-Geo")
  144. }[obj.multigeo])
  145. )
  146. ],
  147. True)
  148. except Exception as e:
  149. log.debug("Properties.addItems() --> %s" % str(e))
  150. self.treeWidget.addChild(obj_name, [obj.options['name']])
  151. def job_thread(obj_prop):
  152. proc = self.app.proc_container.new(_("Calculating dimensions ... Please wait."))
  153. length = 0.0
  154. width = 0.0
  155. area = 0.0
  156. copper_area = 0.0
  157. geo = obj_prop.solid_geometry
  158. if geo:
  159. # calculate physical dimensions
  160. try:
  161. xmin, ymin, xmax, ymax = obj_prop.bounds()
  162. length = abs(xmax - xmin)
  163. width = abs(ymax - ymin)
  164. except Exception as ee:
  165. log.debug("PropertiesTool.addItems() -> calculate dimensions --> %s" % str(ee))
  166. # calculate box area
  167. if self.app.defaults['units'].lower() == 'mm':
  168. area = (length * width) / 100
  169. else:
  170. area = length * width
  171. if obj_prop.kind.lower() == 'gerber':
  172. # calculate copper area
  173. try:
  174. for geo_el in geo:
  175. copper_area += geo_el.area
  176. except TypeError:
  177. copper_area += geo.area
  178. copper_area /= 100
  179. else:
  180. xmin = []
  181. ymin = []
  182. xmax = []
  183. ymax = []
  184. if obj_prop.kind.lower() == 'cncjob':
  185. try:
  186. for tool_k in obj_prop.exc_cnc_tools:
  187. x0, y0, x1, y1 = cascaded_union(obj_prop.exc_cnc_tools[tool_k]['solid_geometry']).bounds
  188. xmin.append(x0)
  189. ymin.append(y0)
  190. xmax.append(x1)
  191. ymax.append(y1)
  192. except Exception as ee:
  193. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  194. try:
  195. for tool_k in obj_prop.cnc_tools:
  196. x0, y0, x1, y1 = cascaded_union(obj_prop.cnc_tools[tool_k]['solid_geometry']).bounds
  197. xmin.append(x0)
  198. ymin.append(y0)
  199. xmax.append(x1)
  200. ymax.append(y1)
  201. except Exception as ee:
  202. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  203. else:
  204. try:
  205. for tool_k in obj_prop.tools:
  206. x0, y0, x1, y1 = cascaded_union(obj_prop.tools[tool_k]['solid_geometry']).bounds
  207. xmin.append(x0)
  208. ymin.append(y0)
  209. xmax.append(x1)
  210. ymax.append(y1)
  211. except Exception as ee:
  212. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  213. try:
  214. xmin = min(xmin)
  215. ymin = min(ymin)
  216. xmax = max(xmax)
  217. ymax = max(ymax)
  218. length = abs(xmax - xmin)
  219. width = abs(ymax - ymin)
  220. # calculate box area
  221. if self.app.defaults['units'].lower() == 'mm':
  222. area = (length * width) / 100
  223. else:
  224. area = length * width
  225. if obj_prop.kind.lower() == 'gerber':
  226. # calculate copper area
  227. # create a complete solid_geometry from the tools
  228. geo_tools = list()
  229. for tool_k in obj_prop.tools:
  230. if 'solid_geometry' in obj_prop.tools[tool_k]:
  231. for geo_el in obj_prop.tools[tool_k]['solid_geometry']:
  232. geo_tools.append(geo_el)
  233. try:
  234. for geo_el in geo_tools:
  235. copper_area += geo_el.area
  236. except TypeError:
  237. copper_area += geo_tools.area
  238. copper_area /= 100
  239. except Exception as err:
  240. log.debug("Properties.addItems() --> %s" % str(err))
  241. area_chull = 0.0
  242. if obj_prop.kind.lower() != 'cncjob':
  243. # calculate and add convex hull area
  244. if geo:
  245. if isinstance(geo, list) and geo[0] is not None:
  246. if isinstance(geo, MultiPolygon):
  247. env_obj = geo.convex_hull
  248. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  249. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  250. env_obj = cascaded_union(geo)
  251. env_obj = env_obj.convex_hull
  252. else:
  253. env_obj = cascaded_union(geo)
  254. env_obj = env_obj.convex_hull
  255. area_chull = env_obj.area
  256. else:
  257. area_chull = 0
  258. else:
  259. try:
  260. area_chull = []
  261. for tool_k in obj_prop.tools:
  262. area_el = cascaded_union(obj_prop.tools[tool_k]['solid_geometry']).convex_hull
  263. area_chull.append(area_el.area)
  264. area_chull = max(area_chull)
  265. except Exception as er:
  266. area_chull = None
  267. log.debug("Properties.addItems() --> %s" % str(er))
  268. if self.app.defaults['units'].lower() == 'mm' and area_chull:
  269. area_chull = area_chull / 100
  270. if area_chull is None:
  271. area_chull = 0
  272. self.calculations_finished.emit(area, length, width, area_chull, copper_area, dims)
  273. self.app.worker_task.emit({'fcn': job_thread, 'params': [obj]})
  274. # Units items
  275. f_unit = {'in': _('Inch'), 'mm': _('Metric')}[str(self.app.defaults['units'].lower())]
  276. self.treeWidget.addChild(units, ['FlatCAM units:', f_unit], True)
  277. o_unit = {
  278. 'in': _('Inch'),
  279. 'mm': _('Metric'),
  280. 'inch': _('Inch'),
  281. 'metric': _('Metric')
  282. }[str(obj.units_found.lower())]
  283. self.treeWidget.addChild(units, ['Object units:', o_unit], True)
  284. # Options items
  285. for option in obj.options:
  286. if option is 'name':
  287. continue
  288. self.treeWidget.addChild(options, [str(option), str(obj.options[option])], True)
  289. # Items that depend on the object type
  290. if obj.kind.lower() == 'gerber':
  291. temp_ap = dict()
  292. for ap in obj.apertures:
  293. temp_ap.clear()
  294. temp_ap = deepcopy(obj.apertures[ap])
  295. temp_ap.pop('geometry', None)
  296. solid_nr = 0
  297. follow_nr = 0
  298. clear_nr = 0
  299. if 'geometry' in obj.apertures[ap]:
  300. if obj.apertures[ap]['geometry']:
  301. font.setBold(True)
  302. for el in obj.apertures[ap]['geometry']:
  303. if 'solid' in el:
  304. solid_nr += 1
  305. if 'follow' in el:
  306. follow_nr += 1
  307. if 'clear' in el:
  308. clear_nr += 1
  309. else:
  310. font.setBold(False)
  311. temp_ap['Solid_Geo'] = '%s Polygons' % str(solid_nr)
  312. temp_ap['Follow_Geo'] = '%s LineStrings' % str(follow_nr)
  313. temp_ap['Clear_Geo'] = '%s Polygons' % str(clear_nr)
  314. apid = self.treeWidget.addParent(
  315. apertures, str(ap), expanded=False, color=QtGui.QColor("#000000"), font=font)
  316. for key in temp_ap:
  317. self.treeWidget.addChild(apid, [str(key), str(temp_ap[key])], True)
  318. elif obj.kind.lower() == 'excellon':
  319. tot_drill_cnt = 0
  320. tot_slot_cnt = 0
  321. for tool, value in obj.tools.items():
  322. toolid = self.treeWidget.addParent(
  323. tools, str(tool), expanded=False, color=QtGui.QColor("#000000"), font=font)
  324. drill_cnt = 0 # variable to store the nr of drills per tool
  325. slot_cnt = 0 # variable to store the nr of slots per tool
  326. # Find no of drills for the current tool
  327. for drill in obj.drills:
  328. if drill['tool'] == tool:
  329. drill_cnt += 1
  330. tot_drill_cnt += drill_cnt
  331. # Find no of slots for the current tool
  332. for slot in obj.slots:
  333. if slot['tool'] == tool:
  334. slot_cnt += 1
  335. tot_slot_cnt += slot_cnt
  336. self.treeWidget.addChild(
  337. toolid,
  338. [
  339. _('Diameter'),
  340. '%.*f %s' % (self.decimals, value['C'], self.app.defaults['units'].lower())
  341. ],
  342. True
  343. )
  344. self.treeWidget.addChild(toolid, [_('Drills number'), str(drill_cnt)], True)
  345. self.treeWidget.addChild(toolid, [_('Slots number'), str(slot_cnt)], True)
  346. self.treeWidget.addChild(drills, [_('Drills total number:'), str(tot_drill_cnt)], True)
  347. self.treeWidget.addChild(slots, [_('Slots total number:'), str(tot_slot_cnt)], True)
  348. elif obj.kind.lower() == 'geometry':
  349. for tool, value in obj.tools.items():
  350. geo_tool = self.treeWidget.addParent(
  351. tools, str(tool), expanded=True, color=QtGui.QColor("#000000"), font=font)
  352. for k, v in value.items():
  353. if k == 'solid_geometry':
  354. # printed_value = _('Present') if v else _('None')
  355. try:
  356. printed_value = str(len(v))
  357. except (TypeError, AttributeError):
  358. printed_value = '1'
  359. self.treeWidget.addChild(geo_tool, [str(k), printed_value], True)
  360. elif k == 'data':
  361. tool_data = self.treeWidget.addParent(
  362. geo_tool, str(k).capitalize(), color=QtGui.QColor("#000000"), font=font)
  363. for data_k, data_v in v.items():
  364. self.treeWidget.addChild(tool_data, [str(data_k), str(data_v)], True)
  365. else:
  366. self.treeWidget.addChild(geo_tool, [str(k), str(v)], True)
  367. elif obj.kind.lower() == 'cncjob':
  368. # for cncjob objects made from gerber or geometry
  369. for tool, value in obj.cnc_tools.items():
  370. geo_tool = self.treeWidget.addParent(
  371. tools, str(tool), expanded=True, color=QtGui.QColor("#000000"), font=font)
  372. for k, v in value.items():
  373. if k == 'solid_geometry':
  374. printed_value = _('Present') if v else _('None')
  375. self.treeWidget.addChild(geo_tool, [_("Solid Geometry"), printed_value], True)
  376. elif k == 'gcode':
  377. printed_value = _('Present') if v != '' else _('None')
  378. self.treeWidget.addChild(geo_tool, [_("GCode Text"), printed_value], True)
  379. elif k == 'gcode_parsed':
  380. printed_value = _('Present') if v else _('None')
  381. self.treeWidget.addChild(geo_tool, [_("GCode Geometry"), printed_value], True)
  382. elif k == 'data':
  383. tool_data = self.treeWidget.addParent(
  384. geo_tool, _("Data"), color=QtGui.QColor("#000000"), font=font)
  385. for data_k, data_v in v.items():
  386. self.treeWidget.addChild(tool_data, [str(data_k).capitalize(), str(data_v)], True)
  387. else:
  388. self.treeWidget.addChild(geo_tool, [str(k), str(v)], True)
  389. # for cncjob objects made from excellon
  390. for tool_dia, value in obj.exc_cnc_tools.items():
  391. exc_tool = self.treeWidget.addParent(
  392. tools, str(value['tool']), expanded=False, color=QtGui.QColor("#000000"), font=font
  393. )
  394. self.treeWidget.addChild(
  395. exc_tool,
  396. [
  397. _('Diameter'),
  398. '%.*f %s' % (self.decimals, tool_dia, self.app.defaults['units'].lower())
  399. ],
  400. True
  401. )
  402. for k, v in value.items():
  403. if k == 'solid_geometry':
  404. printed_value = _('Present') if v else _('None')
  405. self.treeWidget.addChild(exc_tool, [_("Solid Geometry"), printed_value], True)
  406. elif k == 'nr_drills':
  407. self.treeWidget.addChild(exc_tool, [_("Drills number"), str(v)], True)
  408. elif k == 'nr_slots':
  409. self.treeWidget.addChild(exc_tool, [_("Slots number"), str(v)], True)
  410. else:
  411. pass
  412. self.treeWidget.addChild(
  413. exc_tool,
  414. [
  415. _("Depth of Cut"),
  416. '%.*f %s' % (
  417. self.decimals,
  418. (obj.z_cut - abs(obj.tool_offset[tool_dia])),
  419. self.app.defaults['units'].lower()
  420. )
  421. ],
  422. True
  423. )
  424. self.treeWidget.addChild(
  425. exc_tool,
  426. [
  427. _("Clearance Height"),
  428. '%.*f %s' % (
  429. self.decimals,
  430. obj.z_move,
  431. self.app.defaults['units'].lower()
  432. )
  433. ],
  434. True
  435. )
  436. self.treeWidget.addChild(
  437. exc_tool,
  438. [
  439. _("Feedrate"),
  440. '%.*f %s/min' % (
  441. self.decimals,
  442. obj.feedrate,
  443. self.app.defaults['units'].lower()
  444. )
  445. ],
  446. True
  447. )
  448. r_time = obj.routing_time
  449. if r_time > 1:
  450. units_lbl = 'min'
  451. else:
  452. r_time *= 60
  453. units_lbl = 'sec'
  454. r_time = math.ceil(float(r_time))
  455. self.treeWidget.addChild(
  456. others,
  457. [
  458. '%s:' % _('Routing time'),
  459. '%.*f %s' % (self.decimals, r_time, units_lbl)],
  460. True
  461. )
  462. self.treeWidget.addChild(
  463. others,
  464. [
  465. '%s:' % _('Travelled distance'),
  466. '%.*f %s' % (self.decimals, obj.travel_distance, self.app.defaults['units'].lower())
  467. ],
  468. True
  469. )
  470. self.treeWidget.addChild(separator, [''])
  471. def show_area_chull(self, area, length, width, chull_area, copper_area, location):
  472. # add dimensions
  473. self.treeWidget.addChild(
  474. location,
  475. ['%s:' % _('Length'), '%.*f %s' % (self.decimals, length, self.app.defaults['units'].lower())],
  476. True
  477. )
  478. self.treeWidget.addChild(
  479. location,
  480. ['%s:' % _('Width'), '%.*f %s' % (self.decimals, width, self.app.defaults['units'].lower())],
  481. True
  482. )
  483. # add box area
  484. if self.app.defaults['units'].lower() == 'mm':
  485. self.treeWidget.addChild(location, ['%s:' % _('Box Area'), '%.*f %s' % (self.decimals, area, 'cm2')], True)
  486. self.treeWidget.addChild(
  487. location,
  488. ['%s:' % _('Convex_Hull Area'), '%.*f %s' % (self.decimals, chull_area, 'cm2')],
  489. True
  490. )
  491. else:
  492. self.treeWidget.addChild(location, ['%s:' % _('Box Area'), '%.*f %s' % (self.decimals, area, 'in2')], True)
  493. self.treeWidget.addChild(
  494. location,
  495. ['%s:' % _('Convex_Hull Area'), '%.*f %s' % (self.decimals, chull_area, 'in2')],
  496. True
  497. )
  498. # add copper area
  499. if self.app.defaults['units'].lower() == 'mm':
  500. self.treeWidget.addChild(
  501. location, ['%s:' % _('Copper Area'), '%.*f %s' % (self.decimals, copper_area, 'cm2')], True)
  502. else:
  503. self.treeWidget.addChild(
  504. location, ['%s:' % _('Copper Area'), '%.*f %s' % (self.decimals, copper_area, 'in2')], True)
  505. # end of file