PrintInformation.py 20 KB

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