ThreeMFWorkspaceReader.py 53 KB

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