PrintInformation.py 19 KB

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