ToolProperties.py 15 KB

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