ThreeMFWorkspaceReader.py 59 KB

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