ThreeMFWorkspaceReader.py 61 KB

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