ToolProperties.py 25 KB

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