PrintInformation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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._pre_sliced = False
  50. self._backend = Application.getInstance().getBackend()
  51. if self._backend:
  52. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  53. self._base_name = ""
  54. self._abbr_machine = ""
  55. self._job_name = ""
  56. self._project_name = ""
  57. Application.getInstance().globalContainerStackChanged.connect(self._updateJobName)
  58. Application.getInstance().fileLoaded.connect(self.setBaseName)
  59. Application.getInstance().projectFileLoaded.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. def _onPrintDurationMessage(self, print_time, material_amounts):
  110. self._updateTotalPrintTimePerFeature(print_time)
  111. self.currentPrintTimeChanged.emit()
  112. self._material_amounts = material_amounts
  113. self._calculateInformation()
  114. def _updateTotalPrintTimePerFeature(self, print_time):
  115. total_estimated_time = 0
  116. for feature, time in print_time.items():
  117. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  118. self._print_time_message_values.get(feature).setDuration(0)
  119. Logger.log("w", "Received NaN for print duration message")
  120. continue
  121. total_estimated_time += time
  122. self._print_time_message_values.get(feature).setDuration(time)
  123. self._current_print_time.setDuration(total_estimated_time)
  124. def _calculateInformation(self):
  125. if Application.getInstance().getGlobalContainerStack() is None:
  126. return
  127. # Material amount is sent as an amount of mm^3, so calculate length from that
  128. radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
  129. self._material_lengths = []
  130. self._material_weights = []
  131. self._material_costs = []
  132. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  133. extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
  134. for index, amount in enumerate(self._material_amounts):
  135. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  136. # list comprehension filtering to solve this for us.
  137. material = None
  138. if extruder_stacks: # Multi extrusion machine
  139. extruder_stack = [extruder for extruder in extruder_stacks if extruder.getMetaDataEntry("position") == str(index)][0]
  140. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  141. material = extruder_stack.findContainer({"type": "material"})
  142. else: # Machine with no extruder stacks
  143. density = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("properties", {}).get("density", 0)
  144. material = Application.getInstance().getGlobalContainerStack().findContainer({"type": "material"})
  145. weight = float(amount) * float(density) / 1000
  146. cost = 0
  147. if material:
  148. material_guid = material.getMetaDataEntry("GUID")
  149. if material_guid in material_preference_values:
  150. material_values = material_preference_values[material_guid]
  151. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  152. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  153. if weight_per_spool != 0:
  154. cost = cost_per_spool * weight / weight_per_spool
  155. else:
  156. cost = 0
  157. if radius != 0:
  158. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  159. else:
  160. length = 0
  161. self._material_weights.append(weight)
  162. self._material_lengths.append(length)
  163. self._material_costs.append(cost)
  164. self.materialLengthsChanged.emit()
  165. self.materialWeightsChanged.emit()
  166. self.materialCostsChanged.emit()
  167. def _onPreferencesChanged(self, preference):
  168. if preference != "cura/material_settings":
  169. return
  170. self._calculateInformation()
  171. def _onActiveMaterialChanged(self):
  172. if self._active_material_container:
  173. try:
  174. self._active_material_container.metaDataChanged.disconnect(self._onMaterialMetaDataChanged)
  175. except TypeError: #pyQtSignal gives a TypeError when disconnecting from something that is already disconnected.
  176. pass
  177. active_material_id = Application.getInstance().getMachineManager().activeMaterialId
  178. active_material_containers = ContainerRegistry.getInstance().findInstanceContainers(id=active_material_id)
  179. if active_material_containers:
  180. self._active_material_container = active_material_containers[0]
  181. self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
  182. def _onMaterialMetaDataChanged(self, *args, **kwargs):
  183. self._calculateInformation()
  184. @pyqtSlot(str)
  185. def setJobName(self, name):
  186. self._job_name = name
  187. self.jobNameChanged.emit()
  188. @pyqtSlot(str)
  189. def setProjectName(self, name):
  190. self._project_name = name
  191. self.setJobName(name)
  192. jobNameChanged = pyqtSignal()
  193. @pyqtProperty(str, notify = jobNameChanged)
  194. def jobName(self):
  195. return self._job_name
  196. def _updateJobName(self):
  197. # if the project name is set, we use the project name as the job name, so the job name should not get updated
  198. # if a model file is loaded after that.
  199. if self._project_name != "":
  200. return
  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. if name == "" or (self._base_name == "" and self._base_name != name):
  230. self._base_name = name
  231. self._updateJobName()
  232. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  233. # Called each time the global stack is switched
  234. def _setAbbreviatedMachineName(self):
  235. global_container_stack = Application.getInstance().getGlobalContainerStack()
  236. if not global_container_stack:
  237. self._abbr_machine = ""
  238. return
  239. global_stack_name = global_container_stack.getName()
  240. split_name = global_stack_name.split(" ")
  241. abbr_machine = ""
  242. for word in split_name:
  243. if word.lower() == "ultimaker":
  244. abbr_machine += "UM"
  245. elif word.isdigit():
  246. abbr_machine += word
  247. else:
  248. stripped_word = self._stripAccents(word.strip("()[]{}#").upper())
  249. # - use only the first character if the word is too long (> 3 characters)
  250. # - use the whole word if it's not too long (<= 3 characters)
  251. if len(stripped_word) > 3:
  252. stripped_word = stripped_word[0]
  253. abbr_machine += stripped_word
  254. self._abbr_machine = abbr_machine
  255. ## Utility method that strips accents from characters (eg: â -> a)
  256. def _stripAccents(self, str):
  257. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
  258. @pyqtSlot(result = "QVariantMap")
  259. def getFeaturePrintTimes(self):
  260. result = {}
  261. for feature, time in self._print_time_message_values.items():
  262. if feature in self._print_time_message_translations:
  263. result[self._print_time_message_translations[feature]] = time
  264. else:
  265. result[feature] = time
  266. return result
  267. # Simulate message with zero time duration
  268. def setToZeroPrintInformation(self):
  269. temp_message = {}
  270. for key in self._print_time_message_values.keys():
  271. temp_message[key] = 0
  272. temp_material_amounts = [0]
  273. self._onPrintDurationMessage(temp_message, temp_material_amounts)