ToolProperties.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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] %s' %
  88. _("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. for obj in obj_list:
  94. self.addItems(obj)
  95. self.app.inform.emit('[success] %s' %
  96. _("Object Properties are displayed."))
  97. self.app.ui.notebook.setTabText(2, _("Properties Tool"))
  98. def addItems(self, obj):
  99. parent = self.treeWidget.invisibleRootItem()
  100. apertures = ''
  101. tools = ''
  102. font = QtGui.QFont()
  103. font.setBold(True)
  104. obj_type = self.addParent(parent, _('TYPE'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  105. obj_name = self.addParent(parent, _('NAME'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  106. dims = self.addParent(parent, _('Dimensions'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  107. units = self.addParent(parent, _('Units'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  108. options = self.addParent(parent, _('Options'), color=QtGui.QColor("#000000"), font=font)
  109. if obj.kind.lower() == 'gerber':
  110. apertures = self.addParent(parent, _('Apertures'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  111. else:
  112. tools = self.addParent(parent, _('Tools'), expanded=True, color=QtGui.QColor("#000000"), font=font)
  113. separator = self.addParent(parent, '')
  114. self.addChild(obj_type, ['%s:' % _('Object Type'), ('%s' % (obj.kind.capitalize()))], True)
  115. try:
  116. self.addChild(obj_type,
  117. ['%s:' % _('Geo Type'),
  118. ('%s' % ({False: _("Single-Geo"), True: _("Multi-Geo")}[obj.multigeo]))],
  119. True)
  120. except Exception as e:
  121. log.debug("Properties.addItems() --> %s" % str(e))
  122. self.addChild(obj_name, [obj.options['name']])
  123. def job_thread(obj):
  124. proc = self.app.proc_container.new(_("Calculating dimensions ... Please wait."))
  125. length = 0.0
  126. width = 0.0
  127. area = 0.0
  128. geo = obj.solid_geometry
  129. if geo:
  130. # calculate physical dimensions
  131. try:
  132. xmin, ymin, xmax, ymax = obj.bounds()
  133. length = abs(xmax - xmin)
  134. width = abs(ymax - ymin)
  135. except Exception as e:
  136. log.debug("PropertiesTool.addItems() --> %s" % str(e))
  137. # calculate box area
  138. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  139. area = (length * width) / 100
  140. else:
  141. area = length * width
  142. else:
  143. xmin = []
  144. ymin = []
  145. xmax = []
  146. ymax = []
  147. for tool in obj.tools:
  148. try:
  149. x0, y0, x1, y1 = cascaded_union(obj.tools[tool]['solid_geometry']).bounds
  150. xmin.append(x0)
  151. ymin.append(y0)
  152. xmax.append(x1)
  153. ymax.append(y1)
  154. except Exception as ee:
  155. log.debug("PropertiesTool.addItems() --> %s" % str(ee))
  156. try:
  157. xmin = min(xmin)
  158. ymin = min(ymin)
  159. xmax = max(xmax)
  160. ymax = max(ymax)
  161. length = abs(xmax - xmin)
  162. width = abs(ymax - ymin)
  163. # calculate box area
  164. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  165. area = (length * width) / 100
  166. else:
  167. area = length * width
  168. except Exception as e:
  169. log.debug("Properties.addItems() --> %s" % str(e))
  170. area_chull = 0.0
  171. if not isinstance(obj, FlatCAMCNCjob):
  172. # calculate and add convex hull area
  173. if geo:
  174. if isinstance(geo, MultiPolygon):
  175. env_obj = geo.convex_hull
  176. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  177. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  178. env_obj = cascaded_union(obj.solid_geometry)
  179. env_obj = env_obj.convex_hull
  180. else:
  181. env_obj = cascaded_union(obj.solid_geometry)
  182. env_obj = env_obj.convex_hull
  183. area_chull = env_obj.area
  184. else:
  185. try:
  186. area_chull = []
  187. for tool in obj.tools:
  188. area_el = cascaded_union(obj.tools[tool]['solid_geometry']).convex_hull
  189. area_chull.append(area_el.area)
  190. area_chull = max(area_chull)
  191. except Exception as e:
  192. area_chull = None
  193. log.debug("Properties.addItems() --> %s" % str(e))
  194. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  195. area_chull = area_chull / 100
  196. self.calculations_finished.emit(area, length, width, area_chull, dims)
  197. self.app.worker_task.emit({'fcn': job_thread, 'params': [obj]})
  198. self.addChild(units,
  199. ['FlatCAM units:',
  200. {
  201. 'in': _('Inch'),
  202. 'mm': _('Metric')
  203. }
  204. [str(self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower())]
  205. ],
  206. True
  207. )
  208. for option in obj.options:
  209. if option is 'name':
  210. continue
  211. self.addChild(options, [str(option), str(obj.options[option])], True)
  212. if obj.kind.lower() == 'gerber':
  213. temp_ap = dict()
  214. for ap in obj.apertures:
  215. temp_ap.clear()
  216. temp_ap = deepcopy(obj.apertures[ap])
  217. temp_ap.pop('geometry', None)
  218. solid_nr = 0
  219. follow_nr = 0
  220. clear_nr = 0
  221. if 'geometry' in obj.apertures[ap]:
  222. if obj.apertures[ap]['geometry']:
  223. font.setBold(True)
  224. for el in obj.apertures[ap]['geometry']:
  225. if 'solid' in el:
  226. solid_nr += 1
  227. if 'follow' in el:
  228. follow_nr += 1
  229. if 'clear' in el:
  230. clear_nr += 1
  231. else:
  232. font.setBold(False)
  233. temp_ap['Solid_Geo'] = '%s Polygons' % str(solid_nr)
  234. temp_ap['Follow_Geo'] = '%s LineStrings' % str(follow_nr)
  235. temp_ap['Clear_Geo'] = '%s Polygons' % str(clear_nr)
  236. apid = self.addParent(apertures, str(ap), expanded=False, color=QtGui.QColor("#000000"), font=font)
  237. for key in temp_ap:
  238. self.addChild(apid, [str(key), str(temp_ap[key])], True)
  239. elif obj.kind.lower() == 'excellon':
  240. for tool, value in obj.tools.items():
  241. self.addChild(tools, [str(tool), str(value['C'])], True)
  242. elif obj.kind.lower() == 'geometry':
  243. for tool, value in obj.tools.items():
  244. geo_tool = self.addParent(tools, str(tool), expanded=True, color=QtGui.QColor("#000000"), font=font)
  245. for k, v in value.items():
  246. if k == 'solid_geometry':
  247. printed_value = _('Present') if v else _('None')
  248. self.addChild(geo_tool, [str(k), printed_value], True)
  249. elif k == 'data':
  250. tool_data = self.addParent(geo_tool, str(k).capitalize(),
  251. color=QtGui.QColor("#000000"), font=font)
  252. for data_k, data_v in v.items():
  253. self.addChild(tool_data, [str(data_k), str(data_v)], True)
  254. else:
  255. self.addChild(geo_tool, [str(k), str(v)], True)
  256. elif obj.kind.lower() == 'cncjob':
  257. for tool, value in obj.cnc_tools.items():
  258. geo_tool = self.addParent(tools, str(tool), expanded=True, color=QtGui.QColor("#000000"), font=font)
  259. for k, v in value.items():
  260. if k == 'solid_geometry':
  261. printed_value = _('Present') if v else _('None')
  262. self.addChild(geo_tool, [str(k), printed_value], True)
  263. elif k == 'gcode':
  264. printed_value = _('Present') if v != '' else _('None')
  265. self.addChild(geo_tool, [str(k), printed_value], True)
  266. elif k == 'gcode_parsed':
  267. printed_value = _('Present') if v else _('None')
  268. self.addChild(geo_tool, [str(k), printed_value], True)
  269. elif k == 'data':
  270. tool_data = self.addParent(geo_tool, str(k).capitalize(),
  271. color=QtGui.QColor("#000000"), font=font)
  272. for data_k, data_v in v.items():
  273. self.addChild(tool_data, [str(data_k), str(data_v)], True)
  274. else:
  275. self.addChild(geo_tool, [str(k), str(v)], True)
  276. self.addChild(separator, [''])
  277. def addParent(self, parent, title, expanded=False, color=None, font=None):
  278. item = QtWidgets.QTreeWidgetItem(parent, [title])
  279. item.setChildIndicatorPolicy(QtWidgets.QTreeWidgetItem.ShowIndicator)
  280. item.setExpanded(expanded)
  281. if color is not None:
  282. # item.setTextColor(0, color) # PyQt4
  283. item.setForeground(0, QtGui.QBrush(color))
  284. if font is not None:
  285. item.setFont(0, font)
  286. return item
  287. def addChild(self, parent, title, column1=None):
  288. item = QtWidgets.QTreeWidgetItem(parent)
  289. item.setText(0, str(title[0]))
  290. if column1 is not None:
  291. item.setText(1, str(title[1]))
  292. def show_area_chull(self, area, length, width, chull_area, location):
  293. # add dimensions
  294. self.addChild(location, ['%s:' % _('Length'), '%.4f %s' % (
  295. length, self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower())], True)
  296. self.addChild(location, ['%s:' % _('Width'), '%.4f %s' % (
  297. width, self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower())], True)
  298. # add box area
  299. if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower() == 'mm':
  300. self.addChild(location, ['%s:' % _('Box Area'), '%.4f %s' % (area, 'cm2')], True)
  301. self.addChild(location, ['%s:' % _('Convex_Hull Area'), '%.4f %s' % (chull_area, 'cm2')], True)
  302. else:
  303. self.addChild(location, ['%s:' % _('Box Area'), '%.4f %s' % (area, 'in2')], True)
  304. self.addChild(location, ['%s:' % _('Convex_Hull Area'), '%.4f %s' % (chull_area, 'in2')], True)
  305. # end of file