PrintInformation.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import math
  5. import os
  6. import unicodedata
  7. import re # To create abbreviations for printer names.
  8. from typing import Dict, List, Optional
  9. from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot
  10. from UM.Logger import Logger
  11. from UM.Qt.Duration import Duration
  12. from UM.Scene.SceneNode import SceneNode
  13. from UM.i18n import i18nCatalog
  14. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeTypeNotFoundError
  15. from typing import TYPE_CHECKING
  16. if TYPE_CHECKING:
  17. from cura.CuraApplication import CuraApplication
  18. catalog = i18nCatalog("cura")
  19. ## A class for processing and the print times per build plate as well as managing the job name
  20. #
  21. # This class also mangles the current machine name and the filename of the first loaded mesh into a job name.
  22. # This job name is requested by the JobSpecs qml file.
  23. class PrintInformation(QObject):
  24. UNTITLED_JOB_NAME = "Untitled"
  25. def __init__(self, application: "CuraApplication", parent = None) -> None:
  26. super().__init__(parent)
  27. self._application = application
  28. self.initializeCuraMessagePrintTimeProperties()
  29. # Indexed by build plate number
  30. self._material_lengths = {} # type: Dict[int, List[float]]
  31. self._material_weights = {} # type: Dict[int, List[float]]
  32. self._material_costs = {} # type: Dict[int, List[float]]
  33. self._material_names = {} # type: Dict[int, List[str]]
  34. self._pre_sliced = False
  35. self._backend = self._application.getBackend()
  36. if self._backend:
  37. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  38. self._application.getController().getScene().sceneChanged.connect(self._onSceneChanged)
  39. self._is_user_specified_job_name = False
  40. self._base_name = ""
  41. self._abbr_machine = ""
  42. self._job_name = ""
  43. self._active_build_plate = 0
  44. self._initVariablesByBuildPlate(self._active_build_plate)
  45. self._multi_build_plate_model = self._application.getMultiBuildPlateModel()
  46. self._application.globalContainerStackChanged.connect(self._updateJobName)
  47. self._application.globalContainerStackChanged.connect(self.setToZeroPrintInformation)
  48. self._application.fileLoaded.connect(self.setBaseName)
  49. self._application.workspaceLoaded.connect(self.setProjectName)
  50. self._application.getMachineManager().rootMaterialChanged.connect(self._onActiveMaterialsChanged)
  51. self._application.getInstance().getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  52. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveBuildPlateChanged)
  53. self._onActiveMaterialsChanged()
  54. self._material_amounts = [] # type: List[float]
  55. def initializeCuraMessagePrintTimeProperties(self) -> None:
  56. self._current_print_time = {} # type: Dict[int, Duration]
  57. self._print_time_message_translations = {
  58. "inset_0": catalog.i18nc("@tooltip", "Outer Wall"),
  59. "inset_x": catalog.i18nc("@tooltip", "Inner Walls"),
  60. "skin": catalog.i18nc("@tooltip", "Skin"),
  61. "infill": catalog.i18nc("@tooltip", "Infill"),
  62. "support_infill": catalog.i18nc("@tooltip", "Support Infill"),
  63. "support_interface": catalog.i18nc("@tooltip", "Support Interface"),
  64. "support": catalog.i18nc("@tooltip", "Support"),
  65. "skirt": catalog.i18nc("@tooltip", "Skirt"),
  66. "travel": catalog.i18nc("@tooltip", "Travel"),
  67. "retract": catalog.i18nc("@tooltip", "Retractions"),
  68. "none": catalog.i18nc("@tooltip", "Other")
  69. }
  70. self._print_times_per_feature = {} # type: Dict[int, Dict[str, Duration]]
  71. def _initPrintTimesPerFeature(self, build_plate_number: int) -> None:
  72. # Full fill message values using keys from _print_time_message_translations
  73. self._print_times_per_feature[build_plate_number] = {}
  74. for key in self._print_time_message_translations.keys():
  75. self._print_times_per_feature[build_plate_number][key] = Duration(None, self)
  76. def _initVariablesByBuildPlate(self, build_plate_number: int) -> None:
  77. if build_plate_number not in self._print_times_per_feature:
  78. self._initPrintTimesPerFeature(build_plate_number)
  79. if self._active_build_plate not in self._material_lengths:
  80. self._material_lengths[self._active_build_plate] = []
  81. if self._active_build_plate not in self._material_weights:
  82. self._material_weights[self._active_build_plate] = []
  83. if self._active_build_plate not in self._material_costs:
  84. self._material_costs[self._active_build_plate] = []
  85. if self._active_build_plate not in self._material_names:
  86. self._material_names[self._active_build_plate] = []
  87. if self._active_build_plate not in self._current_print_time:
  88. self._current_print_time[self._active_build_plate] = Duration(parent = self)
  89. currentPrintTimeChanged = pyqtSignal()
  90. preSlicedChanged = pyqtSignal()
  91. @pyqtProperty(bool, notify=preSlicedChanged)
  92. def preSliced(self) -> bool:
  93. return self._pre_sliced
  94. def setPreSliced(self, pre_sliced: bool) -> None:
  95. if self._pre_sliced != pre_sliced:
  96. self._pre_sliced = pre_sliced
  97. self._updateJobName()
  98. self.preSlicedChanged.emit()
  99. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  100. def currentPrintTime(self) -> Duration:
  101. return self._current_print_time[self._active_build_plate]
  102. materialLengthsChanged = pyqtSignal()
  103. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  104. def materialLengths(self):
  105. return self._material_lengths[self._active_build_plate]
  106. materialWeightsChanged = pyqtSignal()
  107. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  108. def materialWeights(self):
  109. return self._material_weights[self._active_build_plate]
  110. materialCostsChanged = pyqtSignal()
  111. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  112. def materialCosts(self):
  113. return self._material_costs[self._active_build_plate]
  114. materialNamesChanged = pyqtSignal()
  115. @pyqtProperty("QVariantList", notify = materialNamesChanged)
  116. def materialNames(self):
  117. return self._material_names[self._active_build_plate]
  118. # Get all print times (by feature) of the active buildplate.
  119. def printTimes(self) -> Dict[str, Duration]:
  120. return self._print_times_per_feature[self._active_build_plate]
  121. def _onPrintDurationMessage(self, build_plate_number: int, print_times_per_feature: Dict[str, int], material_amounts: List[float]) -> None:
  122. self._updateTotalPrintTimePerFeature(build_plate_number, print_times_per_feature)
  123. self.currentPrintTimeChanged.emit()
  124. self._material_amounts = material_amounts
  125. self._calculateInformation(build_plate_number)
  126. def _updateTotalPrintTimePerFeature(self, build_plate_number: int, print_times_per_feature: Dict[str, int]) -> None:
  127. total_estimated_time = 0
  128. if build_plate_number not in self._print_times_per_feature:
  129. self._initPrintTimesPerFeature(build_plate_number)
  130. for feature, time in print_times_per_feature.items():
  131. if feature not in self._print_times_per_feature[build_plate_number]:
  132. self._print_times_per_feature[build_plate_number][feature] = Duration(parent=self)
  133. duration = self._print_times_per_feature[build_plate_number][feature]
  134. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  135. duration.setDuration(0)
  136. Logger.log("w", "Received NaN for print duration message")
  137. continue
  138. total_estimated_time += time
  139. duration.setDuration(time)
  140. if build_plate_number not in self._current_print_time:
  141. self._current_print_time[build_plate_number] = Duration(None, self)
  142. self._current_print_time[build_plate_number].setDuration(total_estimated_time)
  143. def _calculateInformation(self, build_plate_number: int) -> None:
  144. global_stack = self._application.getGlobalContainerStack()
  145. if global_stack is None:
  146. return
  147. self._material_lengths[build_plate_number] = []
  148. self._material_weights[build_plate_number] = []
  149. self._material_costs[build_plate_number] = []
  150. self._material_names[build_plate_number] = []
  151. material_preference_values = json.loads(self._application.getInstance().getPreferences().getValue("cura/material_settings"))
  152. extruder_stacks = global_stack.extruders
  153. for position in extruder_stacks:
  154. extruder_stack = extruder_stacks[position]
  155. index = int(position)
  156. if index >= len(self._material_amounts):
  157. continue
  158. amount = self._material_amounts[index]
  159. # Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  160. # list comprehension filtering to solve this for us.
  161. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  162. material = extruder_stack.material
  163. radius = extruder_stack.getProperty("material_diameter", "value") / 2
  164. weight = float(amount) * float(density) / 1000
  165. cost = 0.
  166. material_guid = material.getMetaDataEntry("GUID")
  167. material_name = material.getName()
  168. if material_guid in material_preference_values:
  169. material_values = material_preference_values[material_guid]
  170. if material_values and "spool_weight" in material_values:
  171. weight_per_spool = float(material_values["spool_weight"])
  172. else:
  173. weight_per_spool = float(extruder_stack.getMetaDataEntry("properties", {}).get("weight", 0))
  174. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  175. if weight_per_spool != 0:
  176. cost = cost_per_spool * weight / weight_per_spool
  177. else:
  178. cost = 0
  179. # Material amount is sent as an amount of mm^3, so calculate length from that
  180. if radius != 0:
  181. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  182. else:
  183. length = 0
  184. self._material_weights[build_plate_number].append(weight)
  185. self._material_lengths[build_plate_number].append(length)
  186. self._material_costs[build_plate_number].append(cost)
  187. self._material_names[build_plate_number].append(material_name)
  188. self.materialLengthsChanged.emit()
  189. self.materialWeightsChanged.emit()
  190. self.materialCostsChanged.emit()
  191. self.materialNamesChanged.emit()
  192. def _onPreferencesChanged(self, preference: str) -> None:
  193. if preference != "cura/material_settings":
  194. return
  195. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  196. self._calculateInformation(build_plate_number)
  197. def _onActiveBuildPlateChanged(self) -> None:
  198. new_active_build_plate = self._multi_build_plate_model.activeBuildPlate
  199. if new_active_build_plate != self._active_build_plate:
  200. self._active_build_plate = new_active_build_plate
  201. self._updateJobName()
  202. self._initVariablesByBuildPlate(self._active_build_plate)
  203. self.materialLengthsChanged.emit()
  204. self.materialWeightsChanged.emit()
  205. self.materialCostsChanged.emit()
  206. self.materialNamesChanged.emit()
  207. self.currentPrintTimeChanged.emit()
  208. def _onActiveMaterialsChanged(self, *args, **kwargs) -> None:
  209. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  210. self._calculateInformation(build_plate_number)
  211. # Manual override of job name should also set the base name so that when the printer prefix is updated, it the
  212. # prefix can be added to the manually added name, not the old base name
  213. @pyqtSlot(str, bool)
  214. def setJobName(self, name: str, is_user_specified_job_name = False) -> None:
  215. self._is_user_specified_job_name = is_user_specified_job_name
  216. self._job_name = name
  217. self._base_name = name.replace(self._abbr_machine + "_", "")
  218. if name == "":
  219. self._is_user_specified_job_name = False
  220. self.jobNameChanged.emit()
  221. jobNameChanged = pyqtSignal()
  222. @pyqtProperty(str, notify = jobNameChanged)
  223. def jobName(self):
  224. return self._job_name
  225. def _updateJobName(self) -> None:
  226. if self._base_name == "":
  227. self._job_name = self.UNTITLED_JOB_NAME
  228. self._is_user_specified_job_name = False
  229. self.jobNameChanged.emit()
  230. return
  231. base_name = self._stripAccents(self._base_name)
  232. self._defineAbbreviatedMachineName()
  233. # Only update the job name when it's not user-specified.
  234. if not self._is_user_specified_job_name:
  235. if self._pre_sliced:
  236. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  237. elif self._application.getInstance().getPreferences().getValue("cura/jobname_prefix"):
  238. # Don't add abbreviation if it already has the exact same abbreviation.
  239. if base_name.startswith(self._abbr_machine + "_"):
  240. self._job_name = base_name
  241. else:
  242. self._job_name = self._abbr_machine + "_" + base_name
  243. else:
  244. self._job_name = base_name
  245. # In case there are several buildplates, a suffix is attached
  246. if self._multi_build_plate_model.maxBuildPlate > 0:
  247. connector = "_#"
  248. suffix = connector + str(self._active_build_plate + 1)
  249. if connector in self._job_name:
  250. self._job_name = self._job_name.split(connector)[0] # get the real name
  251. if self._active_build_plate != 0:
  252. self._job_name += suffix
  253. self.jobNameChanged.emit()
  254. @pyqtSlot(str)
  255. def setProjectName(self, name: str) -> None:
  256. self.setBaseName(name, is_project_file = True)
  257. baseNameChanged = pyqtSignal()
  258. def setBaseName(self, base_name: str, is_project_file: bool = False) -> None:
  259. self._is_user_specified_job_name = False
  260. # Ensure that we don't use entire path but only filename
  261. name = os.path.basename(base_name)
  262. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  263. # extension. This cuts the extension off if necessary.
  264. check_name = os.path.splitext(name)[0]
  265. filename_parts = os.path.basename(base_name).split(".")
  266. # If it's a gcode, also always update the job name
  267. is_gcode = False
  268. if len(filename_parts) > 1:
  269. # Only check the extension(s)
  270. is_gcode = "gcode" in filename_parts[1:]
  271. # if this is a profile file, always update the job name
  272. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  273. is_empty = check_name == ""
  274. if is_gcode or is_project_file or (is_empty or (self._base_name == "" and self._base_name != check_name)):
  275. # Only take the file name part, Note : file name might have 'dot' in name as well
  276. data = ""
  277. try:
  278. mime_type = MimeTypeDatabase.getMimeTypeForFile(name)
  279. data = mime_type.stripExtension(name)
  280. except MimeTypeNotFoundError:
  281. Logger.log("w", "Unsupported Mime Type Database file extension %s", name)
  282. if data is not None and check_name is not None:
  283. self._base_name = data
  284. else:
  285. self._base_name = ""
  286. # Strip the old "curaproject" extension from the name
  287. OLD_CURA_PROJECT_EXT = ".curaproject"
  288. if self._base_name.lower().endswith(OLD_CURA_PROJECT_EXT):
  289. self._base_name = self._base_name[:len(self._base_name) - len(OLD_CURA_PROJECT_EXT)]
  290. # CURA-5896 Try to strip extra extensions with an infinite amount of ".curaproject.3mf".
  291. OLD_CURA_PROJECT_3MF_EXT = ".curaproject.3mf"
  292. while self._base_name.lower().endswith(OLD_CURA_PROJECT_3MF_EXT):
  293. self._base_name = self._base_name[:len(self._base_name) - len(OLD_CURA_PROJECT_3MF_EXT)]
  294. self._updateJobName()
  295. @pyqtProperty(str, fset = setBaseName, notify = baseNameChanged)
  296. def baseName(self):
  297. return self._base_name
  298. ## Created an acronym-like abbreviated machine name from the currently
  299. # active machine name.
  300. # Called each time the global stack is switched.
  301. def _defineAbbreviatedMachineName(self) -> None:
  302. global_container_stack = self._application.getGlobalContainerStack()
  303. if not global_container_stack:
  304. self._abbr_machine = ""
  305. return
  306. active_machine_type_name = global_container_stack.definition.getName()
  307. self._abbr_machine = self._application.getMachineManager().getAbbreviatedMachineName(active_machine_type_name)
  308. ## Utility method that strips accents from characters (eg: â -> a)
  309. def _stripAccents(self, to_strip: str) -> str:
  310. return ''.join(char for char in unicodedata.normalize('NFD', to_strip) if unicodedata.category(char) != 'Mn')
  311. @pyqtSlot(result = "QVariantMap")
  312. def getFeaturePrintTimes(self) -> Dict[str, Duration]:
  313. result = {}
  314. if self._active_build_plate not in self._print_times_per_feature:
  315. self._initPrintTimesPerFeature(self._active_build_plate)
  316. for feature, time in self._print_times_per_feature[self._active_build_plate].items():
  317. if feature in self._print_time_message_translations:
  318. result[self._print_time_message_translations[feature]] = time
  319. else:
  320. result[feature] = time
  321. return result
  322. # Simulate message with zero time duration
  323. def setToZeroPrintInformation(self, build_plate: Optional[int] = None) -> None:
  324. if build_plate is None:
  325. build_plate = self._active_build_plate
  326. # Construct the 0-time message
  327. temp_message = {}
  328. if build_plate not in self._print_times_per_feature:
  329. self._print_times_per_feature[build_plate] = {}
  330. for key in self._print_times_per_feature[build_plate].keys():
  331. temp_message[key] = 0
  332. temp_material_amounts = [0.]
  333. self._onPrintDurationMessage(build_plate, temp_message, temp_material_amounts)
  334. ## Listen to scene changes to check if we need to reset the print information
  335. def _onSceneChanged(self, scene_node: SceneNode) -> None:
  336. # Ignore any changes that are not related to sliceable objects
  337. if not isinstance(scene_node, SceneNode)\
  338. or not scene_node.callDecoration("isSliceable")\
  339. or not scene_node.callDecoration("getBuildPlateNumber") == self._active_build_plate:
  340. return
  341. self.setToZeroPrintInformation(self._active_build_plate)