ThreeMFWorkspaceReader.py 69 KB

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