PrintInformation.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import math
  5. import os
  6. import unicodedata
  7. from typing import Dict, List, Optional, TYPE_CHECKING
  8. from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot
  9. from UM.Logger import Logger
  10. from UM.Qt.Duration import Duration
  11. from UM.Scene.SceneNode import SceneNode
  12. from UM.i18n import i18nCatalog
  13. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeTypeNotFoundError
  14. if TYPE_CHECKING:
  15. from cura.CuraApplication import CuraApplication
  16. catalog = i18nCatalog("cura")
  17. ## A class for processing and the print times per build plate as well as managing the job name
  18. #
  19. # This class also mangles the current machine name and the filename of the first loaded mesh into a job name.
  20. # This job name is requested by the JobSpecs qml file.
  21. class PrintInformation(QObject):
  22. UNTITLED_JOB_NAME = "Untitled"
  23. def __init__(self, application: "CuraApplication", parent = None) -> None:
  24. super().__init__(parent)
  25. self._application = application
  26. self.initializeCuraMessagePrintTimeProperties()
  27. # Indexed by build plate number
  28. self._material_lengths = {} # type: Dict[int, List[float]]
  29. self._material_weights = {} # type: Dict[int, List[float]]
  30. self._material_costs = {} # type: Dict[int, List[float]]
  31. self._material_names = {} # type: Dict[int, List[str]]
  32. self._pre_sliced = False
  33. self._backend = self._application.getBackend()
  34. if self._backend:
  35. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  36. self._application.getController().getScene().sceneChanged.connect(self._onSceneChanged)
  37. self._is_user_specified_job_name = False
  38. self._base_name = ""
  39. self._abbr_machine = ""
  40. self._job_name = ""
  41. self._active_build_plate = 0
  42. self._initVariablesByBuildPlate(self._active_build_plate)
  43. self._multi_build_plate_model = self._application.getMultiBuildPlateModel()
  44. self._application.globalContainerStackChanged.connect(self._updateJobName)
  45. self._application.globalContainerStackChanged.connect(self.setToZeroPrintInformation)
  46. self._application.fileLoaded.connect(self.setBaseName)
  47. self._application.workspaceLoaded.connect(self.setProjectName)
  48. self._application.getMachineManager().rootMaterialChanged.connect(self._onActiveMaterialsChanged)
  49. self._application.getInstance().getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  50. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveBuildPlateChanged)
  51. self._material_amounts = [] # type: List[float]
  52. self._onActiveMaterialsChanged()
  53. def initializeCuraMessagePrintTimeProperties(self) -> None:
  54. self._current_print_time = {} # type: Dict[int, Duration]
  55. self._print_time_message_translations = {
  56. "inset_0": catalog.i18nc("@tooltip", "Outer Wall"),
  57. "inset_x": catalog.i18nc("@tooltip", "Inner Walls"),
  58. "skin": catalog.i18nc("@tooltip", "Skin"),
  59. "infill": catalog.i18nc("@tooltip", "Infill"),
  60. "support_infill": catalog.i18nc("@tooltip", "Support Infill"),
  61. "support_interface": catalog.i18nc("@tooltip", "Support Interface"),
  62. "support": catalog.i18nc("@tooltip", "Support"),
  63. "skirt": catalog.i18nc("@tooltip", "Skirt"),
  64. "prime_tower": catalog.i18nc("@tooltip", "Prime Tower"),
  65. "travel": catalog.i18nc("@tooltip", "Travel"),
  66. "retract": catalog.i18nc("@tooltip", "Retractions"),
  67. "none": catalog.i18nc("@tooltip", "Other")
  68. }
  69. self._print_times_per_feature = {} # type: Dict[int, Dict[str, Duration]]
  70. def _initPrintTimesPerFeature(self, build_plate_number: int) -> None:
  71. # Full fill message values using keys from _print_time_message_translations
  72. self._print_times_per_feature[build_plate_number] = {}
  73. for key in self._print_time_message_translations.keys():
  74. self._print_times_per_feature[build_plate_number][key] = Duration(None, self)
  75. def _initVariablesByBuildPlate(self, build_plate_number: int) -> None:
  76. if build_plate_number not in self._print_times_per_feature:
  77. self._initPrintTimesPerFeature(build_plate_number)
  78. if self._active_build_plate not in self._material_lengths:
  79. self._material_lengths[self._active_build_plate] = []
  80. if self._active_build_plate not in self._material_weights:
  81. self._material_weights[self._active_build_plate] = []
  82. if self._active_build_plate not in self._material_costs:
  83. self._material_costs[self._active_build_plate] = []
  84. if self._active_build_plate not in self._material_names:
  85. self._material_names[self._active_build_plate] = []
  86. if self._active_build_plate not in self._current_print_time:
  87. self._current_print_time[self._active_build_plate] = Duration(parent = self)
  88. currentPrintTimeChanged = pyqtSignal()
  89. preSlicedChanged = pyqtSignal()
  90. @pyqtProperty(bool, notify=preSlicedChanged)
  91. def preSliced(self) -> bool:
  92. return self._pre_sliced
  93. def setPreSliced(self, pre_sliced: bool) -> None:
  94. if self._pre_sliced != pre_sliced:
  95. self._pre_sliced = pre_sliced
  96. self._updateJobName()
  97. self.preSlicedChanged.emit()
  98. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  99. def currentPrintTime(self) -> Duration:
  100. return self._current_print_time[self._active_build_plate]
  101. materialLengthsChanged = pyqtSignal()
  102. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  103. def materialLengths(self):
  104. return self._material_lengths[self._active_build_plate]
  105. materialWeightsChanged = pyqtSignal()
  106. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  107. def materialWeights(self):
  108. return self._material_weights[self._active_build_plate]
  109. materialCostsChanged = pyqtSignal()
  110. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  111. def materialCosts(self):
  112. return self._material_costs[self._active_build_plate]
  113. materialNamesChanged = pyqtSignal()
  114. @pyqtProperty("QVariantList", notify = materialNamesChanged)
  115. def materialNames(self):
  116. return self._material_names[self._active_build_plate]
  117. # Get all print times (by feature) of the active buildplate.
  118. def printTimes(self) -> Dict[str, Duration]:
  119. return self._print_times_per_feature[self._active_build_plate]
  120. def _onPrintDurationMessage(self, build_plate_number: int, print_times_per_feature: Dict[str, int], material_amounts: List[float]) -> None:
  121. self._updateTotalPrintTimePerFeature(build_plate_number, print_times_per_feature)
  122. self.currentPrintTimeChanged.emit()
  123. self._material_amounts = material_amounts
  124. self._calculateInformation(build_plate_number)
  125. def _updateTotalPrintTimePerFeature(self, build_plate_number: int, print_times_per_feature: Dict[str, int]) -> None:
  126. total_estimated_time = 0
  127. if build_plate_number not in self._print_times_per_feature:
  128. self._initPrintTimesPerFeature(build_plate_number)
  129. for feature, time in print_times_per_feature.items():
  130. if feature not in self._print_times_per_feature[build_plate_number]:
  131. self._print_times_per_feature[build_plate_number][feature] = Duration(parent=self)
  132. duration = self._print_times_per_feature[build_plate_number][feature]
  133. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  134. duration.setDuration(0)
  135. Logger.log("w", "Received NaN for print duration message")
  136. continue
  137. total_estimated_time += time
  138. duration.setDuration(time)
  139. if build_plate_number not in self._current_print_time:
  140. self._current_print_time[build_plate_number] = Duration(None, self)
  141. self._current_print_time[build_plate_number].setDuration(total_estimated_time)
  142. def _calculateInformation(self, build_plate_number: int) -> None:
  143. global_stack = self._application.getGlobalContainerStack()
  144. if global_stack is None:
  145. return
  146. self._material_lengths[build_plate_number] = []
  147. self._material_weights[build_plate_number] = []
  148. self._material_costs[build_plate_number] = []
  149. self._material_names[build_plate_number] = []
  150. material_preference_values = json.loads(self._application.getInstance().getPreferences().getValue("cura/material_settings"))
  151. extruder_stacks = global_stack.extruders
  152. for position in extruder_stacks:
  153. extruder_stack = extruder_stacks[position]
  154. index = int(position)
  155. if index >= len(self._material_amounts):
  156. continue
  157. amount = self._material_amounts[index]
  158. # Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  159. # list comprehension filtering to solve this for us.
  160. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  161. material = extruder_stack.material
  162. radius = extruder_stack.getProperty("material_diameter", "value") / 2
  163. weight = float(amount) * float(density) / 1000
  164. cost = 0.
  165. material_guid = material.getMetaDataEntry("GUID")
  166. material_name = material.getName()
  167. if material_guid in material_preference_values:
  168. material_values = material_preference_values[material_guid]
  169. if material_values and "spool_weight" in material_values:
  170. weight_per_spool = float(material_values["spool_weight"])
  171. else:
  172. weight_per_spool = float(extruder_stack.getMetaDataEntry("properties", {}).get("weight", 0))
  173. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  174. if weight_per_spool != 0:
  175. cost = cost_per_spool * weight / weight_per_spool
  176. else:
  177. cost = 0
  178. # Material amount is sent as an amount of mm^3, so calculate length from that
  179. if radius != 0:
  180. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  181. else:
  182. length = 0
  183. self._material_weights[build_plate_number].append(weight)
  184. self._material_lengths[build_plate_number].append(length)
  185. self._material_costs[build_plate_number].append(cost)
  186. self._material_names[build_plate_number].append(material_name)
  187. self.materialLengthsChanged.emit()
  188. self.materialWeightsChanged.emit()
  189. self.materialCostsChanged.emit()
  190. self.materialNamesChanged.emit()
  191. def _onPreferencesChanged(self, preference: str) -> None:
  192. if preference != "cura/material_settings":
  193. return
  194. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  195. self._calculateInformation(build_plate_number)
  196. def _onActiveBuildPlateChanged(self) -> None:
  197. new_active_build_plate = self._multi_build_plate_model.activeBuildPlate
  198. if new_active_build_plate != self._active_build_plate:
  199. self._active_build_plate = new_active_build_plate
  200. self._updateJobName()
  201. self._initVariablesByBuildPlate(self._active_build_plate)
  202. self.materialLengthsChanged.emit()
  203. self.materialWeightsChanged.emit()
  204. self.materialCostsChanged.emit()
  205. self.materialNamesChanged.emit()
  206. self.currentPrintTimeChanged.emit()
  207. def _onActiveMaterialsChanged(self, *args, **kwargs) -> None:
  208. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  209. self._calculateInformation(build_plate_number)
  210. # Manual override of job name should also set the base name so that when the printer prefix is updated, it the
  211. # prefix can be added to the manually added name, not the old base name
  212. @pyqtSlot(str, bool)
  213. def setJobName(self, name: str, is_user_specified_job_name = False) -> None:
  214. self._is_user_specified_job_name = is_user_specified_job_name
  215. self._job_name = name
  216. self._base_name = name.replace(self._abbr_machine + "_", "")
  217. if name == "":
  218. self._is_user_specified_job_name = False
  219. self.jobNameChanged.emit()
  220. jobNameChanged = pyqtSignal()
  221. @pyqtProperty(str, notify = jobNameChanged)
  222. def jobName(self):
  223. return self._job_name
  224. def _updateJobName(self) -> None:
  225. if self._base_name == "":
  226. self._job_name = self.UNTITLED_JOB_NAME
  227. self._is_user_specified_job_name = False
  228. self.jobNameChanged.emit()
  229. return
  230. base_name = self._stripAccents(self._base_name)
  231. self._defineAbbreviatedMachineName()
  232. # Only update the job name when it's not user-specified.
  233. if not self._is_user_specified_job_name:
  234. if self._pre_sliced:
  235. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  236. elif self._application.getInstance().getPreferences().getValue("cura/jobname_prefix"):
  237. # Don't add abbreviation if it already has the exact same abbreviation.
  238. if base_name.startswith(self._abbr_machine + "_"):
  239. self._job_name = base_name
  240. else:
  241. self._job_name = self._abbr_machine + "_" + base_name
  242. else:
  243. self._job_name = base_name
  244. # In case there are several buildplates, a suffix is attached
  245. if self._multi_build_plate_model.maxBuildPlate > 0:
  246. connector = "_#"
  247. suffix = connector + str(self._active_build_plate + 1)
  248. if connector in self._job_name:
  249. self._job_name = self._job_name.split(connector)[0] # get the real name
  250. if self._active_build_plate != 0:
  251. self._job_name += suffix
  252. self.jobNameChanged.emit()
  253. @pyqtSlot(str)
  254. def setProjectName(self, name: str) -> None:
  255. self.setBaseName(name, is_project_file = True)
  256. baseNameChanged = pyqtSignal()
  257. def setBaseName(self, base_name: str, is_project_file: bool = False) -> None:
  258. self._is_user_specified_job_name = False
  259. # Ensure that we don't use entire path but only filename
  260. name = os.path.basename(base_name)
  261. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  262. # extension. This cuts the extension off if necessary.
  263. check_name = os.path.splitext(name)[0]
  264. filename_parts = os.path.basename(base_name).split(".")
  265. # If it's a gcode, also always update the job name
  266. is_gcode = False
  267. if len(filename_parts) > 1:
  268. # Only check the extension(s)
  269. is_gcode = "gcode" in filename_parts[1:]
  270. # if this is a profile file, always update the job name
  271. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  272. is_empty = check_name == ""
  273. if is_gcode or is_project_file or (is_empty or (self._base_name == "" and self._base_name != check_name)):
  274. # Only take the file name part, Note : file name might have 'dot' in name as well
  275. data = ""
  276. try:
  277. mime_type = MimeTypeDatabase.getMimeTypeForFile(name)
  278. data = mime_type.stripExtension(name)
  279. except MimeTypeNotFoundError:
  280. Logger.log("w", "Unsupported Mime Type Database file extension %s", name)
  281. if data is not None and check_name is not None:
  282. self._base_name = data
  283. else:
  284. self._base_name = ""
  285. # Strip the old "curaproject" extension from the name
  286. OLD_CURA_PROJECT_EXT = ".curaproject"
  287. if self._base_name.lower().endswith(OLD_CURA_PROJECT_EXT):
  288. self._base_name = self._base_name[:len(self._base_name) - len(OLD_CURA_PROJECT_EXT)]
  289. # CURA-5896 Try to strip extra extensions with an infinite amount of ".curaproject.3mf".
  290. OLD_CURA_PROJECT_3MF_EXT = ".curaproject.3mf"
  291. while self._base_name.lower().endswith(OLD_CURA_PROJECT_3MF_EXT):
  292. self._base_name = self._base_name[:len(self._base_name) - len(OLD_CURA_PROJECT_3MF_EXT)]
  293. self._updateJobName()
  294. @pyqtProperty(str, fset = setBaseName, notify = baseNameChanged)
  295. def baseName(self):
  296. return self._base_name
  297. ## Created an acronym-like abbreviated machine name from the currently
  298. # active machine name.
  299. # Called each time the global stack is switched.
  300. def _defineAbbreviatedMachineName(self) -> None:
  301. global_container_stack = self._application.getGlobalContainerStack()
  302. if not global_container_stack:
  303. self._abbr_machine = ""
  304. return
  305. active_machine_type_name = global_container_stack.definition.getName()
  306. self._abbr_machine = self._application.getMachineManager().getAbbreviatedMachineName(active_machine_type_name)
  307. ## Utility method that strips accents from characters (eg: â -> a)
  308. def _stripAccents(self, to_strip: str) -> str:
  309. return ''.join(char for char in unicodedata.normalize('NFD', to_strip) if unicodedata.category(char) != 'Mn')
  310. @pyqtSlot(result = "QVariantMap")
  311. def getFeaturePrintTimes(self) -> Dict[str, Duration]:
  312. result = {}
  313. if self._active_build_plate not in self._print_times_per_feature:
  314. self._initPrintTimesPerFeature(self._active_build_plate)
  315. for feature, time in self._print_times_per_feature[self._active_build_plate].items():
  316. if feature in self._print_time_message_translations:
  317. result[self._print_time_message_translations[feature]] = time
  318. else:
  319. result[feature] = time
  320. return result
  321. # Simulate message with zero time duration
  322. def setToZeroPrintInformation(self, build_plate: Optional[int] = None) -> None:
  323. if build_plate is None:
  324. build_plate = self._active_build_plate
  325. # Construct the 0-time message
  326. temp_message = {}
  327. if build_plate not in self._print_times_per_feature:
  328. self._print_times_per_feature[build_plate] = {}
  329. for key in self._print_times_per_feature[build_plate].keys():
  330. temp_message[key] = 0
  331. temp_material_amounts = [0.]
  332. self._onPrintDurationMessage(build_plate, temp_message, temp_material_amounts)
  333. ## Listen to scene changes to check if we need to reset the print information
  334. def _onSceneChanged(self, scene_node: SceneNode) -> None:
  335. # Ignore any changes that are not related to sliceable objects
  336. if not isinstance(scene_node, SceneNode)\
  337. or not scene_node.callDecoration("isSliceable")\
  338. or not scene_node.callDecoration("getBuildPlateNumber") == self._active_build_plate:
  339. return
  340. self.setToZeroPrintInformation(self._active_build_plate)