ThreeMFWorkspaceReader.py 77 KB

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