ThreeMFWorkspaceReader.py 69 KB

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