ThreeMFWorkspaceReader.py 57 KB

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