PrintInformation.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 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 "high quality settings pass".
  29. # - When the high quality 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._current_print_time = Duration(None, self)
  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._job_name = ""
  54. self._abbr_machine = ""
  55. Application.getInstance().globalContainerStackChanged.connect(self._setAbbreviatedMachineName)
  56. Application.getInstance().fileLoaded.connect(self.setJobName)
  57. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  58. self._active_material_container = None
  59. Application.getInstance().getMachineManager().activeMaterialChanged.connect(self._onActiveMaterialChanged)
  60. self._onActiveMaterialChanged()
  61. self._material_amounts = []
  62. currentPrintTimeChanged = pyqtSignal()
  63. preSlicedChanged = pyqtSignal()
  64. @pyqtProperty(bool, notify=preSlicedChanged)
  65. def preSliced(self):
  66. return self._pre_sliced
  67. def setPreSliced(self, pre_sliced):
  68. self._pre_sliced = pre_sliced
  69. self.preSlicedChanged.emit()
  70. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  71. def currentPrintTime(self):
  72. return self._current_print_time
  73. materialLengthsChanged = pyqtSignal()
  74. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  75. def materialLengths(self):
  76. return self._material_lengths
  77. materialWeightsChanged = pyqtSignal()
  78. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  79. def materialWeights(self):
  80. return self._material_weights
  81. materialCostsChanged = pyqtSignal()
  82. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  83. def materialCosts(self):
  84. return self._material_costs
  85. def _onPrintDurationMessage(self, total_time, material_amounts):
  86. if total_time != total_time: # Check for NaN. Engine can sometimes give us weird values.
  87. Logger.log("w", "Received NaN for print duration message")
  88. self._current_print_time.setDuration(0)
  89. else:
  90. self._current_print_time.setDuration(total_time)
  91. self.currentPrintTimeChanged.emit()
  92. self._material_amounts = material_amounts
  93. self._calculateInformation()
  94. def _calculateInformation(self):
  95. if Application.getInstance().getGlobalContainerStack() is None:
  96. return
  97. # Material amount is sent as an amount of mm^3, so calculate length from that
  98. radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
  99. self._material_lengths = []
  100. self._material_weights = []
  101. self._material_costs = []
  102. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  103. extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
  104. for index, amount in enumerate(self._material_amounts):
  105. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  106. # list comprehension filtering to solve this for us.
  107. material = None
  108. if extruder_stacks: # Multi extrusion machine
  109. extruder_stack = [extruder for extruder in extruder_stacks if extruder.getMetaDataEntry("position") == str(index)][0]
  110. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  111. material = extruder_stack.findContainer({"type": "material"})
  112. else: # Machine with no extruder stacks
  113. density = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("properties", {}).get("density", 0)
  114. material = Application.getInstance().getGlobalContainerStack().findContainer({"type": "material"})
  115. weight = float(amount) * float(density) / 1000
  116. cost = 0
  117. if material:
  118. material_guid = material.getMetaDataEntry("GUID")
  119. if material_guid in material_preference_values:
  120. material_values = material_preference_values[material_guid]
  121. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  122. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  123. if weight_per_spool != 0:
  124. cost = cost_per_spool * weight / weight_per_spool
  125. else:
  126. cost = 0
  127. if radius != 0:
  128. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  129. else:
  130. length = 0
  131. self._material_weights.append(weight)
  132. self._material_lengths.append(length)
  133. self._material_costs.append(cost)
  134. self.materialLengthsChanged.emit()
  135. self.materialWeightsChanged.emit()
  136. self.materialCostsChanged.emit()
  137. def _onPreferencesChanged(self, preference):
  138. if preference != "cura/material_settings":
  139. return
  140. self._calculateInformation()
  141. def _onActiveMaterialChanged(self):
  142. if self._active_material_container:
  143. self._active_material_container.metaDataChanged.disconnect(self._onMaterialMetaDataChanged)
  144. active_material_id = Application.getInstance().getMachineManager().activeMaterialId
  145. active_material_containers = ContainerRegistry.getInstance().findInstanceContainers(id=active_material_id)
  146. if active_material_containers:
  147. self._active_material_container = active_material_containers[0]
  148. self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
  149. def _onMaterialMetaDataChanged(self, *args, **kwargs):
  150. self._calculateInformation()
  151. @pyqtSlot(str)
  152. def setJobName(self, name):
  153. # Ensure that we don't use entire path but only filename
  154. name = os.path.basename(name)
  155. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  156. # extension. This cuts the extension off if necessary.
  157. name = os.path.splitext(name)[0]
  158. if self._job_name != name:
  159. self._job_name = name
  160. self.jobNameChanged.emit()
  161. jobNameChanged = pyqtSignal()
  162. @pyqtProperty(str, notify = jobNameChanged)
  163. def jobName(self):
  164. return self._job_name
  165. @pyqtSlot(str, result = str)
  166. def createJobName(self, base_name):
  167. if base_name == "":
  168. return ""
  169. base_name = self._stripAccents(base_name)
  170. self._setAbbreviatedMachineName()
  171. if self._pre_sliced:
  172. return catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  173. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  174. # Don't add abbreviation if it already has the exact same abbreviation.
  175. if base_name.startswith(self._abbr_machine + "_"):
  176. return base_name
  177. return self._abbr_machine + "_" + base_name
  178. else:
  179. return base_name
  180. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  181. # Called each time the global stack is switched
  182. def _setAbbreviatedMachineName(self):
  183. global_container_stack = Application.getInstance().getGlobalContainerStack()
  184. if not global_container_stack:
  185. self._abbr_machine = ""
  186. return
  187. global_stack_name = global_container_stack.getName()
  188. split_name = global_stack_name.split(" ")
  189. abbr_machine = ""
  190. for word in split_name:
  191. if word.lower() == "ultimaker":
  192. abbr_machine += "UM"
  193. elif word.isdigit():
  194. abbr_machine += word
  195. else:
  196. abbr_machine += self._stripAccents(word.strip("()[]{}#").upper())[0]
  197. self._abbr_machine = abbr_machine
  198. ## Utility method that strips accents from characters (eg: â -> a)
  199. def _stripAccents(self, str):
  200. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')