ThreeMFWorkspaceReader.py 77 KB

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