ToolProperties.py 15 KB

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