ThreeMFWorkspaceReader.py 71 KB

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