PrintInformation.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. from UM.MimeTypeDatabase import MimeTypeDatabase
  17. catalog = i18nCatalog("cura")
  18. ## A class for processing and calculating minimum, current and maximum print time as well as managing the job name
  19. #
  20. # This class contains all the logic relating to calculation and slicing for the
  21. # time/quality slider concept. It is a rather tricky combination of event handling
  22. # and state management. The logic behind this is as follows:
  23. #
  24. # - A scene change or setting change event happens.
  25. # We track what the source was of the change, either a scene change, a setting change, an active machine change or something else.
  26. # - This triggers a new slice with the current settings - this is the "current settings pass".
  27. # - When the slice is done, we update the current print time and material amount.
  28. # - 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.
  29. # - When that is done, we update the minimum print time and start the final slice pass, the "Extra Fine settings pass".
  30. # - When the Extra Fine pass is done, we update the maximum print time.
  31. #
  32. # This class also mangles the current machine name and the filename of the first loaded mesh into a job name.
  33. # This job name is requested by the JobSpecs qml file.
  34. class PrintInformation(QObject):
  35. class SlicePass:
  36. CurrentSettings = 1
  37. LowQualitySettings = 2
  38. HighQualitySettings = 3
  39. class SliceReason:
  40. SceneChanged = 1
  41. SettingChanged = 2
  42. ActiveMachineChanged = 3
  43. Other = 4
  44. def __init__(self, parent = None):
  45. super().__init__(parent)
  46. self.initializeCuraMessagePrintTimeProperties()
  47. self._material_lengths = {} # indexed by build plate number
  48. self._material_weights = {}
  49. self._material_costs = {}
  50. self._material_names = {}
  51. self._pre_sliced = False
  52. self._backend = Application.getInstance().getBackend()
  53. if self._backend:
  54. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  55. Application.getInstance().getController().getScene().sceneChanged.connect(self._onSceneChanged)
  56. self._is_user_specified_job_name = False
  57. self._base_name = ""
  58. self._abbr_machine = ""
  59. self._job_name = ""
  60. self._project_name = ""
  61. self._active_build_plate = 0
  62. self._initVariablesWithBuildPlate(self._active_build_plate)
  63. self._application = Application.getInstance()
  64. self._multi_build_plate_model = self._application.getMultiBuildPlateModel()
  65. self._application.globalContainerStackChanged.connect(self._updateJobName)
  66. self._application.globalContainerStackChanged.connect(self.setToZeroPrintInformation)
  67. self._application.fileLoaded.connect(self.setBaseName)
  68. self._application.workspaceLoaded.connect(self.setProjectName)
  69. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveBuildPlateChanged)
  70. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  71. self._application.getMachineManager().rootMaterialChanged.connect(self._onActiveMaterialsChanged)
  72. self._onActiveMaterialsChanged()
  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._updateJobName()
  118. self.preSlicedChanged.emit()
  119. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  120. def currentPrintTime(self):
  121. return self._current_print_time[self._active_build_plate]
  122. materialLengthsChanged = pyqtSignal()
  123. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  124. def materialLengths(self):
  125. return self._material_lengths[self._active_build_plate]
  126. materialWeightsChanged = pyqtSignal()
  127. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  128. def materialWeights(self):
  129. return self._material_weights[self._active_build_plate]
  130. materialCostsChanged = pyqtSignal()
  131. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  132. def materialCosts(self):
  133. return self._material_costs[self._active_build_plate]
  134. materialNamesChanged = pyqtSignal()
  135. @pyqtProperty("QVariantList", notify = materialNamesChanged)
  136. def materialNames(self):
  137. return self._material_names[self._active_build_plate]
  138. def printTimes(self):
  139. return self._print_time_message_values[self._active_build_plate]
  140. def _onPrintDurationMessage(self, build_plate_number, print_time: Dict[str, int], material_amounts: list):
  141. self._updateTotalPrintTimePerFeature(build_plate_number, print_time)
  142. self.currentPrintTimeChanged.emit()
  143. self._material_amounts = material_amounts
  144. self._calculateInformation(build_plate_number)
  145. def _updateTotalPrintTimePerFeature(self, build_plate_number, print_time: Dict[str, int]):
  146. total_estimated_time = 0
  147. if build_plate_number not in self._print_time_message_values:
  148. self._initPrintTimeMessageValues(build_plate_number)
  149. for feature, time in print_time.items():
  150. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  151. self._print_time_message_values[build_plate_number].get(feature).setDuration(0)
  152. Logger.log("w", "Received NaN for print duration message")
  153. continue
  154. total_estimated_time += time
  155. self._print_time_message_values[build_plate_number].get(feature).setDuration(time)
  156. if build_plate_number not in self._current_print_time:
  157. self._current_print_time[build_plate_number] = Duration(None, self)
  158. self._current_print_time[build_plate_number].setDuration(total_estimated_time)
  159. def _calculateInformation(self, build_plate_number):
  160. global_stack = Application.getInstance().getGlobalContainerStack()
  161. if global_stack is None:
  162. return
  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 = global_stack.extruders
  169. for position, extruder_stack in extruder_stacks.items():
  170. index = int(position)
  171. if index >= len(self._material_amounts):
  172. continue
  173. amount = self._material_amounts[index]
  174. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  175. # list comprehension filtering to solve this for us.
  176. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  177. material = extruder_stack.findContainer({"type": "material"})
  178. radius = extruder_stack.getProperty("material_diameter", "value") / 2
  179. weight = float(amount) * float(density) / 1000
  180. cost = 0
  181. material_name = catalog.i18nc("@label unknown material", "Unknown")
  182. if material:
  183. material_guid = material.getMetaDataEntry("GUID")
  184. material_name = material.getName()
  185. if material_guid in material_preference_values:
  186. material_values = material_preference_values[material_guid]
  187. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  188. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  189. if weight_per_spool != 0:
  190. cost = cost_per_spool * weight / weight_per_spool
  191. else:
  192. cost = 0
  193. # Material amount is sent as an amount of mm^3, so calculate length from that
  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(self._multi_build_plate_model.maxBuildPlate + 1):
  210. self._calculateInformation(build_plate_number)
  211. def _onActiveBuildPlateChanged(self):
  212. new_active_build_plate = self._multi_build_plate_model.activeBuildPlate
  213. if new_active_build_plate != self._active_build_plate:
  214. self._active_build_plate = new_active_build_plate
  215. self._initVariablesWithBuildPlate(self._active_build_plate)
  216. self.materialLengthsChanged.emit()
  217. self.materialWeightsChanged.emit()
  218. self.materialCostsChanged.emit()
  219. self.materialNamesChanged.emit()
  220. self.currentPrintTimeChanged.emit()
  221. def _onActiveMaterialsChanged(self, *args, **kwargs):
  222. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  223. self._calculateInformation(build_plate_number)
  224. # Manual override of job name should also set the base name so that when the printer prefix is updated, it the
  225. # prefix can be added to the manually added name, not the old base name
  226. @pyqtSlot(str, bool)
  227. def setJobName(self, name, is_user_specified_job_name = False):
  228. self._is_user_specified_job_name = is_user_specified_job_name
  229. self._job_name = name
  230. self._base_name = name.replace(self._abbr_machine + "_", "")
  231. if name == "":
  232. self._is_user_specified_job_name = False
  233. self.jobNameChanged.emit()
  234. jobNameChanged = pyqtSignal()
  235. @pyqtProperty(str, notify = jobNameChanged)
  236. def jobName(self):
  237. return self._job_name
  238. def _updateJobName(self):
  239. if self._base_name == "":
  240. self._job_name = "unnamed"
  241. self._is_user_specified_job_name = False
  242. self.jobNameChanged.emit()
  243. return
  244. base_name = self._stripAccents(self._base_name)
  245. self._setAbbreviatedMachineName()
  246. # Only update the job name when it's not user-specified.
  247. if not self._is_user_specified_job_name:
  248. if self._pre_sliced:
  249. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  250. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  251. # Don't add abbreviation if it already has the exact same abbreviation.
  252. if base_name.startswith(self._abbr_machine + "_"):
  253. self._job_name = base_name
  254. else:
  255. self._job_name = self._abbr_machine + "_" + base_name
  256. else:
  257. self._job_name = base_name
  258. self.jobNameChanged.emit()
  259. @pyqtSlot(str)
  260. def setProjectName(self, name):
  261. self.setBaseName(name, is_project_file = True)
  262. baseNameChanged = pyqtSignal()
  263. def setBaseName(self, base_name: str, is_project_file: bool = False):
  264. self._is_user_specified_job_name = False
  265. # Ensure that we don't use entire path but only filename
  266. name = os.path.basename(base_name)
  267. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  268. # extension. This cuts the extension off if necessary.
  269. check_name = os.path.splitext(name)[0]
  270. filename_parts = os.path.basename(base_name).split(".")
  271. # If it's a gcode, also always update the job name
  272. is_gcode = False
  273. if len(filename_parts) > 1:
  274. # Only check the extension(s)
  275. is_gcode = "gcode" in filename_parts[1:]
  276. # if this is a profile file, always update the job name
  277. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  278. is_empty = check_name == ""
  279. if is_gcode or is_project_file or (is_empty or (self._base_name == "" and self._base_name != check_name)):
  280. # Only take the file name part, Note : file name might have 'dot' in name as well
  281. data = ""
  282. try:
  283. mime_type = MimeTypeDatabase.getMimeTypeForFile(name)
  284. data = mime_type.stripExtension(name)
  285. except:
  286. Logger.log("w", "Unsupported Mime Type Database file extension %s", name)
  287. if data is not None and check_name is not None:
  288. self._base_name = data
  289. else:
  290. self._base_name = ""
  291. self._updateJobName()
  292. @pyqtProperty(str, fset = setBaseName, notify = baseNameChanged)
  293. def baseName(self):
  294. return self._base_name
  295. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  296. # Called each time the global stack is switched
  297. def _setAbbreviatedMachineName(self):
  298. global_container_stack = Application.getInstance().getGlobalContainerStack()
  299. if not global_container_stack:
  300. self._abbr_machine = ""
  301. return
  302. active_machine_type_name = global_container_stack.definition.getName()
  303. abbr_machine = ""
  304. for word in re.findall(r"[\w']+", active_machine_type_name):
  305. if word.lower() == "ultimaker":
  306. abbr_machine += "UM"
  307. elif word.isdigit():
  308. abbr_machine += word
  309. else:
  310. stripped_word = self._stripAccents(word.upper())
  311. # - use only the first character if the word is too long (> 3 characters)
  312. # - use the whole word if it's not too long (<= 3 characters)
  313. if len(stripped_word) > 3:
  314. stripped_word = stripped_word[0]
  315. abbr_machine += stripped_word
  316. self._abbr_machine = abbr_machine
  317. ## Utility method that strips accents from characters (eg: â -> a)
  318. def _stripAccents(self, str):
  319. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
  320. @pyqtSlot(result = "QVariantMap")
  321. def getFeaturePrintTimes(self):
  322. result = {}
  323. if self._active_build_plate not in self._print_time_message_values:
  324. self._initPrintTimeMessageValues(self._active_build_plate)
  325. for feature, time in self._print_time_message_values[self._active_build_plate].items():
  326. if feature in self._print_time_message_translations:
  327. result[self._print_time_message_translations[feature]] = time
  328. else:
  329. result[feature] = time
  330. return result
  331. # Simulate message with zero time duration
  332. def setToZeroPrintInformation(self, build_plate = None):
  333. if build_plate is None:
  334. build_plate = self._active_build_plate
  335. # Construct the 0-time message
  336. temp_message = {}
  337. if build_plate not in self._print_time_message_values:
  338. self._print_time_message_values[build_plate] = {}
  339. for key in self._print_time_message_values[build_plate].keys():
  340. temp_message[key] = 0
  341. temp_material_amounts = [0]
  342. self._onPrintDurationMessage(build_plate, temp_message, temp_material_amounts)
  343. ## Listen to scene changes to check if we need to reset the print information
  344. def _onSceneChanged(self, scene_node):
  345. # Ignore any changes that are not related to sliceable objects
  346. if not isinstance(scene_node, SceneNode)\
  347. or not scene_node.callDecoration("isSliceable")\
  348. or not scene_node.callDecoration("getBuildPlateNumber") == self._active_build_plate:
  349. return
  350. self.setToZeroPrintInformation(self._active_build_plate)