ThreeMFWorkspaceReader.py 72 KB

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