PrintInformation.py 13 KB

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