ThreeMFWorkspaceReader.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from configparser import ConfigParser
  4. import zipfile
  5. import os
  6. import json
  7. from typing import cast, Dict, List, Optional, Tuple, Any
  8. import xml.etree.ElementTree as ET
  9. from UM.Workspace.WorkspaceReader import WorkspaceReader
  10. from UM.Application import Application
  11. from UM.Logger import Logger
  12. from UM.Message import Message
  13. from UM.i18n import i18nCatalog
  14. from UM.Settings.ContainerFormatError import ContainerFormatError
  15. from UM.Settings.ContainerStack import ContainerStack
  16. from UM.Settings.DefinitionContainer import DefinitionContainer
  17. from UM.Settings.InstanceContainer import InstanceContainer
  18. from UM.Settings.ContainerRegistry import ContainerRegistry
  19. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  20. from UM.Job import Job
  21. from UM.Preferences import Preferences
  22. from cura.Machines.ContainerTree import ContainerTree
  23. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  24. from cura.Settings.ExtruderManager import ExtruderManager
  25. from cura.Settings.ExtruderStack import ExtruderStack
  26. from cura.Settings.GlobalStack import GlobalStack
  27. from cura.Settings.IntentManager import IntentManager
  28. from cura.Settings.CuraContainerStack import _ContainerIndexes
  29. from cura.CuraApplication import CuraApplication
  30. from cura.Utils.Threading import call_on_qt_thread
  31. from PyQt5.QtCore import QCoreApplication
  32. from .WorkspaceDialog import WorkspaceDialog
  33. i18n_catalog = i18nCatalog("cura")
  34. class ContainerInfo:
  35. def __init__(self, file_name: Optional[str], serialized: Optional[str], parser: Optional[ConfigParser]) -> None:
  36. self.file_name = file_name
  37. self.serialized = serialized
  38. self.parser = parser
  39. self.container = None
  40. self.definition_id = None
  41. class QualityChangesInfo:
  42. def __init__(self) -> None:
  43. self.name = None
  44. self.global_info = None
  45. self.extruder_info_dict = {} # type: Dict[str, ContainerInfo]
  46. class MachineInfo:
  47. def __init__(self) -> None:
  48. self.container_id = None
  49. self.name = None
  50. self.definition_id = None
  51. self.metadata_dict = {} # type: Dict[str, str]
  52. self.quality_type = None
  53. self.intent_category = None
  54. self.custom_quality_name = None
  55. self.quality_changes_info = None
  56. self.variant_info = None
  57. self.definition_changes_info = None
  58. self.user_changes_info = None
  59. self.extruder_info_dict = {} # type: Dict[str, ExtruderInfo]
  60. class ExtruderInfo:
  61. def __init__(self) -> None:
  62. self.position = None
  63. self.enabled = True
  64. self.variant_info = None
  65. self.root_material_id = None
  66. self.definition_changes_info = None
  67. self.user_changes_info = None
  68. self.intent_info = None
  69. ## Base implementation for reading 3MF workspace files.
  70. class ThreeMFWorkspaceReader(WorkspaceReader):
  71. def __init__(self) -> None:
  72. super().__init__()
  73. self._supported_extensions = [".3mf"]
  74. self._dialog = WorkspaceDialog()
  75. self._3mf_mesh_reader = None
  76. self._container_registry = ContainerRegistry.getInstance()
  77. # suffixes registered with the MimeTypes don't start with a dot '.'
  78. self._definition_container_suffix = "." + cast(MimeType, ContainerRegistry.getMimeTypeForContainer(DefinitionContainer)).preferredSuffix
  79. self._material_container_suffix = None # We have to wait until all other plugins are loaded before we can set it
  80. self._instance_container_suffix = "." + cast(MimeType, ContainerRegistry.getMimeTypeForContainer(InstanceContainer)).preferredSuffix
  81. self._container_stack_suffix = "." + cast(MimeType, ContainerRegistry.getMimeTypeForContainer(ContainerStack)).preferredSuffix
  82. self._extruder_stack_suffix = "." + cast(MimeType, ContainerRegistry.getMimeTypeForContainer(ExtruderStack)).preferredSuffix
  83. self._global_stack_suffix = "." + cast(MimeType, ContainerRegistry.getMimeTypeForContainer(GlobalStack)).preferredSuffix
  84. # Certain instance container types are ignored because we make the assumption that only we make those types
  85. # of containers. They are:
  86. # - quality
  87. # - variant
  88. self._ignored_instance_container_types = {"quality", "variant"}
  89. self._resolve_strategies = {} # type: Dict[str, str]
  90. self._id_mapping = {} # type: Dict[str, str]
  91. # In Cura 2.5 and 2.6, the empty profiles used to have those long names
  92. self._old_empty_profile_id_dict = {"empty_%s" % k: "empty" for k in ["material", "variant"]}
  93. self._is_same_machine_type = False
  94. self._old_new_materials = {} # type: Dict[str, str]
  95. self._machine_info = None
  96. def _clearState(self):
  97. self._is_same_machine_type = False
  98. self._id_mapping = {}
  99. self._old_new_materials = {}
  100. self._machine_info = None
  101. ## Get a unique name based on the old_id. This is different from directly calling the registry in that it caches results.
  102. # This has nothing to do with speed, but with getting consistent new naming for instances & objects.
  103. def getNewId(self, old_id: str):
  104. if old_id not in self._id_mapping:
  105. self._id_mapping[old_id] = self._container_registry.uniqueName(old_id)
  106. return self._id_mapping[old_id]
  107. ## Separates the given file list into a list of GlobalStack files and a list of ExtruderStack files.
  108. #
  109. # In old versions, extruder stack files have the same suffix as container stack files ".stack.cfg".
  110. #
  111. def _determineGlobalAndExtruderStackFiles(self, project_file_name: str, file_list: List[str]) -> Tuple[str, List[str]]:
  112. archive = zipfile.ZipFile(project_file_name, "r")
  113. global_stack_file_list = [name for name in file_list if name.endswith(self._global_stack_suffix)]
  114. extruder_stack_file_list = [name for name in file_list if name.endswith(self._extruder_stack_suffix)]
  115. # separate container stack files and extruder stack files
  116. files_to_determine = [name for name in file_list if name.endswith(self._container_stack_suffix)]
  117. for file_name in files_to_determine:
  118. # FIXME: HACK!
  119. # We need to know the type of the stack file, but we can only know it if we deserialize it.
  120. # The default ContainerStack.deserialize() will connect signals, which is not desired in this case.
  121. # Since we know that the stack files are INI files, so we directly use the ConfigParser to parse them.
  122. serialized = archive.open(file_name).read().decode("utf-8")
  123. stack_config = ConfigParser(interpolation = None)
  124. stack_config.read_string(serialized)
  125. # sanity check
  126. if not stack_config.has_option("metadata", "type"):
  127. Logger.log("e", "%s in %s doesn't seem to be valid stack file", file_name, project_file_name)
  128. continue
  129. stack_type = stack_config.get("metadata", "type")
  130. if stack_type == "extruder_train":
  131. extruder_stack_file_list.append(file_name)
  132. elif stack_type == "machine":
  133. global_stack_file_list.append(file_name)
  134. else:
  135. Logger.log("w", "Unknown container stack type '%s' from %s in %s",
  136. stack_type, file_name, project_file_name)
  137. if len(global_stack_file_list) > 1:
  138. Logger.log("e", "More than one global stack file found: [{file_list}]".format(file_list = global_stack_file_list))
  139. #But we can recover by just getting the first global stack file.
  140. if len(global_stack_file_list) == 0:
  141. Logger.log("e", "No global stack file found!")
  142. raise FileNotFoundError("No global stack file found!")
  143. return global_stack_file_list[0], extruder_stack_file_list
  144. ## read some info so we can make decisions
  145. # \param file_name
  146. # \param show_dialog In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  147. def preRead(self, file_name, show_dialog=True, *args, **kwargs):
  148. self._clearState()
  149. self._3mf_mesh_reader = Application.getInstance().getMeshFileHandler().getReaderForFile(file_name)
  150. if self._3mf_mesh_reader and self._3mf_mesh_reader.preRead(file_name) == WorkspaceReader.PreReadResult.accepted:
  151. pass
  152. else:
  153. Logger.log("w", "Could not find reader that was able to read the scene data for 3MF workspace")
  154. return WorkspaceReader.PreReadResult.failed
  155. self._machine_info = MachineInfo()
  156. machine_type = ""
  157. variant_type_name = i18n_catalog.i18nc("@label", "Nozzle")
  158. # Check if there are any conflicts, so we can ask the user.
  159. archive = zipfile.ZipFile(file_name, "r")
  160. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  161. resolve_strategy_keys = ["machine", "material", "quality_changes"]
  162. self._resolve_strategies = {k: None for k in resolve_strategy_keys}
  163. containers_found_dict = {k: False for k in resolve_strategy_keys}
  164. #
  165. # Read definition containers
  166. #
  167. machine_definition_id = None
  168. machine_definition_container_count = 0
  169. extruder_definition_container_count = 0
  170. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  171. for definition_container_file in definition_container_files:
  172. container_id = self._stripFileToId(definition_container_file)
  173. definitions = self._container_registry.findDefinitionContainersMetadata(id = container_id)
  174. serialized = archive.open(definition_container_file).read().decode("utf-8")
  175. if not definitions:
  176. definition_container = DefinitionContainer.deserializeMetadata(serialized, container_id)[0]
  177. else:
  178. definition_container = definitions[0]
  179. definition_container_type = definition_container.get("type")
  180. if definition_container_type == "machine":
  181. machine_definition_id = container_id
  182. machine_type = definition_container["name"]
  183. variant_type_name = definition_container.get("variants_name", variant_type_name)
  184. machine_definition_container_count += 1
  185. elif definition_container_type == "extruder":
  186. extruder_definition_container_count += 1
  187. else:
  188. Logger.log("w", "Unknown definition container type %s for %s",
  189. definition_container_type, definition_container_file)
  190. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  191. Job.yieldThread()
  192. if machine_definition_container_count != 1:
  193. return WorkspaceReader.PreReadResult.failed # Not a workspace file but ordinary 3MF.
  194. material_labels = []
  195. material_conflict = False
  196. xml_material_profile = self._getXmlProfileClass()
  197. reverse_material_id_dict = {}
  198. if self._material_container_suffix is None:
  199. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).preferredSuffix
  200. if xml_material_profile:
  201. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  202. for material_container_file in material_container_files:
  203. container_id = self._stripFileToId(material_container_file)
  204. serialized = archive.open(material_container_file).read().decode("utf-8")
  205. metadata_list = xml_material_profile.deserializeMetadata(serialized, container_id)
  206. reverse_map = {metadata["id"]: container_id for metadata in metadata_list}
  207. reverse_material_id_dict.update(reverse_map)
  208. material_labels.append(self._getMaterialLabelFromSerialized(serialized))
  209. if self._container_registry.findContainersMetadata(id = container_id): #This material already exists.
  210. containers_found_dict["material"] = True
  211. if not self._container_registry.isReadOnly(container_id): # Only non readonly materials can be in conflict
  212. material_conflict = True
  213. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  214. Job.yieldThread()
  215. # Check if any quality_changes instance container is in conflict.
  216. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  217. quality_name = ""
  218. custom_quality_name = ""
  219. intent_name = ""
  220. intent_category = ""
  221. num_settings_overridden_by_quality_changes = 0 # How many settings are changed by the quality changes
  222. num_user_settings = 0
  223. quality_changes_conflict = False
  224. self._machine_info.quality_changes_info = QualityChangesInfo()
  225. quality_changes_info_list = []
  226. instance_container_info_dict = {} # id -> parser
  227. for instance_container_file_name in instance_container_files:
  228. container_id = self._stripFileToId(instance_container_file_name)
  229. serialized = archive.open(instance_container_file_name).read().decode("utf-8")
  230. # Qualities and variants don't have upgrades, so don't upgrade them
  231. parser = ConfigParser(interpolation = None, comment_prefixes = ())
  232. parser.read_string(serialized)
  233. container_type = parser["metadata"]["type"]
  234. if container_type not in ("quality", "variant"):
  235. serialized = InstanceContainer._updateSerialized(serialized, instance_container_file_name)
  236. parser = ConfigParser(interpolation = None, comment_prefixes = ())
  237. parser.read_string(serialized)
  238. container_info = ContainerInfo(instance_container_file_name, serialized, parser)
  239. instance_container_info_dict[container_id] = container_info
  240. container_type = parser["metadata"]["type"]
  241. if container_type == "quality_changes":
  242. quality_changes_info_list.append(container_info)
  243. if not parser.has_option("metadata", "position"):
  244. self._machine_info.quality_changes_info.name = parser["general"]["name"]
  245. self._machine_info.quality_changes_info.global_info = container_info
  246. else:
  247. position = parser["metadata"]["position"]
  248. self._machine_info.quality_changes_info.extruder_info_dict[position] = container_info
  249. custom_quality_name = parser["general"]["name"]
  250. values = parser["values"] if parser.has_section("values") else dict()
  251. num_settings_overridden_by_quality_changes += len(values)
  252. # Check if quality changes already exists.
  253. quality_changes = self._container_registry.findInstanceContainers(name = custom_quality_name,
  254. type = "quality_changes")
  255. if quality_changes:
  256. containers_found_dict["quality_changes"] = True
  257. # Check if there really is a conflict by comparing the values
  258. instance_container = InstanceContainer(container_id)
  259. try:
  260. instance_container.deserialize(serialized, file_name = instance_container_file_name)
  261. except ContainerFormatError:
  262. Logger.logException("e", "Failed to deserialize InstanceContainer %s from project file %s",
  263. instance_container_file_name, file_name)
  264. return ThreeMFWorkspaceReader.PreReadResult.failed
  265. if quality_changes[0] != instance_container:
  266. quality_changes_conflict = True
  267. elif container_type == "quality":
  268. if not quality_name:
  269. quality_name = parser["general"]["name"]
  270. elif container_type == "intent":
  271. if not intent_name:
  272. intent_name = parser["general"]["name"]
  273. intent_category = parser["metadata"]["intent_category"]
  274. elif container_type == "user":
  275. num_user_settings += len(parser["values"])
  276. elif container_type in self._ignored_instance_container_types:
  277. # Ignore certain instance container types
  278. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  279. continue
  280. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  281. Job.yieldThread()
  282. if self._machine_info.quality_changes_info.global_info is None:
  283. self._machine_info.quality_changes_info = None
  284. # Load ContainerStack files and ExtruderStack files
  285. try:
  286. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(
  287. file_name, cura_file_names)
  288. except FileNotFoundError:
  289. return WorkspaceReader.PreReadResult.failed
  290. machine_conflict = False
  291. # Because there can be cases as follows:
  292. # - the global stack exists but some/all of the extruder stacks DON'T exist
  293. # - the global stack DOESN'T exist but some/all of the extruder stacks exist
  294. # To simplify this, only check if the global stack exists or not
  295. global_stack_id = self._stripFileToId(global_stack_file)
  296. serialized = archive.open(global_stack_file).read().decode("utf-8")
  297. serialized = GlobalStack._updateSerialized(serialized, global_stack_file)
  298. machine_name = self._getMachineNameFromSerializedStack(serialized)
  299. self._machine_info.metadata_dict = self._getMetaDataDictFromSerializedStack(serialized)
  300. stacks = self._container_registry.findContainerStacks(name = machine_name, type = "machine")
  301. self._is_same_machine_type = True
  302. existing_global_stack = None
  303. if stacks:
  304. global_stack = stacks[0]
  305. existing_global_stack = global_stack
  306. containers_found_dict["machine"] = True
  307. # Check if there are any changes at all in any of the container stacks.
  308. id_list = self._getContainerIdListFromSerialized(serialized)
  309. for index, container_id in enumerate(id_list):
  310. # take into account the old empty container IDs
  311. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  312. if global_stack.getContainer(index).getId() != container_id:
  313. machine_conflict = True
  314. break
  315. self._is_same_machine_type = global_stack.definition.getId() == machine_definition_id
  316. # Get quality type
  317. parser = ConfigParser(interpolation = None)
  318. parser.read_string(serialized)
  319. quality_container_id = parser["containers"][str(_ContainerIndexes.Quality)]
  320. quality_type = "empty_quality"
  321. if quality_container_id not in ("empty", "empty_quality"):
  322. quality_type = instance_container_info_dict[quality_container_id].parser["metadata"]["quality_type"]
  323. # Get machine info
  324. serialized = archive.open(global_stack_file).read().decode("utf-8")
  325. serialized = GlobalStack._updateSerialized(serialized, global_stack_file)
  326. parser = ConfigParser(interpolation = None)
  327. parser.read_string(serialized)
  328. definition_changes_id = parser["containers"][str(_ContainerIndexes.DefinitionChanges)]
  329. if definition_changes_id not in ("empty", "empty_definition_changes"):
  330. self._machine_info.definition_changes_info = instance_container_info_dict[definition_changes_id]
  331. user_changes_id = parser["containers"][str(_ContainerIndexes.UserChanges)]
  332. if user_changes_id not in ("empty", "empty_user_changes"):
  333. self._machine_info.user_changes_info = instance_container_info_dict[user_changes_id]
  334. # Also check variant and material in case it doesn't have extruder stacks
  335. if not extruder_stack_files:
  336. position = "0"
  337. extruder_info = ExtruderInfo()
  338. extruder_info.position = position
  339. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  340. material_id = parser["containers"][str(_ContainerIndexes.Material)]
  341. if variant_id not in ("empty", "empty_variant"):
  342. extruder_info.variant_info = instance_container_info_dict[variant_id]
  343. if material_id not in ("empty", "empty_material"):
  344. root_material_id = reverse_material_id_dict[material_id]
  345. extruder_info.root_material_id = root_material_id
  346. self._machine_info.extruder_info_dict[position] = extruder_info
  347. else:
  348. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  349. if variant_id not in ("empty", "empty_variant"):
  350. self._machine_info.variant_info = instance_container_info_dict[variant_id]
  351. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  352. Job.yieldThread()
  353. # if the global stack is found, we check if there are conflicts in the extruder stacks
  354. for extruder_stack_file in extruder_stack_files:
  355. serialized = archive.open(extruder_stack_file).read().decode("utf-8")
  356. serialized = ExtruderStack._updateSerialized(serialized, extruder_stack_file)
  357. parser = ConfigParser(interpolation = None)
  358. parser.read_string(serialized)
  359. # The check should be done for the extruder stack that's associated with the existing global stack,
  360. # and those extruder stacks may have different IDs.
  361. # So we check according to the positions
  362. position = parser["metadata"]["position"]
  363. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  364. material_id = parser["containers"][str(_ContainerIndexes.Material)]
  365. extruder_info = ExtruderInfo()
  366. extruder_info.position = position
  367. if parser.has_option("metadata", "enabled"):
  368. extruder_info.enabled = parser["metadata"]["enabled"]
  369. if variant_id not in ("empty", "empty_variant"):
  370. if variant_id in instance_container_info_dict:
  371. extruder_info.variant_info = instance_container_info_dict[variant_id]
  372. if material_id not in ("empty", "empty_material"):
  373. root_material_id = reverse_material_id_dict[material_id]
  374. extruder_info.root_material_id = root_material_id
  375. definition_changes_id = parser["containers"][str(_ContainerIndexes.DefinitionChanges)]
  376. if definition_changes_id not in ("empty", "empty_definition_changes"):
  377. extruder_info.definition_changes_info = instance_container_info_dict[definition_changes_id]
  378. user_changes_id = parser["containers"][str(_ContainerIndexes.UserChanges)]
  379. if user_changes_id not in ("empty", "empty_user_changes"):
  380. extruder_info.user_changes_info = instance_container_info_dict[user_changes_id]
  381. self._machine_info.extruder_info_dict[position] = extruder_info
  382. intent_id = parser["containers"][str(_ContainerIndexes.Intent)]
  383. if intent_id not in ("empty", "empty_intent"):
  384. extruder_info.intent_info = instance_container_info_dict[intent_id]
  385. if not machine_conflict and containers_found_dict["machine"]:
  386. if position not in global_stack.extruders:
  387. continue
  388. existing_extruder_stack = global_stack.extruders[position]
  389. # check if there are any changes at all in any of the container stacks.
  390. id_list = self._getContainerIdListFromSerialized(serialized)
  391. for index, container_id in enumerate(id_list):
  392. # take into account the old empty container IDs
  393. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  394. if existing_extruder_stack.getContainer(index).getId() != container_id:
  395. machine_conflict = True
  396. break
  397. num_visible_settings = 0
  398. try:
  399. temp_preferences = Preferences()
  400. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  401. temp_preferences.deserialize(serialized)
  402. visible_settings_string = temp_preferences.getValue("general/visible_settings")
  403. has_visible_settings_string = visible_settings_string is not None
  404. if visible_settings_string is not None:
  405. num_visible_settings = len(visible_settings_string.split(";"))
  406. active_mode = temp_preferences.getValue("cura/active_mode")
  407. if not active_mode:
  408. active_mode = Application.getInstance().getPreferences().getValue("cura/active_mode")
  409. except KeyError:
  410. # If there is no preferences file, it's not a workspace, so notify user of failure.
  411. Logger.log("w", "File %s is not a valid workspace.", file_name)
  412. return WorkspaceReader.PreReadResult.failed
  413. # Check if the machine definition exists. If not, indicate failure because we do not import definition files.
  414. def_results = self._container_registry.findDefinitionContainersMetadata(id = machine_definition_id)
  415. if not def_results:
  416. message = Message(i18n_catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!",
  417. "Project file <filename>{0}</filename> contains an unknown machine type"
  418. " <message>{1}</message>. Cannot import the machine."
  419. " Models will be imported instead.", file_name, machine_definition_id),
  420. title = i18n_catalog.i18nc("@info:title", "Open Project File"))
  421. message.show()
  422. Logger.log("i", "Could unknown machine definition %s in project file %s, cannot import it.",
  423. self._machine_info.definition_id, file_name)
  424. return WorkspaceReader.PreReadResult.failed
  425. # In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  426. if not show_dialog:
  427. return WorkspaceReader.PreReadResult.accepted
  428. # prepare data for the dialog
  429. num_extruders = extruder_definition_container_count
  430. if num_extruders == 0:
  431. num_extruders = 1 # No extruder stacks found, which means there is one extruder
  432. extruders = num_extruders * [""]
  433. quality_name = custom_quality_name if custom_quality_name else quality_name
  434. self._machine_info.container_id = global_stack_id
  435. self._machine_info.name = machine_name
  436. self._machine_info.definition_id = machine_definition_id
  437. self._machine_info.quality_type = quality_type
  438. self._machine_info.custom_quality_name = quality_name
  439. self._machine_info.intent_category = intent_category
  440. if machine_conflict and not self._is_same_machine_type:
  441. machine_conflict = False
  442. is_printer_group = False
  443. if machine_conflict:
  444. group_name = existing_global_stack.getMetaDataEntry("group_name")
  445. if group_name is not None:
  446. is_printer_group = True
  447. machine_name = group_name
  448. # Show the dialog, informing the user what is about to happen.
  449. self._dialog.setMachineConflict(machine_conflict)
  450. self._dialog.setIsPrinterGroup(is_printer_group)
  451. self._dialog.setQualityChangesConflict(quality_changes_conflict)
  452. self._dialog.setMaterialConflict(material_conflict)
  453. self._dialog.setHasVisibleSettingsField(has_visible_settings_string)
  454. self._dialog.setNumVisibleSettings(num_visible_settings)
  455. self._dialog.setQualityName(quality_name)
  456. self._dialog.setQualityType(quality_type)
  457. self._dialog.setIntentName(intent_name)
  458. self._dialog.setNumSettingsOverriddenByQualityChanges(num_settings_overridden_by_quality_changes)
  459. self._dialog.setNumUserSettings(num_user_settings)
  460. self._dialog.setActiveMode(active_mode)
  461. self._dialog.setMachineName(machine_name)
  462. self._dialog.setMaterialLabels(material_labels)
  463. self._dialog.setMachineType(machine_type)
  464. self._dialog.setExtruders(extruders)
  465. self._dialog.setVariantType(variant_type_name)
  466. self._dialog.setHasObjectsOnPlate(Application.getInstance().platformActivity)
  467. self._dialog.show()
  468. # Block until the dialog is closed.
  469. self._dialog.waitForClose()
  470. if self._dialog.getResult() == {}:
  471. return WorkspaceReader.PreReadResult.cancelled
  472. self._resolve_strategies = self._dialog.getResult()
  473. #
  474. # There can be 3 resolve strategies coming from the dialog:
  475. # - new: create a new container
  476. # - override: override the existing container
  477. # - None: There is no conflict, which means containers with the same IDs may or may not be there already.
  478. # If there is an existing container, there is no conflict between them, and default to "override"
  479. # If there is no existing container, default to "new"
  480. #
  481. # Default values
  482. for key, strategy in self._resolve_strategies.items():
  483. if key not in containers_found_dict or strategy is not None:
  484. continue
  485. self._resolve_strategies[key] = "override" if containers_found_dict[key] else "new"
  486. return WorkspaceReader.PreReadResult.accepted
  487. ## Read the project file
  488. # Add all the definitions / materials / quality changes that do not exist yet. Then it loads
  489. # all the stacks into the container registry. In some cases it will reuse the container for the global stack.
  490. # It handles old style project files containing .stack.cfg as well as new style project files
  491. # containing global.cfg / extruder.cfg
  492. #
  493. # \param file_name
  494. @call_on_qt_thread
  495. def read(self, file_name):
  496. application = CuraApplication.getInstance()
  497. archive = zipfile.ZipFile(file_name, "r")
  498. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  499. # Create a shadow copy of the preferences (we don't want all of the preferences, but we do want to re-use its
  500. # parsing code.
  501. temp_preferences = Preferences()
  502. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  503. temp_preferences.deserialize(serialized)
  504. # Copy a number of settings from the temp preferences to the global
  505. global_preferences = application.getInstance().getPreferences()
  506. visible_settings = temp_preferences.getValue("general/visible_settings")
  507. if visible_settings is None:
  508. Logger.log("w", "Workspace did not contain visible settings. Leaving visibility unchanged")
  509. else:
  510. global_preferences.setValue("general/visible_settings", visible_settings)
  511. global_preferences.setValue("cura/active_setting_visibility_preset", "custom")
  512. categories_expanded = temp_preferences.getValue("cura/categories_expanded")
  513. if categories_expanded is None:
  514. Logger.log("w", "Workspace did not contain expanded categories. Leaving them unchanged")
  515. else:
  516. global_preferences.setValue("cura/categories_expanded", categories_expanded)
  517. application.expandedCategoriesChanged.emit() # Notify the GUI of the change
  518. # If a machine with the same name is of a different type, always create a new one.
  519. if not self._is_same_machine_type or self._resolve_strategies["machine"] != "override":
  520. # We need to create a new machine
  521. machine_name = self._container_registry.uniqueName(self._machine_info.name)
  522. global_stack = CuraStackBuilder.createMachine(machine_name, self._machine_info.definition_id)
  523. if global_stack: #Only switch if creating the machine was successful.
  524. extruder_stack_dict = global_stack.extruders
  525. self._container_registry.addContainer(global_stack)
  526. else:
  527. # Find the machine
  528. global_stack = self._container_registry.findContainerStacks(name = self._machine_info.name, type = "machine")[0]
  529. extruder_stacks = self._container_registry.findContainerStacks(machine = global_stack.getId(),
  530. type = "extruder_train")
  531. extruder_stack_dict = {stack.getMetaDataEntry("position"): stack for stack in extruder_stacks}
  532. # Make sure that those extruders have the global stack as the next stack or later some value evaluation
  533. # will fail.
  534. for stack in extruder_stacks:
  535. stack.setNextStack(global_stack, connect_signals = False)
  536. Logger.log("d", "Workspace loading is checking definitions...")
  537. # Get all the definition files & check if they exist. If not, add them.
  538. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  539. for definition_container_file in definition_container_files:
  540. container_id = self._stripFileToId(definition_container_file)
  541. definitions = self._container_registry.findDefinitionContainersMetadata(id = container_id)
  542. if not definitions:
  543. definition_container = DefinitionContainer(container_id)
  544. try:
  545. definition_container.deserialize(archive.open(definition_container_file).read().decode("utf-8"),
  546. file_name = definition_container_file)
  547. except ContainerFormatError:
  548. # We cannot just skip the definition file because everything else later will just break if the
  549. # machine definition cannot be found.
  550. Logger.logException("e", "Failed to deserialize definition file %s in project file %s",
  551. definition_container_file, file_name)
  552. definition_container = self._container_registry.findDefinitionContainers(id = "fdmprinter")[0] #Fall back to defaults.
  553. self._container_registry.addContainer(definition_container)
  554. Job.yieldThread()
  555. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  556. Logger.log("d", "Workspace loading is checking materials...")
  557. # Get all the material files and check if they exist. If not, add them.
  558. xml_material_profile = self._getXmlProfileClass()
  559. if self._material_container_suffix is None:
  560. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).suffixes[0]
  561. if xml_material_profile:
  562. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  563. for material_container_file in material_container_files:
  564. to_deserialize_material = False
  565. container_id = self._stripFileToId(material_container_file)
  566. need_new_name = False
  567. materials = self._container_registry.findInstanceContainers(id = container_id)
  568. if not materials:
  569. # No material found, deserialize this material later and add it
  570. to_deserialize_material = True
  571. else:
  572. material_container = materials[0]
  573. old_material_root_id = material_container.getMetaDataEntry("base_file")
  574. if old_material_root_id is not None and not self._container_registry.isReadOnly(old_material_root_id): # Only create new materials if they are not read only.
  575. to_deserialize_material = True
  576. if self._resolve_strategies["material"] == "override":
  577. # Remove the old materials and then deserialize the one from the project
  578. root_material_id = material_container.getMetaDataEntry("base_file")
  579. application.getContainerRegistry().removeContainer(root_material_id)
  580. elif self._resolve_strategies["material"] == "new":
  581. # Note that we *must* deserialize it with a new ID, as multiple containers will be
  582. # auto created & added.
  583. container_id = self.getNewId(container_id)
  584. self._old_new_materials[old_material_root_id] = container_id
  585. need_new_name = True
  586. if to_deserialize_material:
  587. material_container = xml_material_profile(container_id)
  588. try:
  589. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"),
  590. file_name = container_id + "." + self._material_container_suffix)
  591. except ContainerFormatError:
  592. Logger.logException("e", "Failed to deserialize material file %s in project file %s",
  593. material_container_file, file_name)
  594. continue
  595. if need_new_name:
  596. new_name = ContainerRegistry.getInstance().uniqueName(material_container.getName())
  597. material_container.setName(new_name)
  598. material_container.setDirty(True)
  599. self._container_registry.addContainer(material_container)
  600. Job.yieldThread()
  601. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  602. # Handle quality changes if any
  603. self._processQualityChanges(global_stack)
  604. # Prepare the machine
  605. self._applyChangesToMachine(global_stack, extruder_stack_dict)
  606. Logger.log("d", "Workspace loading is notifying rest of the code of changes...")
  607. # Actually change the active machine.
  608. #
  609. # This is scheduled for later is because it depends on the Variant/Material/Qualitiy Managers to have the latest
  610. # data, but those managers will only update upon a container/container metadata changed signal. Because this
  611. # function is running on the main thread (Qt thread), although those "changed" signals have been emitted, but
  612. # they won't take effect until this function is done.
  613. # To solve this, we schedule _updateActiveMachine() for later so it will have the latest data.
  614. self._updateActiveMachine(global_stack)
  615. # Load all the nodes / mesh data of the workspace
  616. nodes = self._3mf_mesh_reader.read(file_name)
  617. if nodes is None:
  618. nodes = []
  619. base_file_name = os.path.basename(file_name)
  620. self.setWorkspaceName(base_file_name)
  621. return nodes, self._loadMetadata(file_name)
  622. @staticmethod
  623. def _loadMetadata(file_name: str) -> Dict[str, Dict[str, Any]]:
  624. archive = zipfile.ZipFile(file_name, "r")
  625. metadata_files = [name for name in archive.namelist() if name.endswith("plugin_metadata.json")]
  626. result = dict()
  627. for metadata_file in metadata_files:
  628. try:
  629. plugin_id = metadata_file.split("/")[0]
  630. result[plugin_id] = json.loads(archive.open("%s/plugin_metadata.json" % plugin_id).read().decode("utf-8"))
  631. except Exception:
  632. Logger.logException("w", "Unable to retrieve metadata for %s", metadata_file)
  633. return result
  634. def _processQualityChanges(self, global_stack):
  635. if self._machine_info.quality_changes_info is None:
  636. return
  637. # If we have custom profiles, load them
  638. quality_changes_name = self._machine_info.quality_changes_info.name
  639. if self._machine_info.quality_changes_info is not None:
  640. Logger.log("i", "Loading custom profile [%s] from project file",
  641. self._machine_info.quality_changes_info.name)
  642. # Get the correct extruder definition IDs for quality changes
  643. machine_definition_id_for_quality = ContainerTree.getInstance().machines[global_stack.definition.getId()].quality_definition
  644. machine_definition_for_quality = self._container_registry.findDefinitionContainers(id = machine_definition_id_for_quality)[0]
  645. quality_changes_info = self._machine_info.quality_changes_info
  646. quality_changes_quality_type = quality_changes_info.global_info.parser["metadata"]["quality_type"]
  647. # quality changes container may not be present for every extruder. Prepopulate the dict with default values.
  648. quality_changes_intent_category_per_extruder = {position: "default" for position in self._machine_info.extruder_info_dict}
  649. for position, info in quality_changes_info.extruder_info_dict.items():
  650. quality_changes_intent_category_per_extruder[position] = info.parser["metadata"].get("intent_category", "default")
  651. quality_changes_name = quality_changes_info.name
  652. create_new = self._resolve_strategies.get("quality_changes") != "override"
  653. if create_new:
  654. container_info_dict = {None: self._machine_info.quality_changes_info.global_info}
  655. container_info_dict.update(quality_changes_info.extruder_info_dict)
  656. quality_changes_name = self._container_registry.uniqueName(quality_changes_name)
  657. for position, container_info in container_info_dict.items():
  658. extruder_stack = None
  659. intent_category = None # type: Optional[str]
  660. if position is not None:
  661. extruder_stack = global_stack.extruders[position]
  662. intent_category = quality_changes_intent_category_per_extruder[position]
  663. container = self._createNewQualityChanges(quality_changes_quality_type, intent_category, quality_changes_name, global_stack, extruder_stack)
  664. container_info.container = container
  665. self._container_registry.addContainer(container)
  666. Logger.log("d", "Created new quality changes container [%s]", container.getId())
  667. else:
  668. # Find the existing containers
  669. quality_changes_containers = self._container_registry.findInstanceContainers(name = quality_changes_name,
  670. type = "quality_changes")
  671. for container in quality_changes_containers:
  672. extruder_position = container.getMetaDataEntry("position")
  673. if extruder_position is None:
  674. quality_changes_info.global_info.container = container
  675. else:
  676. if extruder_position not in quality_changes_info.extruder_info_dict:
  677. quality_changes_info.extruder_info_dict[extruder_position] = ContainerInfo(None, None, None)
  678. container_info = quality_changes_info.extruder_info_dict[extruder_position]
  679. container_info.container = container
  680. # If there is no quality changes for any extruder, create one.
  681. if not quality_changes_info.extruder_info_dict:
  682. container_info = ContainerInfo(None, None, None)
  683. quality_changes_info.extruder_info_dict["0"] = container_info
  684. # If the global stack we're "targeting" has never been active, but was updated from Cura 3.4,
  685. # it might not have its extruders set properly.
  686. if not global_stack.extruders:
  687. ExtruderManager.getInstance().fixSingleExtrusionMachineExtruderDefinition(global_stack)
  688. extruder_stack = global_stack.extruders["0"]
  689. intent_category = quality_changes_intent_category_per_extruder["0"]
  690. container = self._createNewQualityChanges(quality_changes_quality_type, intent_category, quality_changes_name, global_stack, extruder_stack)
  691. container_info.container = container
  692. self._container_registry.addContainer(container)
  693. Logger.log("d", "Created new quality changes container [%s]", container.getId())
  694. # Clear all existing containers
  695. quality_changes_info.global_info.container.clear()
  696. for container_info in quality_changes_info.extruder_info_dict.values():
  697. if container_info.container:
  698. container_info.container.clear()
  699. # Loop over everything and override the existing containers
  700. global_info = quality_changes_info.global_info
  701. global_info.container.clear() # Clear all
  702. for key, value in global_info.parser["values"].items():
  703. if not machine_definition_for_quality.getProperty(key, "settable_per_extruder"):
  704. global_info.container.setProperty(key, "value", value)
  705. else:
  706. quality_changes_info.extruder_info_dict["0"].container.setProperty(key, "value", value)
  707. for position, container_info in quality_changes_info.extruder_info_dict.items():
  708. if container_info.parser is None:
  709. continue
  710. if container_info.container is None:
  711. extruder_stack = global_stack.extruders[position]
  712. intent_category = quality_changes_intent_category_per_extruder[position]
  713. container = self._createNewQualityChanges(quality_changes_quality_type, intent_category, quality_changes_name, global_stack, extruder_stack)
  714. container_info.container = container
  715. self._container_registry.addContainer(container)
  716. for key, value in container_info.parser["values"].items():
  717. container_info.container.setProperty(key, "value", value)
  718. self._machine_info.quality_changes_info.name = quality_changes_name
  719. ## Helper class to create a new quality changes profile.
  720. #
  721. # This will then later be filled with the appropriate data.
  722. # \param quality_type The quality type of the new profile.
  723. # \param intent_category The intent category of the new profile.
  724. # \param name The name for the profile. This will later be made unique so
  725. # it doesn't need to be unique yet.
  726. # \param global_stack The global stack showing the configuration that the
  727. # profile should be created for.
  728. # \param extruder_stack The extruder stack showing the configuration that
  729. # the profile should be created for. If this is None, it will be created
  730. # for the global stack.
  731. def _createNewQualityChanges(self, quality_type: str, intent_category: Optional[str], name: str, global_stack: GlobalStack, extruder_stack: Optional[ExtruderStack]) -> InstanceContainer:
  732. container_registry = CuraApplication.getInstance().getContainerRegistry()
  733. base_id = global_stack.definition.getId() if extruder_stack is None else extruder_stack.getId()
  734. new_id = base_id + "_" + name
  735. new_id = new_id.lower().replace(" ", "_")
  736. new_id = container_registry.uniqueName(new_id)
  737. # Create a new quality_changes container for the quality.
  738. quality_changes = InstanceContainer(new_id)
  739. quality_changes.setName(name)
  740. quality_changes.setMetaDataEntry("type", "quality_changes")
  741. quality_changes.setMetaDataEntry("quality_type", quality_type)
  742. if intent_category is not None:
  743. quality_changes.setMetaDataEntry("intent_category", intent_category)
  744. # If we are creating a container for an extruder, ensure we add that to the container.
  745. if extruder_stack is not None:
  746. quality_changes.setMetaDataEntry("position", extruder_stack.getMetaDataEntry("position"))
  747. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  748. machine_definition_id = ContainerTree.getInstance().machines[global_stack.definition.getId()].quality_definition
  749. quality_changes.setDefinition(machine_definition_id)
  750. quality_changes.setMetaDataEntry("setting_version", CuraApplication.getInstance().SettingVersion)
  751. quality_changes.setDirty(True)
  752. return quality_changes
  753. @staticmethod
  754. def _clearStack(stack):
  755. application = CuraApplication.getInstance()
  756. stack.definitionChanges.clear()
  757. stack.variant = application.empty_variant_container
  758. stack.material = application.empty_material_container
  759. stack.quality = application.empty_quality_container
  760. stack.qualityChanges = application.empty_quality_changes_container
  761. stack.userChanges.clear()
  762. def _applyDefinitionChanges(self, global_stack, extruder_stack_dict):
  763. values_to_set_for_extruders = {}
  764. if self._machine_info.definition_changes_info is not None:
  765. parser = self._machine_info.definition_changes_info.parser
  766. for key, value in parser["values"].items():
  767. if global_stack.getProperty(key, "settable_per_extruder"):
  768. values_to_set_for_extruders[key] = value
  769. else:
  770. global_stack.definitionChanges.setProperty(key, "value", value)
  771. for position, extruder_stack in extruder_stack_dict.items():
  772. if position not in self._machine_info.extruder_info_dict:
  773. continue
  774. extruder_info = self._machine_info.extruder_info_dict[position]
  775. if extruder_info.definition_changes_info is None:
  776. continue
  777. parser = extruder_info.definition_changes_info.parser
  778. for key, value in values_to_set_for_extruders.items():
  779. extruder_stack.definitionChanges.setProperty(key, "value", value)
  780. if parser is not None:
  781. for key, value in parser["values"].items():
  782. extruder_stack.definitionChanges.setProperty(key, "value", value)
  783. def _applyUserChanges(self, global_stack, extruder_stack_dict):
  784. values_to_set_for_extruder_0 = {}
  785. if self._machine_info.user_changes_info is not None:
  786. parser = self._machine_info.user_changes_info.parser
  787. for key, value in parser["values"].items():
  788. if global_stack.getProperty(key, "settable_per_extruder"):
  789. values_to_set_for_extruder_0[key] = value
  790. else:
  791. global_stack.userChanges.setProperty(key, "value", value)
  792. for position, extruder_stack in extruder_stack_dict.items():
  793. if position not in self._machine_info.extruder_info_dict:
  794. continue
  795. extruder_info = self._machine_info.extruder_info_dict[position]
  796. if extruder_info.user_changes_info is not None:
  797. parser = self._machine_info.extruder_info_dict[position].user_changes_info.parser
  798. if position == "0":
  799. for key, value in values_to_set_for_extruder_0.items():
  800. extruder_stack.userChanges.setProperty(key, "value", value)
  801. if parser is not None:
  802. for key, value in parser["values"].items():
  803. extruder_stack.userChanges.setProperty(key, "value", value)
  804. def _applyVariants(self, global_stack, extruder_stack_dict):
  805. machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
  806. # Take the global variant from the machine info if available.
  807. if self._machine_info.variant_info is not None:
  808. variant_name = self._machine_info.variant_info.parser["general"]["name"]
  809. if variant_name in machine_node.variants:
  810. global_stack.variant = machine_node.variants[variant_name].container
  811. else:
  812. Logger.log("w", "Could not find global variant '{0}'.".format(variant_name))
  813. for position, extruder_stack in extruder_stack_dict.items():
  814. if position not in self._machine_info.extruder_info_dict:
  815. continue
  816. extruder_info = self._machine_info.extruder_info_dict[position]
  817. if extruder_info.variant_info is None:
  818. # If there is no variant_info, try to use the default variant. Otherwise, any available variant.
  819. node = machine_node.variants.get(machine_node.preferred_variant_name, next(iter(machine_node.variants.values())))
  820. else:
  821. variant_name = extruder_info.variant_info.parser["general"]["name"]
  822. node = ContainerTree.getInstance().machines[global_stack.definition.getId()].variants[variant_name]
  823. extruder_stack.variant = node.container
  824. def _applyMaterials(self, global_stack, extruder_stack_dict):
  825. machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
  826. for position, extruder_stack in extruder_stack_dict.items():
  827. if position not in self._machine_info.extruder_info_dict:
  828. continue
  829. extruder_info = self._machine_info.extruder_info_dict[position]
  830. if extruder_info.root_material_id is None:
  831. continue
  832. root_material_id = extruder_info.root_material_id
  833. root_material_id = self._old_new_materials.get(root_material_id, root_material_id)
  834. material_node = machine_node.variants[extruder_stack.variant.getName()].materials[root_material_id]
  835. extruder_stack.material = material_node.container # type: InstanceContainer
  836. def _applyChangesToMachine(self, global_stack, extruder_stack_dict):
  837. # Clear all first
  838. self._clearStack(global_stack)
  839. for extruder_stack in extruder_stack_dict.values():
  840. self._clearStack(extruder_stack)
  841. self._applyDefinitionChanges(global_stack, extruder_stack_dict)
  842. self._applyUserChanges(global_stack, extruder_stack_dict)
  843. self._applyVariants(global_stack, extruder_stack_dict)
  844. self._applyMaterials(global_stack, extruder_stack_dict)
  845. # prepare the quality to select
  846. self._quality_changes_to_apply = None
  847. self._quality_type_to_apply = None
  848. self._intent_category_to_apply = None
  849. if self._machine_info.quality_changes_info is not None:
  850. self._quality_changes_to_apply = self._machine_info.quality_changes_info.name
  851. else:
  852. self._quality_type_to_apply = self._machine_info.quality_type
  853. self._intent_category_to_apply = self._machine_info.intent_category
  854. # Set enabled/disabled for extruders
  855. for position, extruder_stack in extruder_stack_dict.items():
  856. extruder_info = self._machine_info.extruder_info_dict.get(position)
  857. if not extruder_info:
  858. continue
  859. if "enabled" not in extruder_stack.getMetaData():
  860. extruder_stack.setMetaDataEntry("enabled", "True")
  861. extruder_stack.setMetaDataEntry("enabled", str(extruder_info.enabled))
  862. # Set metadata fields that are missing from the global stack
  863. for key, value in self._machine_info.metadata_dict.items():
  864. global_stack.setMetaDataEntry(key, value)
  865. def _updateActiveMachine(self, global_stack):
  866. # Actually change the active machine.
  867. machine_manager = Application.getInstance().getMachineManager()
  868. container_tree = ContainerTree.getInstance()
  869. machine_manager.setActiveMachine(global_stack.getId())
  870. # Set metadata fields that are missing from the global stack
  871. for key, value in self._machine_info.metadata_dict.items():
  872. if key not in global_stack.getMetaData():
  873. global_stack.setMetaDataEntry(key, value)
  874. if self._quality_changes_to_apply:
  875. quality_changes_group_list = container_tree.getCurrentQualityChangesGroups()
  876. quality_changes_group = next((qcg for qcg in quality_changes_group_list if qcg.name == self._quality_changes_to_apply), None)
  877. if not quality_changes_group:
  878. Logger.log("e", "Could not find quality_changes [%s]", self._quality_changes_to_apply)
  879. return
  880. machine_manager.setQualityChangesGroup(quality_changes_group, no_dialog = True)
  881. else:
  882. self._quality_type_to_apply = self._quality_type_to_apply.lower()
  883. quality_group_dict = container_tree.getCurrentQualityGroups()
  884. if self._quality_type_to_apply in quality_group_dict:
  885. quality_group = quality_group_dict[self._quality_type_to_apply]
  886. else:
  887. Logger.log("i", "Could not find quality type [%s], switch to default", self._quality_type_to_apply)
  888. preferred_quality_type = global_stack.getMetaDataEntry("preferred_quality_type")
  889. quality_group = quality_group_dict.get(preferred_quality_type)
  890. if quality_group is None:
  891. Logger.log("e", "Could not get preferred quality type [%s]", preferred_quality_type)
  892. if quality_group is not None:
  893. machine_manager.setQualityGroup(quality_group, no_dialog = True)
  894. # Also apply intent if available
  895. available_intent_category_list = IntentManager.getInstance().currentAvailableIntentCategories()
  896. if self._intent_category_to_apply is not None and self._intent_category_to_apply in available_intent_category_list:
  897. machine_manager.setIntentByCategory(self._intent_category_to_apply)
  898. # Notify everything/one that is to notify about changes.
  899. global_stack.containersChanged.emit(global_stack.getTop())
  900. @staticmethod
  901. def _stripFileToId(file):
  902. mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
  903. file = mime_type.stripExtension(file)
  904. return file.replace("Cura/", "")
  905. def _getXmlProfileClass(self):
  906. return self._container_registry.getContainerForMimeType(MimeTypeDatabase.getMimeType("application/x-ultimaker-material-profile"))
  907. ## Get the list of ID's of all containers in a container stack by partially parsing it's serialized data.
  908. @staticmethod
  909. def _getContainerIdListFromSerialized(serialized):
  910. parser = ConfigParser(interpolation = None, empty_lines_in_values = False)
  911. parser.read_string(serialized)
  912. container_ids = []
  913. if "containers" in parser:
  914. for index, container_id in parser.items("containers"):
  915. container_ids.append(container_id)
  916. elif parser.has_option("general", "containers"):
  917. container_string = parser["general"].get("containers", "")
  918. container_list = container_string.split(",")
  919. container_ids = [container_id for container_id in container_list if container_id != ""]
  920. # HACK: there used to be 6 containers numbering from 0 to 5 in a stack,
  921. # now we have 7: index 5 becomes "definition_changes"
  922. if len(container_ids) == 6:
  923. # Hack; We used to not save the definition changes. Fix this.
  924. container_ids.insert(5, "empty")
  925. return container_ids
  926. @staticmethod
  927. def _getMachineNameFromSerializedStack(serialized):
  928. parser = ConfigParser(interpolation = None, empty_lines_in_values = False)
  929. parser.read_string(serialized)
  930. return parser["general"].get("name", "")
  931. @staticmethod
  932. def _getMetaDataDictFromSerializedStack(serialized: str) -> Dict[str, str]:
  933. parser = ConfigParser(interpolation = None, empty_lines_in_values = False)
  934. parser.read_string(serialized)
  935. return dict(parser["metadata"])
  936. @staticmethod
  937. def _getMaterialLabelFromSerialized(serialized):
  938. data = ET.fromstring(serialized)
  939. metadata = data.iterfind("./um:metadata/um:name/um:label", {"um": "http://www.ultimaker.com/material"})
  940. for entry in metadata:
  941. return entry.text