ThreeMFWorkspaceReader.py 62 KB

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