PrintInformation.py 19 KB

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