PrintInformation.py 19 KB

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