PrintInformation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  60. self._active_material_container = None
  61. Application.getInstance().getMachineManager().activeMaterialChanged.connect(self._onActiveMaterialChanged)
  62. self._onActiveMaterialChanged()
  63. self._material_amounts = []
  64. # Crate cura message translations and using translation keys initialize empty time Duration object for total time
  65. # and time for each feature
  66. def initializeCuraMessagePrintTimeProperties(self):
  67. self._current_print_time = Duration(None, self)
  68. self._print_time_message_translations = {
  69. "inset_0": catalog.i18nc("@tooltip", "Outer Wall"),
  70. "inset_x": catalog.i18nc("@tooltip", "Inner Walls"),
  71. "skin": catalog.i18nc("@tooltip", "Skin"),
  72. "infill": catalog.i18nc("@tooltip", "Infill"),
  73. "support_infill": catalog.i18nc("@tooltip", "Support Infill"),
  74. "support_interface": catalog.i18nc("@tooltip", "Support Interface"),
  75. "support": catalog.i18nc("@tooltip", "Support"),
  76. "skirt": catalog.i18nc("@tooltip", "Skirt"),
  77. "travel": catalog.i18nc("@tooltip", "Travel"),
  78. "retract": catalog.i18nc("@tooltip", "Retractions"),
  79. "none": catalog.i18nc("@tooltip", "Other")
  80. }
  81. self._print_time_message_values = {}
  82. # Full fill message values using keys from _print_time_message_translations
  83. for key in self._print_time_message_translations.keys():
  84. self._print_time_message_values[key] = Duration(None, self)
  85. currentPrintTimeChanged = pyqtSignal()
  86. preSlicedChanged = pyqtSignal()
  87. @pyqtProperty(bool, notify=preSlicedChanged)
  88. def preSliced(self):
  89. return self._pre_sliced
  90. def setPreSliced(self, pre_sliced):
  91. self._pre_sliced = pre_sliced
  92. self.preSlicedChanged.emit()
  93. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  94. def currentPrintTime(self):
  95. return self._current_print_time
  96. materialLengthsChanged = pyqtSignal()
  97. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  98. def materialLengths(self):
  99. return self._material_lengths
  100. materialWeightsChanged = pyqtSignal()
  101. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  102. def materialWeights(self):
  103. return self._material_weights
  104. materialCostsChanged = pyqtSignal()
  105. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  106. def materialCosts(self):
  107. return self._material_costs
  108. materialNamesChanged = pyqtSignal()
  109. @pyqtProperty("QVariantList", notify = materialNamesChanged)
  110. def materialNames(self):
  111. return self._material_names
  112. def _onPrintDurationMessage(self, print_time, material_amounts):
  113. self._updateTotalPrintTimePerFeature(print_time)
  114. self.currentPrintTimeChanged.emit()
  115. self._material_amounts = material_amounts
  116. self._calculateInformation()
  117. def _updateTotalPrintTimePerFeature(self, print_time):
  118. total_estimated_time = 0
  119. for feature, time in print_time.items():
  120. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  121. self._print_time_message_values.get(feature).setDuration(0)
  122. Logger.log("w", "Received NaN for print duration message")
  123. continue
  124. total_estimated_time += time
  125. self._print_time_message_values.get(feature).setDuration(time)
  126. self._current_print_time.setDuration(total_estimated_time)
  127. def _calculateInformation(self):
  128. if Application.getInstance().getGlobalContainerStack() is None:
  129. return
  130. # Material amount is sent as an amount of mm^3, so calculate length from that
  131. radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
  132. self._material_lengths = []
  133. self._material_weights = []
  134. self._material_costs = []
  135. self._material_names = []
  136. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  137. extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
  138. for index, amount in enumerate(self._material_amounts):
  139. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  140. # list comprehension filtering to solve this for us.
  141. material = None
  142. if extruder_stacks: # Multi extrusion machine
  143. extruder_stack = [extruder for extruder in extruder_stacks if extruder.getMetaDataEntry("position") == str(index)][0]
  144. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  145. material = extruder_stack.findContainer({"type": "material"})
  146. else: # Machine with no extruder stacks
  147. density = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("properties", {}).get("density", 0)
  148. material = Application.getInstance().getGlobalContainerStack().findContainer({"type": "material"})
  149. weight = float(amount) * float(density) / 1000
  150. cost = 0
  151. material_name = catalog.i18nc("@label unknown material", "Unknown")
  152. if material:
  153. material_guid = material.getMetaDataEntry("GUID")
  154. material_name = material.getName()
  155. if material_guid in material_preference_values:
  156. material_values = material_preference_values[material_guid]
  157. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  158. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  159. if weight_per_spool != 0:
  160. cost = cost_per_spool * weight / weight_per_spool
  161. else:
  162. cost = 0
  163. if radius != 0:
  164. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  165. else:
  166. length = 0
  167. self._material_weights.append(weight)
  168. self._material_lengths.append(length)
  169. self._material_costs.append(cost)
  170. self._material_names.append(material_name)
  171. self.materialLengthsChanged.emit()
  172. self.materialWeightsChanged.emit()
  173. self.materialCostsChanged.emit()
  174. self.materialNamesChanged.emit()
  175. def _onPreferencesChanged(self, preference):
  176. if preference != "cura/material_settings":
  177. return
  178. self._calculateInformation()
  179. def _onActiveMaterialChanged(self):
  180. if self._active_material_container:
  181. try:
  182. self._active_material_container.metaDataChanged.disconnect(self._onMaterialMetaDataChanged)
  183. except TypeError: #pyQtSignal gives a TypeError when disconnecting from something that is already disconnected.
  184. pass
  185. active_material_id = Application.getInstance().getMachineManager().activeMaterialId
  186. active_material_containers = ContainerRegistry.getInstance().findInstanceContainers(id=active_material_id)
  187. if active_material_containers:
  188. self._active_material_container = active_material_containers[0]
  189. self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
  190. def _onMaterialMetaDataChanged(self, *args, **kwargs):
  191. self._calculateInformation()
  192. @pyqtSlot(str)
  193. def setJobName(self, name):
  194. self._job_name = name
  195. self.jobNameChanged.emit()
  196. jobNameChanged = pyqtSignal()
  197. @pyqtProperty(str, notify = jobNameChanged)
  198. def jobName(self):
  199. return self._job_name
  200. def _updateJobName(self):
  201. if self._base_name == "":
  202. self._job_name = ""
  203. self.jobNameChanged.emit()
  204. return
  205. base_name = self._stripAccents(self._base_name)
  206. self._setAbbreviatedMachineName()
  207. if self._pre_sliced:
  208. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  209. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  210. # Don't add abbreviation if it already has the exact same abbreviation.
  211. if base_name.startswith(self._abbr_machine + "_"):
  212. self._job_name = base_name
  213. else:
  214. self._job_name = self._abbr_machine + "_" + base_name
  215. else:
  216. self._job_name = base_name
  217. self.jobNameChanged.emit()
  218. @pyqtProperty(str)
  219. def baseName(self):
  220. return self._base_name
  221. @pyqtSlot(str)
  222. def setBaseName(self, base_name):
  223. # Ensure that we don't use entire path but only filename
  224. name = os.path.basename(base_name)
  225. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  226. # extension. This cuts the extension off if necessary.
  227. name = os.path.splitext(name)[0]
  228. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  229. is_empty = name == ""
  230. if is_empty or (self._base_name == "" and self._base_name != name):
  231. # remove ".curaproject" suffix from (imported) the file name
  232. if name.endswith(".curaproject"):
  233. name = name[:name.rfind(".curaproject")]
  234. self._base_name = name
  235. self._updateJobName()
  236. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  237. # Called each time the global stack is switched
  238. def _setAbbreviatedMachineName(self):
  239. global_container_stack = Application.getInstance().getGlobalContainerStack()
  240. if not global_container_stack:
  241. self._abbr_machine = ""
  242. return
  243. global_stack_name = global_container_stack.getName()
  244. split_name = global_stack_name.split(" ")
  245. abbr_machine = ""
  246. for word in split_name:
  247. if word.lower() == "ultimaker":
  248. abbr_machine += "UM"
  249. elif word.isdigit():
  250. abbr_machine += word
  251. else:
  252. stripped_word = self._stripAccents(word.strip("()[]{}#").upper())
  253. # - use only the first character if the word is too long (> 3 characters)
  254. # - use the whole word if it's not too long (<= 3 characters)
  255. if len(stripped_word) > 3:
  256. stripped_word = stripped_word[0]
  257. abbr_machine += stripped_word
  258. self._abbr_machine = abbr_machine
  259. ## Utility method that strips accents from characters (eg: â -> a)
  260. def _stripAccents(self, str):
  261. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
  262. @pyqtSlot(result = "QVariantMap")
  263. def getFeaturePrintTimes(self):
  264. result = {}
  265. for feature, time in self._print_time_message_values.items():
  266. if feature in self._print_time_message_translations:
  267. result[self._print_time_message_translations[feature]] = time
  268. else:
  269. result[feature] = time
  270. return result
  271. # Simulate message with zero time duration
  272. def setToZeroPrintInformation(self):
  273. temp_message = {}
  274. for key in self._print_time_message_values.keys():
  275. temp_message[key] = 0
  276. temp_material_amounts = [0]
  277. self._onPrintDurationMessage(temp_message, temp_material_amounts)