PrintInformation.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Dict
  4. import math
  5. import os.path
  6. import unicodedata
  7. import json
  8. import re # To create abbreviations for printer names.
  9. from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot
  10. from UM.Application import Application
  11. from UM.Logger import Logger
  12. from UM.Qt.Duration import Duration
  13. from UM.Preferences import Preferences
  14. from UM.Scene.SceneNode import SceneNode
  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 = {} # indexed by build plate number
  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. Application.getInstance().getController().getScene().sceneChanged.connect(self._onSceneChanged)
  55. self._base_name = ""
  56. self._abbr_machine = ""
  57. self._job_name = ""
  58. self._project_name = ""
  59. self._active_build_plate = 0
  60. self._initVariablesWithBuildPlate(self._active_build_plate)
  61. self._application = Application.getInstance()
  62. self._multi_build_plate_model = self._application.getMultiBuildPlateModel()
  63. self._application.globalContainerStackChanged.connect(self._updateJobName)
  64. self._application.globalContainerStackChanged.connect(self.setToZeroPrintInformation)
  65. self._application.fileLoaded.connect(self.setBaseName)
  66. self._application.workspaceLoaded.connect(self.setProjectName)
  67. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveBuildPlateChanged)
  68. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  69. self._application.getMachineManager().rootMaterialChanged.connect(self._onActiveMaterialsChanged)
  70. self._onActiveMaterialsChanged()
  71. self._material_amounts = []
  72. # Crate cura message translations and using translation keys initialize empty time Duration object for total time
  73. # and time for each feature
  74. def initializeCuraMessagePrintTimeProperties(self):
  75. self._current_print_time = {} # Duration(None, self)
  76. self._print_time_message_translations = {
  77. "inset_0": catalog.i18nc("@tooltip", "Outer Wall"),
  78. "inset_x": catalog.i18nc("@tooltip", "Inner Walls"),
  79. "skin": catalog.i18nc("@tooltip", "Skin"),
  80. "infill": catalog.i18nc("@tooltip", "Infill"),
  81. "support_infill": catalog.i18nc("@tooltip", "Support Infill"),
  82. "support_interface": catalog.i18nc("@tooltip", "Support Interface"),
  83. "support": catalog.i18nc("@tooltip", "Support"),
  84. "skirt": catalog.i18nc("@tooltip", "Skirt"),
  85. "travel": catalog.i18nc("@tooltip", "Travel"),
  86. "retract": catalog.i18nc("@tooltip", "Retractions"),
  87. "none": catalog.i18nc("@tooltip", "Other")
  88. }
  89. self._print_time_message_values = {}
  90. def _initPrintTimeMessageValues(self, build_plate_number):
  91. # Full fill message values using keys from _print_time_message_translations
  92. self._print_time_message_values[build_plate_number] = {}
  93. for key in self._print_time_message_translations.keys():
  94. self._print_time_message_values[build_plate_number][key] = Duration(None, self)
  95. def _initVariablesWithBuildPlate(self, build_plate_number):
  96. if build_plate_number not in self._print_time_message_values:
  97. self._initPrintTimeMessageValues(build_plate_number)
  98. if self._active_build_plate not in self._material_lengths:
  99. self._material_lengths[self._active_build_plate] = []
  100. if self._active_build_plate not in self._material_weights:
  101. self._material_weights[self._active_build_plate] = []
  102. if self._active_build_plate not in self._material_costs:
  103. self._material_costs[self._active_build_plate] = []
  104. if self._active_build_plate not in self._material_names:
  105. self._material_names[self._active_build_plate] = []
  106. if self._active_build_plate not in self._current_print_time:
  107. self._current_print_time[self._active_build_plate] = Duration(None, self)
  108. currentPrintTimeChanged = pyqtSignal()
  109. preSlicedChanged = pyqtSignal()
  110. @pyqtProperty(bool, notify=preSlicedChanged)
  111. def preSliced(self):
  112. return self._pre_sliced
  113. def setPreSliced(self, pre_sliced):
  114. self._pre_sliced = pre_sliced
  115. self._updateJobName()
  116. self.preSlicedChanged.emit()
  117. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  118. def currentPrintTime(self):
  119. return self._current_print_time[self._active_build_plate]
  120. materialLengthsChanged = pyqtSignal()
  121. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  122. def materialLengths(self):
  123. return self._material_lengths[self._active_build_plate]
  124. materialWeightsChanged = pyqtSignal()
  125. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  126. def materialWeights(self):
  127. return self._material_weights[self._active_build_plate]
  128. materialCostsChanged = pyqtSignal()
  129. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  130. def materialCosts(self):
  131. return self._material_costs[self._active_build_plate]
  132. materialNamesChanged = pyqtSignal()
  133. @pyqtProperty("QVariantList", notify = materialNamesChanged)
  134. def materialNames(self):
  135. return self._material_names[self._active_build_plate]
  136. def printTimes(self):
  137. return self._print_time_message_values[self._active_build_plate]
  138. def _onPrintDurationMessage(self, build_plate_number, print_time: Dict[str, int], material_amounts: list):
  139. self._updateTotalPrintTimePerFeature(build_plate_number, print_time)
  140. self.currentPrintTimeChanged.emit()
  141. self._material_amounts = material_amounts
  142. self._calculateInformation(build_plate_number)
  143. def _updateTotalPrintTimePerFeature(self, build_plate_number, print_time: Dict[str, int]):
  144. total_estimated_time = 0
  145. if build_plate_number not in self._print_time_message_values:
  146. self._initPrintTimeMessageValues(build_plate_number)
  147. for feature, time in print_time.items():
  148. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  149. self._print_time_message_values[build_plate_number].get(feature).setDuration(0)
  150. Logger.log("w", "Received NaN for print duration message")
  151. continue
  152. total_estimated_time += time
  153. self._print_time_message_values[build_plate_number].get(feature).setDuration(time)
  154. if build_plate_number not in self._current_print_time:
  155. self._current_print_time[build_plate_number] = Duration(None, self)
  156. self._current_print_time[build_plate_number].setDuration(total_estimated_time)
  157. def _calculateInformation(self, build_plate_number):
  158. global_stack = Application.getInstance().getGlobalContainerStack()
  159. if global_stack is None:
  160. return
  161. self._material_lengths[build_plate_number] = []
  162. self._material_weights[build_plate_number] = []
  163. self._material_costs[build_plate_number] = []
  164. self._material_names[build_plate_number] = []
  165. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  166. extruder_stacks = global_stack.extruders
  167. for position, extruder_stack in extruder_stacks.items():
  168. index = int(position)
  169. if index >= len(self._material_amounts):
  170. continue
  171. amount = self._material_amounts[index]
  172. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  173. # list comprehension filtering to solve this for us.
  174. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  175. material = extruder_stack.findContainer({"type": "material"})
  176. radius = extruder_stack.getProperty("material_diameter", "value") / 2
  177. weight = float(amount) * float(density) / 1000
  178. cost = 0
  179. material_name = catalog.i18nc("@label unknown material", "Unknown")
  180. if material:
  181. material_guid = material.getMetaDataEntry("GUID")
  182. material_name = material.getName()
  183. if material_guid in material_preference_values:
  184. material_values = material_preference_values[material_guid]
  185. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  186. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  187. if weight_per_spool != 0:
  188. cost = cost_per_spool * weight / weight_per_spool
  189. else:
  190. cost = 0
  191. # Material amount is sent as an amount of mm^3, so calculate length from that
  192. if radius != 0:
  193. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  194. else:
  195. length = 0
  196. self._material_weights[build_plate_number].append(weight)
  197. self._material_lengths[build_plate_number].append(length)
  198. self._material_costs[build_plate_number].append(cost)
  199. self._material_names[build_plate_number].append(material_name)
  200. self.materialLengthsChanged.emit()
  201. self.materialWeightsChanged.emit()
  202. self.materialCostsChanged.emit()
  203. self.materialNamesChanged.emit()
  204. def _onPreferencesChanged(self, preference):
  205. if preference != "cura/material_settings":
  206. return
  207. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  208. self._calculateInformation(build_plate_number)
  209. def _onActiveBuildPlateChanged(self):
  210. new_active_build_plate = self._multi_build_plate_model.activeBuildPlate
  211. if new_active_build_plate != self._active_build_plate:
  212. self._active_build_plate = new_active_build_plate
  213. self._initVariablesWithBuildPlate(self._active_build_plate)
  214. self.materialLengthsChanged.emit()
  215. self.materialWeightsChanged.emit()
  216. self.materialCostsChanged.emit()
  217. self.materialNamesChanged.emit()
  218. self.currentPrintTimeChanged.emit()
  219. def _onActiveMaterialsChanged(self, *args, **kwargs):
  220. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  221. self._calculateInformation(build_plate_number)
  222. @pyqtSlot(str)
  223. def setJobName(self, name):
  224. self._job_name = name
  225. self.jobNameChanged.emit()
  226. jobNameChanged = pyqtSignal()
  227. @pyqtProperty(str, notify = jobNameChanged)
  228. def jobName(self):
  229. return self._job_name
  230. def _updateJobName(self):
  231. if self._base_name == "":
  232. self._job_name = ""
  233. self.jobNameChanged.emit()
  234. return
  235. base_name = self._stripAccents(self._base_name)
  236. self._setAbbreviatedMachineName()
  237. if self._pre_sliced:
  238. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  239. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  240. # Don't add abbreviation if it already has the exact same abbreviation.
  241. if base_name.startswith(self._abbr_machine + "_"):
  242. self._job_name = base_name
  243. else:
  244. self._job_name = self._abbr_machine + "_" + base_name
  245. else:
  246. self._job_name = base_name
  247. self.jobNameChanged.emit()
  248. @pyqtSlot(str)
  249. def setProjectName(self, name):
  250. self.setBaseName(name, is_project_file = True)
  251. baseNameChanged = pyqtSignal()
  252. def setBaseName(self, base_name: str, is_project_file: bool = False):
  253. # Ensure that we don't use entire path but only filename
  254. name = os.path.basename(base_name)
  255. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  256. # extension. This cuts the extension off if necessary.
  257. name = os.path.splitext(name)[0]
  258. filename_parts = os.path.basename(base_name).split(".")
  259. # If it's a gcode, also always update the job name
  260. is_gcode = False
  261. if len(filename_parts) > 1:
  262. # Only check the extension(s)
  263. is_gcode = "gcode" in filename_parts[1:]
  264. # if this is a profile file, always update the job name
  265. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  266. is_empty = name == ""
  267. if is_gcode or is_project_file or (is_empty or (self._base_name == "" and self._base_name != name)):
  268. # Only take the file name part
  269. self._base_name = filename_parts[0]
  270. self._updateJobName()
  271. @pyqtProperty(str, fset = setBaseName, notify = baseNameChanged)
  272. def baseName(self):
  273. return self._base_name
  274. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  275. # Called each time the global stack is switched
  276. def _setAbbreviatedMachineName(self):
  277. global_container_stack = Application.getInstance().getGlobalContainerStack()
  278. if not global_container_stack:
  279. self._abbr_machine = ""
  280. return
  281. active_machine_type_name = global_container_stack.definition.getName()
  282. abbr_machine = ""
  283. for word in re.findall(r"[\w']+", active_machine_type_name):
  284. if word.lower() == "ultimaker":
  285. abbr_machine += "UM"
  286. elif word.isdigit():
  287. abbr_machine += word
  288. else:
  289. stripped_word = self._stripAccents(word.upper())
  290. # - use only the first character if the word is too long (> 3 characters)
  291. # - use the whole word if it's not too long (<= 3 characters)
  292. if len(stripped_word) > 3:
  293. stripped_word = stripped_word[0]
  294. abbr_machine += stripped_word
  295. self._abbr_machine = abbr_machine
  296. ## Utility method that strips accents from characters (eg: â -> a)
  297. def _stripAccents(self, str):
  298. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
  299. @pyqtSlot(result = "QVariantMap")
  300. def getFeaturePrintTimes(self):
  301. result = {}
  302. if self._active_build_plate not in self._print_time_message_values:
  303. self._initPrintTimeMessageValues(self._active_build_plate)
  304. for feature, time in self._print_time_message_values[self._active_build_plate].items():
  305. if feature in self._print_time_message_translations:
  306. result[self._print_time_message_translations[feature]] = time
  307. else:
  308. result[feature] = time
  309. return result
  310. # Simulate message with zero time duration
  311. def setToZeroPrintInformation(self, build_plate = None):
  312. if build_plate is None:
  313. build_plate = self._active_build_plate
  314. # Construct the 0-time message
  315. temp_message = {}
  316. if build_plate not in self._print_time_message_values:
  317. self._print_time_message_values[build_plate] = {}
  318. for key in self._print_time_message_values[build_plate].keys():
  319. temp_message[key] = 0
  320. temp_material_amounts = [0]
  321. self._onPrintDurationMessage(build_plate, temp_message, temp_material_amounts)
  322. ## Listen to scene changes to check if we need to reset the print information
  323. def _onSceneChanged(self, scene_node):
  324. # Ignore any changes that are not related to sliceable objects
  325. if not isinstance(scene_node, SceneNode)\
  326. or not scene_node.callDecoration("isSliceable")\
  327. or not scene_node.callDecoration("getBuildPlateNumber") == self._active_build_plate:
  328. return
  329. self.setToZeroPrintInformation(self._active_build_plate)