ToolProperties.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 appTool import AppTool
  9. from appGUI.GUIElements import FCTree
  10. from shapely.geometry import MultiPolygon, Polygon
  11. from shapely.ops import unary_union
  12. from copy import deepcopy
  13. import math
  14. import logging
  15. import gettext
  16. import appTranslation 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(AppTool):
  23. toolName = _("Properties")
  24. calculations_finished = QtCore.pyqtSignal(float, float, float, float, float, object)
  25. def __init__(self, app):
  26. AppTool.__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.defaults.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. AppTool.run(self)
  77. self.set_tool_ui()
  78. self.properties()
  79. def install(self, icon=None, separator=None, **kwargs):
  80. AppTool.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' % _("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. # make sure that the FCTree widget columns are resized to content
  103. self.treeWidget.resize_sig.emit()
  104. self.app.ui.notebook.setTabText(2, _("Properties Tool"))
  105. def addItems(self, obj):
  106. parent = self.treeWidget.invisibleRootItem()
  107. apertures = ''
  108. tools = ''
  109. drills = ''
  110. slots = ''
  111. others = ''
  112. font = QtGui.QFont()
  113. font.setBold(True)
  114. p_color = QtGui.QColor("#000000") if self.app.defaults['global_gray_icons'] is False \
  115. else QtGui.QColor("#FFFFFF")
  116. # main Items categories
  117. obj_type = self.treeWidget.addParent(parent, _('TYPE'), expanded=True, color=p_color, font=font)
  118. obj_name = self.treeWidget.addParent(parent, _('NAME'), expanded=True, color=p_color, font=font)
  119. dims = self.treeWidget.addParent(
  120. parent, _('Dimensions'), expanded=True, color=p_color, font=font)
  121. units = self.treeWidget.addParent(parent, _('Units'), expanded=True, color=p_color, font=font)
  122. options = self.treeWidget.addParent(parent, _('Options'), color=p_color, font=font)
  123. if obj.kind.lower() == 'gerber':
  124. apertures = self.treeWidget.addParent(
  125. parent, _('Apertures'), expanded=True, color=p_color, font=font)
  126. else:
  127. tools = self.treeWidget.addParent(
  128. parent, _('Tools'), expanded=True, color=p_color, font=font)
  129. if obj.kind.lower() == 'excellon':
  130. drills = self.treeWidget.addParent(
  131. parent, _('Drills'), expanded=True, color=p_color, font=font)
  132. slots = self.treeWidget.addParent(
  133. parent, _('Slots'), expanded=True, color=p_color, font=font)
  134. if obj.kind.lower() == 'cncjob':
  135. others = self.treeWidget.addParent(
  136. parent, _('Others'), expanded=True, color=p_color, font=font)
  137. separator = self.treeWidget.addParent(parent, '')
  138. self.treeWidget.addChild(
  139. obj_type, ['%s:' % _('Object Type'), ('%s' % (obj.kind.upper()))], True, font=font, font_items=1)
  140. try:
  141. self.treeWidget.addChild(obj_type,
  142. [
  143. '%s:' % _('Geo Type'),
  144. ('%s' % (
  145. {
  146. False: _("Single-Geo"),
  147. True: _("Multi-Geo")
  148. }[obj.multigeo])
  149. )
  150. ],
  151. True)
  152. except Exception as e:
  153. log.debug("Properties.addItems() --> %s" % str(e))
  154. self.treeWidget.addChild(obj_name, [obj.options['name']])
  155. def job_thread(obj_prop):
  156. self.app.proc_container.new(_("Calculating dimensions ... Please wait."))
  157. length = 0.0
  158. width = 0.0
  159. area = 0.0
  160. copper_area = 0.0
  161. geo = obj_prop.solid_geometry
  162. if geo:
  163. # calculate physical dimensions
  164. try:
  165. xmin, ymin, xmax, ymax = obj_prop.bounds()
  166. length = abs(xmax - xmin)
  167. width = abs(ymax - ymin)
  168. except Exception as ee:
  169. log.debug("PropertiesTool.addItems() -> calculate dimensions --> %s" % str(ee))
  170. # calculate box area
  171. if self.app.defaults['units'].lower() == 'mm':
  172. area = (length * width) / 100
  173. else:
  174. area = length * width
  175. if obj_prop.kind.lower() == 'gerber':
  176. # calculate copper area
  177. try:
  178. for geo_el in geo:
  179. copper_area += geo_el.area
  180. except TypeError:
  181. copper_area += geo.area
  182. copper_area /= 100
  183. else:
  184. xmin = []
  185. ymin = []
  186. xmax = []
  187. ymax = []
  188. if obj_prop.kind.lower() == 'cncjob':
  189. try:
  190. for tool_k in obj_prop.exc_cnc_tools:
  191. x0, y0, x1, y1 = unary_union(obj_prop.exc_cnc_tools[tool_k]['solid_geometry']).bounds
  192. xmin.append(x0)
  193. ymin.append(y0)
  194. xmax.append(x1)
  195. ymax.append(y1)
  196. except Exception as ee:
  197. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  198. try:
  199. for tool_k in obj_prop.cnc_tools:
  200. x0, y0, x1, y1 = unary_union(obj_prop.cnc_tools[tool_k]['solid_geometry']).bounds
  201. xmin.append(x0)
  202. ymin.append(y0)
  203. xmax.append(x1)
  204. ymax.append(y1)
  205. except Exception as ee:
  206. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  207. else:
  208. try:
  209. for tool_k in obj_prop.tools:
  210. x0, y0, x1, y1 = unary_union(obj_prop.tools[tool_k]['solid_geometry']).bounds
  211. xmin.append(x0)
  212. ymin.append(y0)
  213. xmax.append(x1)
  214. ymax.append(y1)
  215. except Exception as ee:
  216. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  217. try:
  218. xmin = min(xmin)
  219. ymin = min(ymin)
  220. xmax = max(xmax)
  221. ymax = max(ymax)
  222. length = abs(xmax - xmin)
  223. width = abs(ymax - ymin)
  224. # calculate box area
  225. if self.app.defaults['units'].lower() == 'mm':
  226. area = (length * width) / 100
  227. else:
  228. area = length * width
  229. if obj_prop.kind.lower() == 'gerber':
  230. # calculate copper area
  231. # create a complete solid_geometry from the tools
  232. geo_tools = []
  233. for tool_k in obj_prop.tools:
  234. if 'solid_geometry' in obj_prop.tools[tool_k]:
  235. for geo_el in obj_prop.tools[tool_k]['solid_geometry']:
  236. geo_tools.append(geo_el)
  237. try:
  238. for geo_el in geo_tools:
  239. copper_area += geo_el.area
  240. except TypeError:
  241. copper_area += geo_tools.area
  242. copper_area /= 100
  243. except Exception as err:
  244. log.debug("Properties.addItems() --> %s" % str(err))
  245. area_chull = 0.0
  246. if obj_prop.kind.lower() != 'cncjob':
  247. # calculate and add convex hull area
  248. if geo:
  249. if isinstance(geo, list) and geo[0] is not None:
  250. if isinstance(geo, MultiPolygon):
  251. env_obj = geo.convex_hull
  252. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  253. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  254. env_obj = unary_union(geo)
  255. env_obj = env_obj.convex_hull
  256. else:
  257. env_obj = unary_union(geo)
  258. env_obj = env_obj.convex_hull
  259. area_chull = env_obj.area
  260. else:
  261. area_chull = 0
  262. else:
  263. try:
  264. area_chull = []
  265. for tool_k in obj_prop.tools:
  266. area_el = unary_union(obj_prop.tools[tool_k]['solid_geometry']).convex_hull
  267. area_chull.append(area_el.area)
  268. area_chull = max(area_chull)
  269. except Exception as er:
  270. area_chull = None
  271. log.debug("Properties.addItems() --> %s" % str(er))
  272. if self.app.defaults['units'].lower() == 'mm' and area_chull:
  273. area_chull = area_chull / 100
  274. if area_chull is None:
  275. area_chull = 0
  276. self.calculations_finished.emit(area, length, width, area_chull, copper_area, dims)
  277. self.app.worker_task.emit({'fcn': job_thread, 'params': [obj]})
  278. # Units items
  279. f_unit = {'in': _('Inch'), 'mm': _('Metric')}[str(self.app.defaults['units'].lower())]
  280. self.treeWidget.addChild(units, ['FlatCAM units:', f_unit], True)
  281. o_unit = {
  282. 'in': _('Inch'),
  283. 'mm': _('Metric'),
  284. 'inch': _('Inch'),
  285. 'metric': _('Metric')
  286. }[str(obj.units_found.lower())]
  287. self.treeWidget.addChild(units, ['Object units:', o_unit], True)
  288. # Options items
  289. for option in obj.options:
  290. if option == 'name':
  291. continue
  292. self.treeWidget.addChild(options, [str(option), str(obj.options[option])], True)
  293. # Items that depend on the object type
  294. if obj.kind.lower() == 'gerber':
  295. temp_ap = {}
  296. for ap in obj.apertures:
  297. temp_ap.clear()
  298. temp_ap = deepcopy(obj.apertures[ap])
  299. temp_ap.pop('geometry', None)
  300. solid_nr = 0
  301. follow_nr = 0
  302. clear_nr = 0
  303. if 'geometry' in obj.apertures[ap]:
  304. if obj.apertures[ap]['geometry']:
  305. font.setBold(True)
  306. for el in obj.apertures[ap]['geometry']:
  307. if 'solid' in el:
  308. solid_nr += 1
  309. if 'follow' in el:
  310. follow_nr += 1
  311. if 'clear' in el:
  312. clear_nr += 1
  313. else:
  314. font.setBold(False)
  315. temp_ap['Solid_Geo'] = '%s Polygons' % str(solid_nr)
  316. temp_ap['Follow_Geo'] = '%s LineStrings' % str(follow_nr)
  317. temp_ap['Clear_Geo'] = '%s Polygons' % str(clear_nr)
  318. apid = self.treeWidget.addParent(
  319. apertures, str(ap), expanded=False, color=p_color, font=font)
  320. for key in temp_ap:
  321. self.treeWidget.addChild(apid, [str(key), str(temp_ap[key])], True)
  322. elif obj.kind.lower() == 'excellon':
  323. tot_drill_cnt = 0
  324. tot_slot_cnt = 0
  325. for tool, value in obj.tools.items():
  326. toolid = self.treeWidget.addParent(
  327. tools, str(tool), expanded=False, color=p_color, font=font)
  328. drill_cnt = 0 # variable to store the nr of drills per tool
  329. slot_cnt = 0 # variable to store the nr of slots per tool
  330. # Find no of drills for the current tool
  331. if 'drills' in value and value['drills']:
  332. drill_cnt = len(value['drills'])
  333. tot_drill_cnt += drill_cnt
  334. # Find no of slots for the current tool
  335. if 'slots' in value and value['slots']:
  336. slot_cnt = len(value['slots'])
  337. tot_slot_cnt += slot_cnt
  338. self.treeWidget.addChild(
  339. toolid,
  340. [
  341. _('Diameter'),
  342. '%.*f %s' % (self.decimals, value['tooldia'], self.app.defaults['units'].lower())
  343. ],
  344. True
  345. )
  346. self.treeWidget.addChild(toolid, [_('Drills number'), str(drill_cnt)], True)
  347. self.treeWidget.addChild(toolid, [_('Slots number'), str(slot_cnt)], True)
  348. self.treeWidget.addChild(drills, [_('Drills total number:'), str(tot_drill_cnt)], True)
  349. self.treeWidget.addChild(slots, [_('Slots total number:'), str(tot_slot_cnt)], True)
  350. elif obj.kind.lower() == 'geometry':
  351. for tool, value in obj.tools.items():
  352. geo_tool = self.treeWidget.addParent(
  353. tools, str(tool), expanded=True, color=p_color, font=font)
  354. for k, v in value.items():
  355. if k == 'solid_geometry':
  356. # printed_value = _('Present') if v else _('None')
  357. try:
  358. printed_value = str(len(v))
  359. except (TypeError, AttributeError):
  360. printed_value = '1'
  361. self.treeWidget.addChild(geo_tool, [str(k), printed_value], True)
  362. elif k == 'data':
  363. tool_data = self.treeWidget.addParent(
  364. geo_tool, str(k).capitalize(), color=p_color, font=font)
  365. for data_k, data_v in v.items():
  366. self.treeWidget.addChild(tool_data, [str(data_k), str(data_v)], True)
  367. else:
  368. self.treeWidget.addChild(geo_tool, [str(k), str(v)], True)
  369. elif obj.kind.lower() == 'cncjob':
  370. # for cncjob objects made from gerber or geometry
  371. for tool, value in obj.cnc_tools.items():
  372. geo_tool = self.treeWidget.addParent(
  373. tools, str(tool), expanded=True, color=p_color, font=font)
  374. for k, v in value.items():
  375. if k == 'solid_geometry':
  376. printed_value = _('Present') if v else _('None')
  377. self.treeWidget.addChild(geo_tool, [_("Solid Geometry"), printed_value], True)
  378. elif k == 'gcode':
  379. printed_value = _('Present') if v != '' else _('None')
  380. self.treeWidget.addChild(geo_tool, [_("GCode Text"), printed_value], True)
  381. elif k == 'gcode_parsed':
  382. printed_value = _('Present') if v else _('None')
  383. self.treeWidget.addChild(geo_tool, [_("GCode Geometry"), printed_value], True)
  384. elif k == 'data':
  385. pass
  386. else:
  387. self.treeWidget.addChild(geo_tool, [str(k), str(v)], True)
  388. v = value['data']
  389. tool_data = self.treeWidget.addParent(
  390. geo_tool, _("Tool Data"), color=p_color, font=font)
  391. for data_k, data_v in v.items():
  392. self.treeWidget.addChild(tool_data, [str(data_k).capitalize(), str(data_v)], True)
  393. # for cncjob objects made from excellon
  394. for tool_dia, value in obj.exc_cnc_tools.items():
  395. exc_tool = self.treeWidget.addParent(
  396. tools, str(value['tool']), expanded=False, color=p_color, font=font
  397. )
  398. self.treeWidget.addChild(
  399. exc_tool,
  400. [
  401. _('Diameter'),
  402. '%.*f %s' % (self.decimals, tool_dia, self.app.defaults['units'].lower())
  403. ],
  404. True
  405. )
  406. for k, v in value.items():
  407. if k == 'solid_geometry':
  408. printed_value = _('Present') if v else _('None')
  409. self.treeWidget.addChild(exc_tool, [_("Solid Geometry"), printed_value], True)
  410. elif k == 'nr_drills':
  411. self.treeWidget.addChild(exc_tool, [_("Drills number"), str(v)], True)
  412. elif k == 'nr_slots':
  413. self.treeWidget.addChild(exc_tool, [_("Slots number"), str(v)], True)
  414. elif k == 'gcode':
  415. printed_value = _('Present') if v != '' else _('None')
  416. self.treeWidget.addChild(exc_tool, [_("GCode Text"), printed_value], True)
  417. elif k == 'gcode_parsed':
  418. printed_value = _('Present') if v else _('None')
  419. self.treeWidget.addChild(exc_tool, [_("GCode Geometry"), printed_value], True)
  420. else:
  421. pass
  422. self.treeWidget.addChild(
  423. exc_tool,
  424. [
  425. _("Depth of Cut"),
  426. '%.*f %s' % (
  427. self.decimals,
  428. (obj.z_cut - abs(value['data']['tools_drill_offset'])),
  429. self.app.defaults['units'].lower()
  430. )
  431. ],
  432. True
  433. )
  434. self.treeWidget.addChild(
  435. exc_tool,
  436. [
  437. _("Clearance Height"),
  438. '%.*f %s' % (
  439. self.decimals,
  440. obj.z_move,
  441. self.app.defaults['units'].lower()
  442. )
  443. ],
  444. True
  445. )
  446. self.treeWidget.addChild(
  447. exc_tool,
  448. [
  449. _("Feedrate"),
  450. '%.*f %s/min' % (
  451. self.decimals,
  452. obj.feedrate,
  453. self.app.defaults['units'].lower()
  454. )
  455. ],
  456. True
  457. )
  458. v = value['data']
  459. tool_data = self.treeWidget.addParent(
  460. exc_tool, _("Tool Data"), color=p_color, font=font)
  461. for data_k, data_v in v.items():
  462. self.treeWidget.addChild(tool_data, [str(data_k).capitalize(), str(data_v)], True)
  463. r_time = obj.routing_time
  464. if r_time > 1:
  465. units_lbl = 'min'
  466. else:
  467. r_time *= 60
  468. units_lbl = 'sec'
  469. r_time = math.ceil(float(r_time))
  470. self.treeWidget.addChild(
  471. others,
  472. [
  473. '%s:' % _('Routing time'),
  474. '%.*f %s' % (self.decimals, r_time, units_lbl)],
  475. True
  476. )
  477. self.treeWidget.addChild(
  478. others,
  479. [
  480. '%s:' % _('Travelled distance'),
  481. '%.*f %s' % (self.decimals, obj.travel_distance, self.app.defaults['units'].lower())
  482. ],
  483. True
  484. )
  485. self.treeWidget.addChild(separator, [''])
  486. def show_area_chull(self, area, length, width, chull_area, copper_area, location):
  487. # add dimensions
  488. self.treeWidget.addChild(
  489. location,
  490. ['%s:' % _('Length'), '%.*f %s' % (self.decimals, length, self.app.defaults['units'].lower())],
  491. True
  492. )
  493. self.treeWidget.addChild(
  494. location,
  495. ['%s:' % _('Width'), '%.*f %s' % (self.decimals, width, self.app.defaults['units'].lower())],
  496. True
  497. )
  498. # add box area
  499. if self.app.defaults['units'].lower() == 'mm':
  500. self.treeWidget.addChild(location, ['%s:' % _('Box Area'), '%.*f %s' % (self.decimals, area, 'cm2')], True)
  501. self.treeWidget.addChild(
  502. location,
  503. ['%s:' % _('Convex_Hull Area'), '%.*f %s' % (self.decimals, chull_area, 'cm2')],
  504. True
  505. )
  506. else:
  507. self.treeWidget.addChild(location, ['%s:' % _('Box Area'), '%.*f %s' % (self.decimals, area, 'in2')], True)
  508. self.treeWidget.addChild(
  509. location,
  510. ['%s:' % _('Convex_Hull Area'), '%.*f %s' % (self.decimals, chull_area, 'in2')],
  511. True
  512. )
  513. # add copper area
  514. if self.app.defaults['units'].lower() == 'mm':
  515. self.treeWidget.addChild(
  516. location, ['%s:' % _('Copper Area'), '%.*f %s' % (self.decimals, copper_area, 'cm2')], True)
  517. else:
  518. self.treeWidget.addChild(
  519. location, ['%s:' % _('Copper Area'), '%.*f %s' % (self.decimals, copper_area, 'in2')], True)
  520. # end of file