PrintInformation.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
  4. from UM.FlameProfiler import pyqtSlot
  5. from UM.Application import Application
  6. from UM.Logger import Logger
  7. from UM.Qt.Duration import Duration
  8. from UM.Preferences import Preferences
  9. from UM.Settings.ContainerRegistry import ContainerRegistry
  10. from cura.Settings.ExtruderManager import ExtruderManager
  11. import math
  12. import os.path
  13. import unicodedata
  14. import json
  15. from UM.i18n import i18nCatalog
  16. catalog = i18nCatalog("cura")
  17. ## A class for processing and calculating minimum, current and maximum print time as well as managing the job name
  18. #
  19. # This class contains all the logic relating to calculation and slicing for the
  20. # time/quality slider concept. It is a rather tricky combination of event handling
  21. # and state management. The logic behind this is as follows:
  22. #
  23. # - A scene change or setting change event happens.
  24. # We track what the source was of the change, either a scene change, a setting change, an active machine change or something else.
  25. # - This triggers a new slice with the current settings - this is the "current settings pass".
  26. # - When the slice is done, we update the current print time and material amount.
  27. # - If the source of the slice was not a Setting change, we start the second slice pass, the "low quality settings pass". Otherwise we stop here.
  28. # - When that is done, we update the minimum print time and start the final slice pass, the "Extra Fine settings pass".
  29. # - When the Extra Fine pass is done, we update the maximum print time.
  30. #
  31. # This class also mangles the current machine name and the filename of the first loaded mesh into a job name.
  32. # This job name is requested by the JobSpecs qml file.
  33. class PrintInformation(QObject):
  34. class SlicePass:
  35. CurrentSettings = 1
  36. LowQualitySettings = 2
  37. HighQualitySettings = 3
  38. class SliceReason:
  39. SceneChanged = 1
  40. SettingChanged = 2
  41. ActiveMachineChanged = 3
  42. Other = 4
  43. def __init__(self, parent = None):
  44. super().__init__(parent)
  45. self.initializeCuraMessagePrintTimeProperties()
  46. self._material_lengths = []
  47. self._material_weights = []
  48. self._material_costs = []
  49. self._material_names = []
  50. self._pre_sliced = False
  51. self._backend = Application.getInstance().getBackend()
  52. if self._backend:
  53. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  54. self._base_name = ""
  55. self._abbr_machine = ""
  56. self._job_name = ""
  57. Application.getInstance().globalContainerStackChanged.connect(self._updateJobName)
  58. Application.getInstance().fileLoaded.connect(self.setBaseName)
  59. Application.getInstance().workspaceLoaded.connect(self.setProjectName)
  60. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  61. self._active_material_container = None
  62. Application.getInstance().getMachineManager().activeMaterialChanged.connect(self._onActiveMaterialChanged)
  63. self._onActiveMaterialChanged()
  64. self._material_amounts = []
  65. # Crate cura message translations and using translation keys initialize empty time Duration object for total time
  66. # and time for each feature
  67. def initializeCuraMessagePrintTimeProperties(self):
  68. self._current_print_time = Duration(None, self)
  69. self._print_time_message_translations = {
  70. "inset_0": catalog.i18nc("@tooltip", "Outer Wall"),
  71. "inset_x": catalog.i18nc("@tooltip", "Inner Walls"),
  72. "skin": catalog.i18nc("@tooltip", "Skin"),
  73. "infill": catalog.i18nc("@tooltip", "Infill"),
  74. "support_infill": catalog.i18nc("@tooltip", "Support Infill"),
  75. "support_interface": catalog.i18nc("@tooltip", "Support Interface"),
  76. "support": catalog.i18nc("@tooltip", "Support"),
  77. "skirt": catalog.i18nc("@tooltip", "Skirt"),
  78. "travel": catalog.i18nc("@tooltip", "Travel"),
  79. "retract": catalog.i18nc("@tooltip", "Retractions"),
  80. "none": catalog.i18nc("@tooltip", "Other")
  81. }
  82. self._print_time_message_values = {}
  83. # Full fill message values using keys from _print_time_message_translations
  84. for key in self._print_time_message_translations.keys():
  85. self._print_time_message_values[key] = Duration(None, self)
  86. currentPrintTimeChanged = pyqtSignal()
  87. preSlicedChanged = pyqtSignal()
  88. @pyqtProperty(bool, notify=preSlicedChanged)
  89. def preSliced(self):
  90. return self._pre_sliced
  91. def setPreSliced(self, pre_sliced):
  92. self._pre_sliced = pre_sliced
  93. self.preSlicedChanged.emit()
  94. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  95. def currentPrintTime(self):
  96. return self._current_print_time
  97. materialLengthsChanged = pyqtSignal()
  98. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  99. def materialLengths(self):
  100. return self._material_lengths
  101. materialWeightsChanged = pyqtSignal()
  102. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  103. def materialWeights(self):
  104. return self._material_weights
  105. materialCostsChanged = pyqtSignal()
  106. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  107. def materialCosts(self):
  108. return self._material_costs
  109. materialNamesChanged = pyqtSignal()
  110. @pyqtProperty("QVariantList", notify = materialNamesChanged)
  111. def materialNames(self):
  112. return self._material_names
  113. def _onPrintDurationMessage(self, print_time, material_amounts):
  114. self._updateTotalPrintTimePerFeature(print_time)
  115. self.currentPrintTimeChanged.emit()
  116. self._material_amounts = material_amounts
  117. self._calculateInformation()
  118. def _updateTotalPrintTimePerFeature(self, print_time):
  119. total_estimated_time = 0
  120. for feature, time in print_time.items():
  121. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  122. self._print_time_message_values.get(feature).setDuration(0)
  123. Logger.log("w", "Received NaN for print duration message")
  124. continue
  125. total_estimated_time += time
  126. self._print_time_message_values.get(feature).setDuration(time)
  127. self._current_print_time.setDuration(total_estimated_time)
  128. def _calculateInformation(self):
  129. if Application.getInstance().getGlobalContainerStack() is None:
  130. return
  131. # Material amount is sent as an amount of mm^3, so calculate length from that
  132. radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
  133. self._material_lengths = []
  134. self._material_weights = []
  135. self._material_costs = []
  136. self._material_names = []
  137. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  138. extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
  139. for index, amount in enumerate(self._material_amounts):
  140. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  141. # list comprehension filtering to solve this for us.
  142. material = None
  143. if extruder_stacks: # Multi extrusion machine
  144. extruder_stack = [extruder for extruder in extruder_stacks if extruder.getMetaDataEntry("position") == str(index)][0]
  145. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  146. material = extruder_stack.findContainer({"type": "material"})
  147. else: # Machine with no extruder stacks
  148. density = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("properties", {}).get("density", 0)
  149. material = Application.getInstance().getGlobalContainerStack().findContainer({"type": "material"})
  150. weight = float(amount) * float(density) / 1000
  151. cost = 0
  152. material_name = catalog.i18nc("@label unknown material", "Unknown")
  153. if material:
  154. material_guid = material.getMetaDataEntry("GUID")
  155. material_name = material.getName()
  156. if material_guid in material_preference_values:
  157. material_values = material_preference_values[material_guid]
  158. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  159. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  160. if weight_per_spool != 0:
  161. cost = cost_per_spool * weight / weight_per_spool
  162. else:
  163. cost = 0
  164. if radius != 0:
  165. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  166. else:
  167. length = 0
  168. self._material_weights.append(weight)
  169. self._material_lengths.append(length)
  170. self._material_costs.append(cost)
  171. self._material_names.append(material_name)
  172. self.materialLengthsChanged.emit()
  173. self.materialWeightsChanged.emit()
  174. self.materialCostsChanged.emit()
  175. self.materialNamesChanged.emit()
  176. def _onPreferencesChanged(self, preference):
  177. if preference != "cura/material_settings":
  178. return
  179. self._calculateInformation()
  180. def _onActiveMaterialChanged(self):
  181. if self._active_material_container:
  182. try:
  183. self._active_material_container.metaDataChanged.disconnect(self._onMaterialMetaDataChanged)
  184. except TypeError: #pyQtSignal gives a TypeError when disconnecting from something that is already disconnected.
  185. pass
  186. active_material_id = Application.getInstance().getMachineManager().activeMaterialId
  187. active_material_containers = ContainerRegistry.getInstance().findInstanceContainers(id=active_material_id)
  188. if active_material_containers:
  189. self._active_material_container = active_material_containers[0]
  190. self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
  191. def _onMaterialMetaDataChanged(self, *args, **kwargs):
  192. self._calculateInformation()
  193. @pyqtSlot(str)
  194. def setJobName(self, name):
  195. self._job_name = name
  196. self.jobNameChanged.emit()
  197. jobNameChanged = pyqtSignal()
  198. @pyqtProperty(str, notify = jobNameChanged)
  199. def jobName(self):
  200. return self._job_name
  201. def _updateJobName(self):
  202. if self._base_name == "":
  203. self._job_name = ""
  204. self.jobNameChanged.emit()
  205. return
  206. base_name = self._stripAccents(self._base_name)
  207. self._setAbbreviatedMachineName()
  208. if self._pre_sliced:
  209. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  210. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  211. # Don't add abbreviation if it already has the exact same abbreviation.
  212. if base_name.startswith(self._abbr_machine + "_"):
  213. self._job_name = base_name
  214. else:
  215. self._job_name = self._abbr_machine + "_" + base_name
  216. else:
  217. self._job_name = base_name
  218. self.jobNameChanged.emit()
  219. @pyqtProperty(str)
  220. def baseName(self):
  221. return self._base_name
  222. @pyqtSlot(str)
  223. def setProjectName(self, name):
  224. self.setBaseName(name, is_project_file = True)
  225. @pyqtSlot(str)
  226. def setBaseName(self, base_name, is_project_file = False):
  227. # Ensure that we don't use entire path but only filename
  228. name = os.path.basename(base_name)
  229. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  230. # extension. This cuts the extension off if necessary.
  231. name = os.path.splitext(name)[0]
  232. # if this is a profile file, always update the job name
  233. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  234. is_empty = name == ""
  235. if is_project_file or (is_empty or (self._base_name == "" and self._base_name != name)):
  236. # remove ".curaproject" suffix from (imported) the file name
  237. if name.endswith(".curaproject"):
  238. name = name[:name.rfind(".curaproject")]
  239. self._base_name = name
  240. self._updateJobName()
  241. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  242. # Called each time the global stack is switched
  243. def _setAbbreviatedMachineName(self):
  244. global_container_stack = Application.getInstance().getGlobalContainerStack()
  245. if not global_container_stack:
  246. self._abbr_machine = ""
  247. return
  248. global_stack_name = global_container_stack.getName()
  249. split_name = global_stack_name.split(" ")
  250. abbr_machine = ""
  251. for word in split_name:
  252. if word.lower() == "ultimaker":
  253. abbr_machine += "UM"
  254. elif word.isdigit():
  255. abbr_machine += word
  256. else:
  257. stripped_word = self._stripAccents(word.strip("()[]{}#").upper())
  258. # - use only the first character if the word is too long (> 3 characters)
  259. # - use the whole word if it's not too long (<= 3 characters)
  260. if len(stripped_word) > 3:
  261. stripped_word = stripped_word[0]
  262. abbr_machine += stripped_word
  263. self._abbr_machine = abbr_machine
  264. ## Utility method that strips accents from characters (eg: â -> a)
  265. def _stripAccents(self, str):
  266. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
  267. @pyqtSlot(result = "QVariantMap")
  268. def getFeaturePrintTimes(self):
  269. result = {}
  270. for feature, time in self._print_time_message_values.items():
  271. if feature in self._print_time_message_translations:
  272. result[self._print_time_message_translations[feature]] = time
  273. else:
  274. result[feature] = time
  275. return result
  276. # Simulate message with zero time duration
  277. def setToZeroPrintInformation(self):
  278. temp_message = {}
  279. for key in self._print_time_message_values.keys():
  280. temp_message[key] = 0
  281. temp_material_amounts = [0]
  282. self._onPrintDurationMessage(temp_message, temp_material_amounts)