ToolProperties.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Marius Adrian Stanciu (c) #
  5. # Date: 3/10/2019 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from PyQt5 import QtGui, QtCore, QtWidgets
  9. from PyQt5.QtCore import Qt
  10. from FlatCAMTool import FlatCAMTool
  11. from FlatCAMObj import *
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. import builtins
  15. fcTranslate.apply_language('strings')
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class Properties(FlatCAMTool):
  19. toolName = _("Properties")
  20. calculations_finished = pyqtSignal(float, float, float, float, object)
  21. def __init__(self, app):
  22. FlatCAMTool.__init__(self, app)
  23. self.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
  24. # this way I can hide/show the frame
  25. self.properties_frame = QtWidgets.QFrame()
  26. self.properties_frame.setContentsMargins(0, 0, 0, 0)
  27. self.layout.addWidget(self.properties_frame)
  28. self.properties_box = QtWidgets.QVBoxLayout()
  29. self.properties_box.setContentsMargins(0, 0, 0, 0)
  30. self.properties_frame.setLayout(self.properties_box)
  31. # ## Title
  32. title_label = QtWidgets.QLabel("%s" % self.toolName)
  33. title_label.setStyleSheet("""
  34. QLabel
  35. {
  36. font-size: 16px;
  37. font-weight: bold;
  38. }
  39. """)
  40. self.properties_box.addWidget(title_label)
  41. # self.layout.setMargin(0) # PyQt4
  42. self.properties_box.setContentsMargins(0, 0, 0, 0) # PyQt5
  43. self.vlay = QtWidgets.QVBoxLayout()
  44. self.properties_box.addLayout(self.vlay)
  45. self.treeWidget = QtWidgets.QTreeWidget()
  46. self.treeWidget.setColumnCount(2)
  47. self.treeWidget.setHeaderHidden(True)
  48. self.treeWidget.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  49. self.treeWidget.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Expanding)
  50. self.vlay.addWidget(self.treeWidget)
  51. self.vlay.setStretch(0, 0)
  52. self.calculations_finished.connect(self.show_area_chull)
  53. def run(self, toggle=True):
  54. self.app.report_usage("ToolProperties()")
  55. if self.app.tool_tab_locked is True:
  56. return
  57. if toggle:
  58. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  59. if self.app.ui.splitter.sizes()[0] == 0:
  60. self.app.ui.splitter.setSizes([1, 1])
  61. else:
  62. try:
  63. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  64. # if tab is populated with the tool but it does not have the focus, focus on it
  65. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  66. # focus on Tool Tab
  67. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  68. else:
  69. self.app.ui.splitter.setSizes([0, 1])
  70. except AttributeError:
  71. pass
  72. else:
  73. if self.app.ui.splitter.sizes()[0] == 0:
  74. self.app.ui.splitter.setSizes([1, 1])
  75. FlatCAMTool.run(self)
  76. self.set_tool_ui()
  77. self.properties()
  78. def install(self, icon=None, separator=None, **kwargs):
  79. FlatCAMTool.install(self, icon, separator, shortcut='P', **kwargs)
  80. def set_tool_ui(self):
  81. # this reset the TreeWidget
  82. self.treeWidget.clear()
  83. self.properties_frame.show()
  84. def properties(self):
  85. obj_list = self.app.collection.get_selected()
  86. if not obj_list:
  87. self.app.inform.emit(_("[ERROR_NOTCL] Properties Tool was not displayed. No object selected."))
  88. self.app.ui.notebook.setTabText(2, _("Tools"))
  89. self.properties_frame.hide()
  90. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  91. return
  92. for obj in obj_list:
  93. self.addItems(obj)
  94. self.app.inform.emit(_("[success] Object Properties are displayed."))
  95. self.app.ui.notebook.setTabText(2, _("Properties Tool"))
  96. def addItems(self, obj):
  97. parent = self.treeWidget.invisibleRootItem()
  98. apertures = ''
  99. tools = ''
  100. font = QtGui.QFont()
  101. font.setBold(True)
  102. obj_type = self.addParent(parent, _('TYPE'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  103. obj_name = self.addParent(parent, _('NAME'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  104. dims = self.addParent(parent, _('Dimensions'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  105. units = self.addParent(parent, _('Units'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  106. options = self.addParent(parent, _('Options'), color=QtGui.QColor("#000000"), font=font)
  107. if obj.kind.lower() == 'gerber':
  108. apertures = self.addParent(parent, _('Apertures'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  109. else:
  110. tools = self.addParent(parent, _('Tools'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  111. separator = self.addParent(parent, '')
  112. self.addChild(obj_type, ['%s:' % _('Object Type'), ('%s' % (obj.kind.capitalize()))], True)
  113. try:
  114. self.addChild(obj_type,
  115. ['%s:' % _('Geo Type'),
  116. ('%s' % ({False: _("Single-Geo"), True: _("Multi-Geo")}[obj.multigeo]))],
  117. True)
  118. except Exception as e:
  119. log.debug("Properties.addItems() --> %s" % str(e))
  120. self.addChild(obj_name, [obj.options['name']])
  121. def job_thread(obj):
  122. proc = self.app.proc_container.new(_("Calculating dimensions ... Please wait."))
  123. length = 0.0
  124. width = 0.0
  125. area = 0.0
  126. geo = obj.solid_geometry
  127. if geo:
  128. # calculate physical dimensions
  129. try:
  130. xmin, ymin, xmax, ymax = obj.bounds()
  131. length = abs(xmax - xmin)
  132. width = abs(ymax - ymin)
  133. except Exception as e:
  134. log.debug("PropertiesTool.addItems() --> %s" % str(e))
  135. # calculate box area
  136. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  137. area = (length * width) / 100
  138. else:
  139. area = length * width
  140. else:
  141. xmin = []
  142. ymin = []
  143. xmax = []
  144. ymax = []
  145. for tool in obj.tools:
  146. try:
  147. x0, y0, x1, y1 = cascaded_union(obj.tools[tool]['solid_geometry']).bounds
  148. xmin.append(x0)
  149. ymin.append(y0)
  150. xmax.append(x1)
  151. ymax.append(y1)
  152. except Exception as ee:
  153. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  154. try:
  155. xmin = min(xmin)
  156. ymin = min(ymin)
  157. xmax = max(xmax)
  158. ymax = max(ymax)
  159. length = abs(xmax - xmin)
  160. width = abs(ymax - ymin)
  161. # calculate box area
  162. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  163. area = (length * width) / 100
  164. else:
  165. area = length * width
  166. except Exception as e:
  167. log.debug("Properties.addItems() --> %s" % str(e))
  168. area_chull = 0.0
  169. if not isinstance(obj, FlatCAMCNCjob):
  170. # calculate and add convex hull area
  171. if geo:
  172. if isinstance(geo, MultiPolygon):
  173. env_obj = geo.convex_hull
  174. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  175. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  176. env_obj = cascaded_union(obj.solid_geometry)
  177. env_obj = env_obj.convex_hull
  178. else:
  179. env_obj = cascaded_union(obj.solid_geometry)
  180. env_obj = env_obj.convex_hull
  181. area_chull = env_obj.area
  182. else:
  183. try:
  184. area_chull = []
  185. for tool in obj.tools:
  186. area_el = cascaded_union(obj.tools[tool]['solid_geometry']).convex_hull
  187. area_chull.append(area_el.area)
  188. area_chull = max(area_chull)
  189. except Exception as e:
  190. area_chull = None
  191. log.debug("Properties.addItems() --> %s" % str(e))
  192. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  193. area_chull = area_chull / 100
  194. self.calculations_finished.emit(area, length, width, area_chull, dims)
  195. self.app.worker_task.emit({'fcn': job_thread, 'params': [obj]})
  196. self.addChild(units,
  197. ['FlatCAM units:',
  198. {
  199. 'in': _('Inch'),
  200. 'mm': _('Metric')
  201. }
  202. [str(self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower())]
  203. ],
  204. True
  205. )
  206. for option in obj.options:
  207. if option is 'name':
  208. continue
  209. self.addChild(options, [str(option), str(obj.options[option])], True)
  210. if obj.kind.lower() == 'gerber':
  211. temp_ap = dict()
  212. for ap in obj.apertures:
  213. temp_ap.clear()
  214. temp_ap = deepcopy(obj.apertures[ap])
  215. temp_ap.pop('geometry', None)
  216. solid_nr = 0
  217. follow_nr = 0
  218. clear_nr = 0
  219. if 'geometry' in obj.apertures[ap]:
  220. if obj.apertures[ap]['geometry']:
  221. font.setBold(True)
  222. for el in obj.apertures[ap]['geometry']:
  223. if 'solid' in el:
  224. solid_nr += 1
  225. if 'follow' in el:
  226. follow_nr += 1
  227. if 'clear' in el:
  228. clear_nr += 1
  229. else:
  230. font.setBold(False)
  231. temp_ap['Solid_Geo'] = '%s Polygons' % str(solid_nr)
  232. temp_ap['Follow_Geo'] = '%s LineStrings' % str(follow_nr)
  233. temp_ap['Clear_Geo'] = '%s Polygons' % str(clear_nr)
  234. apid = self.addParent(apertures, str(ap), expanded=False, color=QtGui.QColor("#000000"), font=font)
  235. for key in temp_ap:
  236. self.addChild(apid, [str(key), str(temp_ap[key])], True)
  237. elif obj.kind.lower() == 'excellon':
  238. for tool, value in obj.tools.items():
  239. self.addChild(tools, [str(tool), str(value['C'])], True)
  240. elif obj.kind.lower() == 'geometry':
  241. for tool, value in obj.tools.items():
  242. geo_tool = self.addParent(tools, str(tool), expanded=True, color=QtGui.QColor("#000000"), font=font)
  243. for k, v in value.items():
  244. if k == 'solid_geometry':
  245. printed_value = _('Present') if v else _('None')
  246. self.addChild(geo_tool, [str(k), printed_value], True)
  247. elif k == 'data':
  248. tool_data = self.addParent(geo_tool, str(k).capitalize(),
  249. color=QtGui.QColor("#000000"), font=font)
  250. for data_k, data_v in v.items():
  251. self.addChild(tool_data, [str(data_k), str(data_v)], True)
  252. else:
  253. self.addChild(geo_tool, [str(k), str(v)], True)
  254. elif obj.kind.lower() == 'cncjob':
  255. for tool, value in obj.cnc_tools.items():
  256. geo_tool = self.addParent(tools, str(tool), expanded=True, color=QtGui.QColor("#000000"), font=font)
  257. for k, v in value.items():
  258. if k == 'solid_geometry':
  259. printed_value = _('Present') if v else _('None')
  260. self.addChild(geo_tool, [str(k), printed_value], True)
  261. elif k == 'gcode':
  262. printed_value = _('Present') if v != '' else _('None')
  263. self.addChild(geo_tool, [str(k), printed_value], True)
  264. elif k == 'gcode_parsed':
  265. printed_value = _('Present') if v else _('None')
  266. self.addChild(geo_tool, [str(k), printed_value], True)
  267. elif k == 'data':
  268. tool_data = self.addParent(geo_tool, str(k).capitalize(),
  269. color=QtGui.QColor("#000000"), font=font)
  270. for data_k, data_v in v.items():
  271. self.addChild(tool_data, [str(data_k), str(data_v)], True)
  272. else:
  273. self.addChild(geo_tool, [str(k), str(v)], True)
  274. self.addChild(separator, [''])
  275. def addParent(self, parent, title, expanded=False, color=None, font=None):
  276. item = QtWidgets.QTreeWidgetItem(parent, [title])
  277. item.setChildIndicatorPolicy(QtWidgets.QTreeWidgetItem.ShowIndicator)
  278. item.setExpanded(expanded)
  279. if color is not None:
  280. # item.setTextColor(0, color) # PyQt4
  281. item.setForeground(0, QtGui.QBrush(color))
  282. if font is not None:
  283. item.setFont(0, font)
  284. return item
  285. def addChild(self, parent, title, column1=None):
  286. item = QtWidgets.QTreeWidgetItem(parent)
  287. item.setText(0, str(title[0]))
  288. if column1 is not None:
  289. item.setText(1, str(title[1]))
  290. def show_area_chull(self, area, length, width, chull_area, location):
  291. # add dimensions
  292. self.addChild(location, ['%s:' % _('Length'), '%.4f %s' % (
  293. length, self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower())], True)
  294. self.addChild(location, ['%s:' % _('Width'), '%.4f %s' % (
  295. width, self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower())], True)
  296. # add box area
  297. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  298. self.addChild(location, ['%s:' % _('Box Area'), '%.4f %s' % (area, 'cm2')], True)
  299. self.addChild(location, ['%s:' % _('Convex_Hull Area'), '%.4f %s' % (chull_area, 'cm2')], True)
  300. else:
  301. self.addChild(location, ['%s:' % _('Box Area'), '%.4f %s' % (area, 'in2')], True)
  302. self.addChild(location, ['%s:' % _('Convex_Hull Area'), '%.4f %s' % (chull_area, 'in2')], True)
  303. # end of file