ThreeMFWorkspaceReader.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Workspace.WorkspaceReader import WorkspaceReader
  4. from UM.Application import Application
  5. from UM.Logger import Logger
  6. from UM.i18n import i18nCatalog
  7. from UM.Settings.ContainerStack import ContainerStack
  8. from UM.Settings.DefinitionContainer import DefinitionContainer
  9. from UM.Settings.InstanceContainer import InstanceContainer
  10. from UM.Settings.ContainerRegistry import ContainerRegistry
  11. from UM.MimeTypeDatabase import MimeTypeDatabase
  12. from UM.Job import Job
  13. from UM.Preferences import Preferences
  14. from .WorkspaceDialog import WorkspaceDialog
  15. import xml.etree.ElementTree as ET
  16. from cura.Settings.ExtruderManager import ExtruderManager
  17. from cura.Settings.ExtruderStack import ExtruderStack
  18. from cura.Settings.GlobalStack import GlobalStack
  19. from configparser import ConfigParser
  20. import zipfile
  21. import io
  22. import configparser
  23. i18n_catalog = i18nCatalog("cura")
  24. ## Base implementation for reading 3MF workspace files.
  25. class ThreeMFWorkspaceReader(WorkspaceReader):
  26. def __init__(self):
  27. super().__init__()
  28. self._supported_extensions = [".3mf"]
  29. self._dialog = WorkspaceDialog()
  30. self._3mf_mesh_reader = None
  31. self._container_registry = ContainerRegistry.getInstance()
  32. # suffixes registered with the MineTypes don't start with a dot '.'
  33. self._definition_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(DefinitionContainer).preferredSuffix
  34. self._material_container_suffix = None # We have to wait until all other plugins are loaded before we can set it
  35. self._instance_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(InstanceContainer).preferredSuffix
  36. self._container_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ContainerStack).preferredSuffix
  37. self._extruder_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ExtruderStack).preferredSuffix
  38. self._global_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(GlobalStack).preferredSuffix
  39. # Certain instance container types are ignored because we make the assumption that only we make those types
  40. # of containers. They are:
  41. # - quality
  42. # - variant
  43. self._ignored_instance_container_types = {"quality", "variant"}
  44. self._resolve_strategies = {}
  45. self._id_mapping = {}
  46. # In Cura 2.5 and 2.6, the empty profiles used to have those long names
  47. self._old_empty_profile_id_dict = {"empty_%s" % k: "empty" for k in ["material", "variant"]}
  48. ## Get a unique name based on the old_id. This is different from directly calling the registry in that it caches results.
  49. # This has nothing to do with speed, but with getting consistent new naming for instances & objects.
  50. def getNewId(self, old_id):
  51. if old_id not in self._id_mapping:
  52. self._id_mapping[old_id] = self._container_registry.uniqueName(old_id)
  53. return self._id_mapping[old_id]
  54. ## Separates the given file list into a list of GlobalStack files and a list of ExtruderStack files.
  55. #
  56. # In old versions, extruder stack files have the same suffix as container stack files ".stack.cfg".
  57. #
  58. def _determineGlobalAndExtruderStackFiles(self, project_file_name, file_list):
  59. archive = zipfile.ZipFile(project_file_name, "r")
  60. global_stack_file_list = [name for name in file_list if name.endswith(self._global_stack_suffix)]
  61. extruder_stack_file_list = [name for name in file_list if name.endswith(self._extruder_stack_suffix)]
  62. # separate container stack files and extruder stack files
  63. files_to_determine = [name for name in file_list if name.endswith(self._container_stack_suffix)]
  64. for file_name in files_to_determine:
  65. # FIXME: HACK!
  66. # We need to know the type of the stack file, but we can only know it if we deserialize it.
  67. # The default ContainerStack.deserialize() will connect signals, which is not desired in this case.
  68. # Since we know that the stack files are INI files, so we directly use the ConfigParser to parse them.
  69. serialized = archive.open(file_name).read().decode("utf-8")
  70. stack_config = ConfigParser()
  71. stack_config.read_string(serialized)
  72. # sanity check
  73. if not stack_config.has_option("metadata", "type"):
  74. Logger.log("e", "%s in %s doesn't seem to be valid stack file", file_name, project_file_name)
  75. continue
  76. stack_type = stack_config.get("metadata", "type")
  77. if stack_type == "extruder_train":
  78. extruder_stack_file_list.append(file_name)
  79. elif stack_type == "machine":
  80. global_stack_file_list.append(file_name)
  81. else:
  82. Logger.log("w", "Unknown container stack type '%s' from %s in %s",
  83. stack_type, file_name, project_file_name)
  84. if len(global_stack_file_list) != 1:
  85. raise RuntimeError("More than one global stack file found: [%s]" % str(global_stack_file_list))
  86. return global_stack_file_list[0], extruder_stack_file_list
  87. ## read some info so we can make decisions
  88. # \param file_name
  89. # \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.
  90. def preRead(self, file_name, show_dialog=True, *args, **kwargs):
  91. self._3mf_mesh_reader = Application.getInstance().getMeshFileHandler().getReaderForFile(file_name)
  92. if self._3mf_mesh_reader and self._3mf_mesh_reader.preRead(file_name) == WorkspaceReader.PreReadResult.accepted:
  93. pass
  94. else:
  95. Logger.log("w", "Could not find reader that was able to read the scene data for 3MF workspace")
  96. return WorkspaceReader.PreReadResult.failed
  97. machine_name = ""
  98. machine_type = ""
  99. variant_type_name = i18n_catalog.i18nc("@label", "Nozzle")
  100. # Check if there are any conflicts, so we can ask the user.
  101. archive = zipfile.ZipFile(file_name, "r")
  102. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  103. # A few lists of containers in this project files.
  104. # When loading the global stack file, it may be associated with those containers, which may or may not be
  105. # in Cura already, so we need to provide them as alternative search lists.
  106. definition_container_list = []
  107. instance_container_list = []
  108. material_container_list = []
  109. resolve_strategy_keys = ["machine", "material", "quality_changes"]
  110. self._resolve_strategies = {k: None for k in resolve_strategy_keys}
  111. containers_found_dict = {k: False for k in resolve_strategy_keys}
  112. #
  113. # Read definition containers
  114. #
  115. machine_definition_container_count = 0
  116. extruder_definition_container_count = 0
  117. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  118. for each_definition_container_file in definition_container_files:
  119. container_id = self._stripFileToId(each_definition_container_file)
  120. definitions = self._container_registry.findDefinitionContainers(id=container_id)
  121. if not definitions:
  122. definition_container = DefinitionContainer(container_id)
  123. definition_container.deserialize(archive.open(each_definition_container_file).read().decode("utf-8"))
  124. else:
  125. definition_container = definitions[0]
  126. definition_container_list.append(definition_container)
  127. definition_container_type = definition_container.getMetaDataEntry("type")
  128. if definition_container_type == "machine":
  129. machine_type = definition_container.getName()
  130. variant_type_name = definition_container.getMetaDataEntry("variants_name", variant_type_name)
  131. machine_definition_container_count += 1
  132. elif definition_container_type == "extruder":
  133. extruder_definition_container_count += 1
  134. else:
  135. Logger.log("w", "Unknown definition container type %s for %s",
  136. definition_container_type, each_definition_container_file)
  137. Job.yieldThread()
  138. # sanity check
  139. if machine_definition_container_count != 1:
  140. msg = "Expecting one machine definition container but got %s" % machine_definition_container_count
  141. Logger.log("e", msg)
  142. raise RuntimeError(msg)
  143. material_labels = []
  144. material_conflict = False
  145. xml_material_profile = self._getXmlProfileClass()
  146. if self._material_container_suffix is None:
  147. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).preferredSuffix
  148. if xml_material_profile:
  149. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  150. for material_container_file in material_container_files:
  151. container_id = self._stripFileToId(material_container_file)
  152. materials = self._container_registry.findInstanceContainers(id=container_id)
  153. material_labels.append(self._getMaterialLabelFromSerialized(archive.open(material_container_file).read().decode("utf-8")))
  154. if materials:
  155. containers_found_dict["material"] = True
  156. if not materials[0].isReadOnly(): # Only non readonly materials can be in conflict
  157. material_conflict = True
  158. Job.yieldThread()
  159. # Check if any quality_changes instance container is in conflict.
  160. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  161. quality_name = ""
  162. quality_type = ""
  163. num_settings_overriden_by_quality_changes = 0 # How many settings are changed by the quality changes
  164. num_settings_overriden_by_definition_changes = 0 # How many settings are changed by the definition changes
  165. num_user_settings = 0
  166. quality_changes_conflict = False
  167. definition_changes_conflict = False
  168. for each_instance_container_file in instance_container_files:
  169. container_id = self._stripFileToId(each_instance_container_file)
  170. instance_container = InstanceContainer(container_id)
  171. # Deserialize InstanceContainer by converting read data from bytes to string
  172. instance_container.deserialize(archive.open(each_instance_container_file).read().decode("utf-8"))
  173. instance_container_list.append(instance_container)
  174. container_type = instance_container.getMetaDataEntry("type")
  175. if container_type == "quality_changes":
  176. quality_name = instance_container.getName()
  177. num_settings_overriden_by_quality_changes += len(instance_container._instances)
  178. # Check if quality changes already exists.
  179. quality_changes = self._container_registry.findInstanceContainers(id = container_id)
  180. if quality_changes:
  181. containers_found_dict["quality_changes"] = True
  182. # Check if there really is a conflict by comparing the values
  183. if quality_changes[0] != instance_container:
  184. quality_changes_conflict = True
  185. elif container_type == "definition_changes":
  186. definition_name = instance_container.getName()
  187. num_settings_overriden_by_definition_changes += len(instance_container._instances)
  188. definition_changes = self._container_registry.findDefinitionContainers(id = container_id)
  189. if definition_changes:
  190. if definition_changes[0] != instance_container:
  191. definition_changes_conflict = True
  192. else:
  193. definition_changes_conflict = True
  194. elif container_type == "user":
  195. num_user_settings += len(instance_container._instances)
  196. elif container_type in self._ignored_instance_container_types:
  197. # Ignore certain instance container types
  198. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  199. continue
  200. Job.yieldThread()
  201. # Load ContainerStack files and ExtruderStack files
  202. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(
  203. file_name, cura_file_names)
  204. machine_conflict = False
  205. # Because there can be cases as follows:
  206. # - the global stack exists but some/all of the extruder stacks DON'T exist
  207. # - the global stack DOESN'T exist but some/all of the extruder stacks exist
  208. # To simplify this, only check if the global stack exists or not
  209. container_id = self._stripFileToId(global_stack_file)
  210. serialized = archive.open(global_stack_file).read().decode("utf-8")
  211. machine_name = self._getMachineNameFromSerializedStack(serialized)
  212. stacks = self._container_registry.findContainerStacks(id = container_id)
  213. if stacks:
  214. global_stack = stacks[0]
  215. containers_found_dict["machine"] = True
  216. # Check if there are any changes at all in any of the container stacks.
  217. id_list = self._getContainerIdListFromSerialized(serialized)
  218. for index, container_id in enumerate(id_list):
  219. # take into account the old empty container IDs
  220. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  221. if global_stack.getContainer(index).getId() != container_id:
  222. machine_conflict = True
  223. break
  224. Job.yieldThread()
  225. # if the global stack is found, we check if there are conflicts in the extruder stacks
  226. if containers_found_dict["machine"] and not machine_conflict:
  227. for extruder_stack_file in extruder_stack_files:
  228. container_id = self._stripFileToId(extruder_stack_file)
  229. serialized = archive.open(extruder_stack_file).read().decode("utf-8")
  230. parser = configparser.ConfigParser()
  231. parser.read_string(serialized)
  232. # The check should be done for the extruder stack that's associated with the existing global stack,
  233. # and those extruder stacks may have different IDs.
  234. # So we check according to the positions
  235. position = str(parser["metadata"]["position"])
  236. if position not in global_stack.extruders:
  237. # The extruder position defined in the project doesn't exist in this global stack.
  238. # We can say that it is a machine conflict, but it is very hard to override the machine in this
  239. # case because we need to override the existing extruders and add the non-existing extruders.
  240. #
  241. # HACK:
  242. # To make this simple, we simply say that there is no machine conflict and create a new machine
  243. # by default.
  244. machine_conflict = False
  245. break
  246. existing_extruder_stack = global_stack.extruders[position]
  247. # check if there are any changes at all in any of the container stacks.
  248. id_list = self._getContainerIdListFromSerialized(serialized)
  249. for index, container_id in enumerate(id_list):
  250. # take into account the old empty container IDs
  251. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  252. if existing_extruder_stack.getContainer(index).getId() != container_id:
  253. machine_conflict = True
  254. break
  255. num_visible_settings = 0
  256. try:
  257. temp_preferences = Preferences()
  258. temp_preferences.readFromFile(io.TextIOWrapper(archive.open("Cura/preferences.cfg"))) # We need to wrap it, else the archive parser breaks.
  259. visible_settings_string = temp_preferences.getValue("general/visible_settings")
  260. if visible_settings_string is not None:
  261. num_visible_settings = len(visible_settings_string.split(";"))
  262. active_mode = temp_preferences.getValue("cura/active_mode")
  263. if not active_mode:
  264. active_mode = Preferences.getInstance().getValue("cura/active_mode")
  265. except KeyError:
  266. # If there is no preferences file, it's not a workspace, so notify user of failure.
  267. Logger.log("w", "File %s is not a valid workspace.", file_name)
  268. return WorkspaceReader.PreReadResult.failed
  269. # In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  270. if not show_dialog:
  271. return WorkspaceReader.PreReadResult.accepted
  272. # prepare data for the dialog
  273. num_extruders = extruder_definition_container_count
  274. if num_extruders == 0:
  275. num_extruders = 1 # No extruder stacks found, which means there is one extruder
  276. extruders = num_extruders * [""]
  277. # Show the dialog, informing the user what is about to happen.
  278. self._dialog.setMachineConflict(machine_conflict)
  279. self._dialog.setQualityChangesConflict(quality_changes_conflict)
  280. self._dialog.setDefinitionChangesConflict(definition_changes_conflict)
  281. self._dialog.setMaterialConflict(material_conflict)
  282. self._dialog.setNumVisibleSettings(num_visible_settings)
  283. self._dialog.setQualityName(quality_name)
  284. self._dialog.setQualityType(quality_type)
  285. self._dialog.setNumSettingsOverridenByQualityChanges(num_settings_overriden_by_quality_changes)
  286. self._dialog.setNumUserSettings(num_user_settings)
  287. self._dialog.setActiveMode(active_mode)
  288. self._dialog.setMachineName(machine_name)
  289. self._dialog.setMaterialLabels(material_labels)
  290. self._dialog.setMachineType(machine_type)
  291. self._dialog.setExtruders(extruders)
  292. self._dialog.setVariantType(variant_type_name)
  293. self._dialog.setHasObjectsOnPlate(Application.getInstance().platformActivity)
  294. self._dialog.show()
  295. # Block until the dialog is closed.
  296. self._dialog.waitForClose()
  297. if self._dialog.getResult() == {}:
  298. return WorkspaceReader.PreReadResult.cancelled
  299. self._resolve_strategies = self._dialog.getResult()
  300. #
  301. # There can be 3 resolve strategies coming from the dialog:
  302. # - new: create a new container
  303. # - override: override the existing container
  304. # - None: There is no conflict, which means containers with the same IDs may or may not be there already.
  305. # If there is an existing container, there is no conflict between the them, and default to "override"
  306. # If there is no existing container, default to "new"
  307. #
  308. # Default values
  309. for key, strategy in self._resolve_strategies.items():
  310. if key not in containers_found_dict or strategy is not None:
  311. continue
  312. self._resolve_strategies[key] = "override" if containers_found_dict[key] else "new"
  313. return WorkspaceReader.PreReadResult.accepted
  314. ## Overrides an ExtruderStack in the given GlobalStack and returns the new ExtruderStack.
  315. def _overrideExtruderStack(self, global_stack, extruder_file_content):
  316. # get extruder position first
  317. extruder_config = configparser.ConfigParser()
  318. extruder_config.read_string(extruder_file_content)
  319. if not extruder_config.has_option("metadata", "position"):
  320. msg = "Could not find 'metadata/position' in extruder stack file"
  321. Logger.log("e", "Could not find 'metadata/position' in extruder stack file")
  322. raise RuntimeError(msg)
  323. extruder_position = extruder_config.get("metadata", "position")
  324. extruder_stack = global_stack.extruders[extruder_position]
  325. # override the given extruder stack
  326. extruder_stack.deserialize(extruder_file_content)
  327. # return the new ExtruderStack
  328. return extruder_stack
  329. ## Read the project file
  330. # Add all the definitions / materials / quality changes that do not exist yet. Then it loads
  331. # all the stacks into the container registry. In some cases it will reuse the container for the global stack.
  332. # It handles old style project files containing .stack.cfg as well as new style project files
  333. # containing global.cfg / extruder.cfg
  334. #
  335. # \param file_name
  336. def read(self, file_name):
  337. archive = zipfile.ZipFile(file_name, "r")
  338. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  339. # Create a shadow copy of the preferences (we don't want all of the preferences, but we do want to re-use its
  340. # parsing code.
  341. temp_preferences = Preferences()
  342. temp_preferences.readFromFile(io.TextIOWrapper(archive.open("Cura/preferences.cfg"))) # We need to wrap it, else the archive parser breaks.
  343. # Copy a number of settings from the temp preferences to the global
  344. global_preferences = Preferences.getInstance()
  345. visible_settings = temp_preferences.getValue("general/visible_settings")
  346. if visible_settings is None:
  347. Logger.log("w", "Workspace did not contain visible settings. Leaving visibility unchanged")
  348. else:
  349. global_preferences.setValue("general/visible_settings", visible_settings)
  350. categories_expanded = temp_preferences.getValue("cura/categories_expanded")
  351. if categories_expanded is None:
  352. Logger.log("w", "Workspace did not contain expanded categories. Leaving them unchanged")
  353. else:
  354. global_preferences.setValue("cura/categories_expanded", categories_expanded)
  355. Application.getInstance().expandedCategoriesChanged.emit() # Notify the GUI of the change
  356. self._id_mapping = {}
  357. # We don't add containers right away, but wait right until right before the stack serialization.
  358. # We do this so that if something goes wrong, it's easier to clean up.
  359. containers_to_add = []
  360. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(file_name, cura_file_names)
  361. global_stack = None
  362. extruder_stacks = []
  363. extruder_stacks_added = []
  364. container_stacks_added = []
  365. containers_added = []
  366. global_stack_id_original = self._stripFileToId(global_stack_file)
  367. global_stack_id_new = global_stack_id_original
  368. global_stack_need_rename = False
  369. extruder_stack_id_map = {} # new and old ExtruderStack IDs map
  370. if self._resolve_strategies["machine"] == "new":
  371. # We need a new id if the id already exists
  372. if self._container_registry.findContainerStacks(id = global_stack_id_original):
  373. global_stack_id_new = self.getNewId(global_stack_id_original)
  374. global_stack_need_rename = True
  375. for each_extruder_stack_file in extruder_stack_files:
  376. old_container_id = self._stripFileToId(each_extruder_stack_file)
  377. new_container_id = old_container_id
  378. if self._container_registry.findContainerStacks(id = old_container_id):
  379. # get a new name for this extruder
  380. new_container_id = self.getNewId(old_container_id)
  381. extruder_stack_id_map[old_container_id] = new_container_id
  382. # TODO: For the moment we use pretty naive existence checking. If the ID is the same, we assume in quite a few
  383. # TODO: cases that the container loaded is the same (most notable in materials & definitions).
  384. # TODO: It might be possible that we need to add smarter checking in the future.
  385. Logger.log("d", "Workspace loading is checking definitions...")
  386. # Get all the definition files & check if they exist. If not, add them.
  387. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  388. for definition_container_file in definition_container_files:
  389. container_id = self._stripFileToId(definition_container_file)
  390. definitions = self._container_registry.findDefinitionContainers(id = container_id)
  391. if not definitions:
  392. definition_container = DefinitionContainer(container_id)
  393. definition_container.deserialize(archive.open(definition_container_file).read().decode("utf-8"))
  394. self._container_registry.addContainer(definition_container)
  395. Job.yieldThread()
  396. Logger.log("d", "Workspace loading is checking materials...")
  397. material_containers = []
  398. # Get all the material files and check if they exist. If not, add them.
  399. xml_material_profile = self._getXmlProfileClass()
  400. if self._material_container_suffix is None:
  401. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).suffixes[0]
  402. if xml_material_profile:
  403. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  404. for material_container_file in material_container_files:
  405. container_id = self._stripFileToId(material_container_file)
  406. materials = self._container_registry.findInstanceContainers(id = container_id)
  407. if not materials:
  408. material_container = xml_material_profile(container_id)
  409. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"))
  410. containers_to_add.append(material_container)
  411. else:
  412. material_container = materials[0]
  413. if not material_container.isReadOnly(): # Only create new materials if they are not read only.
  414. if self._resolve_strategies["material"] == "override":
  415. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"))
  416. elif self._resolve_strategies["material"] == "new":
  417. # Note that we *must* deserialize it with a new ID, as multiple containers will be
  418. # auto created & added.
  419. material_container = xml_material_profile(self.getNewId(container_id))
  420. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"))
  421. containers_to_add.append(material_container)
  422. material_containers.append(material_container)
  423. Job.yieldThread()
  424. Logger.log("d", "Workspace loading is checking instance containers...")
  425. # Get quality_changes and user profiles saved in the workspace
  426. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  427. user_instance_containers = []
  428. quality_and_definition_changes_instance_containers = []
  429. for instance_container_file in instance_container_files:
  430. container_id = self._stripFileToId(instance_container_file)
  431. serialized = archive.open(instance_container_file).read().decode("utf-8")
  432. # HACK! we ignore "quality" and "variant" instance containers!
  433. parser = configparser.ConfigParser()
  434. parser.read_string(serialized)
  435. if not parser.has_option("metadata", "type"):
  436. Logger.log("w", "Cannot find metadata/type in %s, ignoring it", instance_container_file)
  437. continue
  438. if parser.get("metadata", "type") in self._ignored_instance_container_types:
  439. continue
  440. instance_container = InstanceContainer(container_id)
  441. # Deserialize InstanceContainer by converting read data from bytes to string
  442. instance_container.deserialize(serialized)
  443. container_type = instance_container.getMetaDataEntry("type")
  444. Job.yieldThread()
  445. #
  446. # IMPORTANT:
  447. # If an instance container (or maybe other type of container) exists, and user chooses "Create New",
  448. # we need to rename this container and all references to it, and changing those references are VERY
  449. # HARD.
  450. #
  451. if container_type in self._ignored_instance_container_types:
  452. # Ignore certain instance container types
  453. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  454. continue
  455. elif container_type == "user":
  456. # Check if quality changes already exists.
  457. user_containers = self._container_registry.findInstanceContainers(id = container_id)
  458. if not user_containers:
  459. containers_to_add.append(instance_container)
  460. else:
  461. if self._resolve_strategies["machine"] == "override" or self._resolve_strategies["machine"] is None:
  462. instance_container = user_containers[0]
  463. instance_container.deserialize(archive.open(instance_container_file).read().decode("utf-8"))
  464. instance_container.setDirty(True)
  465. elif self._resolve_strategies["machine"] == "new":
  466. # The machine is going to get a spiffy new name, so ensure that the id's of user settings match.
  467. old_extruder_id = instance_container.getMetaDataEntry("extruder", None)
  468. if old_extruder_id:
  469. new_extruder_id = extruder_stack_id_map[old_extruder_id]
  470. new_id = new_extruder_id + "_current_settings"
  471. instance_container._id = new_id
  472. instance_container.setName(new_id)
  473. instance_container.setMetaDataEntry("extruder", new_extruder_id)
  474. containers_to_add.append(instance_container)
  475. machine_id = instance_container.getMetaDataEntry("machine", None)
  476. if machine_id:
  477. new_machine_id = self.getNewId(machine_id)
  478. new_id = new_machine_id + "_current_settings"
  479. instance_container._id = new_id
  480. instance_container.setName(new_id)
  481. instance_container.setMetaDataEntry("machine", new_machine_id)
  482. containers_to_add.append(instance_container)
  483. user_instance_containers.append(instance_container)
  484. elif container_type in ("quality_changes", "definition_changes"):
  485. # Check if quality changes already exists.
  486. changes_containers = self._container_registry.findInstanceContainers(id = container_id)
  487. if not changes_containers:
  488. # no existing containers with the same ID, so we can safely add the new one
  489. containers_to_add.append(instance_container)
  490. else:
  491. # we have found existing container with the same ID, so we need to resolve according to the
  492. # selected strategy.
  493. if self._resolve_strategies[container_type] == "override":
  494. instance_container = changes_containers[0]
  495. instance_container.deserialize(archive.open(instance_container_file).read().decode("utf-8"))
  496. instance_container.setDirty(True)
  497. elif self._resolve_strategies[container_type] == "new":
  498. # TODO: how should we handle the case "new" for quality_changes and definition_changes?
  499. instance_container.setName(self._container_registry.uniqueName(instance_container.getName()))
  500. new_changes_container_id = self.getNewId(instance_container.getId())
  501. instance_container._id = new_changes_container_id
  502. # TODO: we don't know the following is correct or not, need to verify
  503. # AND REFACTOR!!!
  504. if self._resolve_strategies["machine"] == "new":
  505. # The machine is going to get a spiffy new name, so ensure that the id's of user settings match.
  506. old_extruder_id = instance_container.getMetaDataEntry("extruder", None)
  507. if old_extruder_id:
  508. new_extruder_id = extruder_stack_id_map[old_extruder_id]
  509. instance_container.setMetaDataEntry("extruder", new_extruder_id)
  510. machine_id = instance_container.getMetaDataEntry("machine", None)
  511. if machine_id:
  512. new_machine_id = self.getNewId(machine_id)
  513. instance_container.setMetaDataEntry("machine", new_machine_id)
  514. containers_to_add.append(instance_container)
  515. elif self._resolve_strategies[container_type] is None:
  516. # The ID already exists, but nothing in the values changed, so do nothing.
  517. pass
  518. quality_and_definition_changes_instance_containers.append(instance_container)
  519. else:
  520. existing_container = self._container_registry.findInstanceContainers(id = container_id)
  521. if not existing_container:
  522. containers_to_add.append(instance_container)
  523. if global_stack_need_rename:
  524. if instance_container.getMetaDataEntry("machine"):
  525. instance_container.setMetaDataEntry("machine", global_stack_id_new)
  526. # Add all the containers right before we try to add / serialize the stack
  527. for container in containers_to_add:
  528. self._container_registry.addContainer(container)
  529. container.setDirty(True)
  530. containers_added.append(container)
  531. # Get the stack(s) saved in the workspace.
  532. Logger.log("d", "Workspace loading is checking stacks containers...")
  533. # --
  534. # load global stack file
  535. try:
  536. if self._resolve_strategies["machine"] == "override":
  537. container_stacks = self._container_registry.findContainerStacks(id = global_stack_id_original)
  538. stack = container_stacks[0]
  539. # HACK
  540. # There is a machine, check if it has authentication data. If so, keep that data.
  541. network_authentication_id = container_stacks[0].getMetaDataEntry("network_authentication_id")
  542. network_authentication_key = container_stacks[0].getMetaDataEntry("network_authentication_key")
  543. container_stacks[0].deserialize(archive.open(global_stack_file).read().decode("utf-8"))
  544. if network_authentication_id:
  545. container_stacks[0].addMetaDataEntry("network_authentication_id", network_authentication_id)
  546. if network_authentication_key:
  547. container_stacks[0].addMetaDataEntry("network_authentication_key", network_authentication_key)
  548. elif self._resolve_strategies["machine"] == "new":
  549. # create a new global stack
  550. stack = GlobalStack(global_stack_id_new)
  551. # Deserialize stack by converting read data from bytes to string
  552. stack.deserialize(archive.open(global_stack_file).read().decode("utf-8"))
  553. # Ensure a unique ID and name
  554. stack._id = global_stack_id_new
  555. # Extruder stacks are "bound" to a machine. If we add the machine as a new one, the id of the
  556. # bound machine also needs to change.
  557. if stack.getMetaDataEntry("machine", None):
  558. stack.setMetaDataEntry("machine", global_stack_id_new)
  559. # Only machines need a new name, stacks may be non-unique
  560. stack.setName(global_stack_id_new)
  561. container_stacks_added.append(stack)
  562. self._container_registry.addContainer(stack)
  563. containers_added.append(stack)
  564. else:
  565. Logger.log("e", "Resolve strategy of %s for machine is not supported",
  566. self._resolve_strategies["machine"])
  567. global_stack = stack
  568. Job.yieldThread()
  569. except:
  570. Logger.logException("w", "We failed to serialize the stack. Trying to clean up.")
  571. # Something went really wrong. Try to remove any data that we added.
  572. for container in containers_added:
  573. self._container_registry.removeContainer(container.getId())
  574. return
  575. # --
  576. # load extruder stack files
  577. try:
  578. for extruder_stack_file in extruder_stack_files:
  579. container_id = self._stripFileToId(extruder_stack_file)
  580. extruder_file_content = archive.open(extruder_stack_file, "r").read().decode("utf-8")
  581. if self._resolve_strategies["machine"] == "override":
  582. # deserialize new extruder stack over the current ones
  583. stack = self._overrideExtruderStack(global_stack, extruder_file_content)
  584. elif self._resolve_strategies["machine"] == "new":
  585. new_id = extruder_stack_id_map[container_id]
  586. stack = ExtruderStack(new_id)
  587. # HACK: the global stack can have a new name, so we need to make sure that this extruder stack
  588. # references to the new name instead of the old one. Normally, this can be done after
  589. # deserialize() by setting the metadata, but in the case of ExtruderStack, deserialize()
  590. # also does addExtruder() to its machine stack, so we have to make sure that it's pointing
  591. # to the right machine BEFORE deserialization.
  592. extruder_config = configparser.ConfigParser()
  593. extruder_config.read_string(extruder_file_content)
  594. extruder_config.set("metadata", "machine", global_stack_id_new)
  595. tmp_string_io = io.StringIO()
  596. extruder_config.write(tmp_string_io)
  597. extruder_file_content = tmp_string_io.getvalue()
  598. stack.deserialize(extruder_file_content)
  599. # Ensure a unique ID and name
  600. stack._id = new_id
  601. self._container_registry.addContainer(stack)
  602. extruder_stacks_added.append(stack)
  603. containers_added.append(stack)
  604. else:
  605. Logger.log("w", "Unknown resolve strategy: %s", self._resolve_strategies["machine"])
  606. extruder_stacks.append(stack)
  607. except:
  608. Logger.logException("w", "We failed to serialize the stack. Trying to clean up.")
  609. # Something went really wrong. Try to remove any data that we added.
  610. for container in containers_added:
  611. self._container_registry.removeContainer(container.getId())
  612. return
  613. #
  614. # Replacing the old containers if resolve is "new".
  615. # When resolve is "new", some containers will get renamed, so all the other containers that reference to those
  616. # MUST get updated too.
  617. #
  618. if self._resolve_strategies["machine"] == "new":
  619. # A new machine was made, but it was serialized with the wrong user container. Fix that now.
  620. for container in user_instance_containers:
  621. # replacing the container ID for user instance containers for the extruders
  622. extruder_id = container.getMetaDataEntry("extruder", None)
  623. if extruder_id:
  624. for extruder in extruder_stacks:
  625. if extruder.getId() == extruder_id:
  626. extruder.userChanges = container
  627. continue
  628. # replacing the container ID for user instance containers for the machine
  629. machine_id = container.getMetaDataEntry("machine", None)
  630. if machine_id:
  631. if global_stack.getId() == machine_id:
  632. global_stack.userChanges = container
  633. continue
  634. for changes_container_type in ("quality_changes", "definition_changes"):
  635. if self._resolve_strategies[changes_container_type] == "new":
  636. # Quality changes needs to get a new ID, added to registry and to the right stacks
  637. for each_changes_container in quality_and_definition_changes_instance_containers:
  638. # NOTE: The renaming and giving new IDs are possibly redundant because they are done in the
  639. # instance container loading part.
  640. new_id = each_changes_container.getId()
  641. # Find the old (current) changes container in the global stack
  642. if changes_container_type == "quality_changes":
  643. old_container = global_stack.qualityChanges
  644. elif changes_container_type == "definition_changes":
  645. old_container = global_stack.definitionChanges
  646. # sanity checks
  647. # NOTE: The following cases SHOULD NOT happen!!!!
  648. if not old_container:
  649. Logger.log("e", "We try to get [%s] from the global stack [%s] but we got None instead!",
  650. changes_container_type, global_stack.getId())
  651. # Replace the quality/definition changes container if it's in the GlobalStack
  652. # NOTE: we can get an empty container here, but the IDs will not match,
  653. # so this comparison is fine.
  654. if self._id_mapping.get(old_container.getId()) == new_id:
  655. if changes_container_type == "quality_changes":
  656. global_stack.qualityChanges = each_changes_container
  657. elif changes_container_type == "definition_changes":
  658. global_stack.definitionChanges = each_changes_container
  659. continue
  660. # Replace the quality/definition changes container if it's in one of the ExtruderStacks
  661. for each_extruder_stack in extruder_stacks:
  662. changes_container = None
  663. if changes_container_type == "quality_changes":
  664. changes_container = each_extruder_stack.qualityChanges
  665. elif changes_container_type == "definition_changes":
  666. changes_container = each_extruder_stack.definitionChanges
  667. # sanity checks
  668. # NOTE: The following cases SHOULD NOT happen!!!!
  669. if not changes_container:
  670. Logger.log("e", "We try to get [%s] from the extruder stack [%s] but we got None instead!",
  671. changes_container_type, each_extruder_stack.getId())
  672. # NOTE: we can get an empty container here, but the IDs will not match,
  673. # so this comparison is fine.
  674. if self._id_mapping.get(changes_container.getId()) == new_id:
  675. if changes_container_type == "quality_changes":
  676. each_extruder_stack.qualityChanges = each_changes_container
  677. elif changes_container_type == "definition_changes":
  678. each_extruder_stack.definitionChanges = each_changes_container
  679. if self._resolve_strategies["material"] == "new":
  680. for each_material in material_containers:
  681. old_material = global_stack.material
  682. # check if the old material container has been renamed to this material container ID
  683. # if the container hasn't been renamed, we do nothing.
  684. new_id = self._id_mapping.get(old_material.getId())
  685. if new_id is None or new_id != each_material.getId():
  686. continue
  687. if old_material.getId() in self._id_mapping:
  688. global_stack.material = each_material
  689. for each_extruder_stack in extruder_stacks:
  690. old_material = each_extruder_stack.material
  691. # check if the old material container has been renamed to this material container ID
  692. # if the container hasn't been renamed, we do nothing.
  693. new_id = self._id_mapping.get(old_material.getId())
  694. if new_id is None or new_id != each_material.getId():
  695. continue
  696. if old_material.getId() in self._id_mapping:
  697. each_extruder_stack.material = each_material
  698. if extruder_stacks:
  699. for stack in extruder_stacks:
  700. ExtruderManager.getInstance().registerExtruder(stack, global_stack.getId())
  701. else:
  702. # Machine has no extruders, but it needs to be registered with the extruder manager.
  703. ExtruderManager.getInstance().registerExtruder(None, global_stack.getId())
  704. Logger.log("d", "Workspace loading is notifying rest of the code of changes...")
  705. if self._resolve_strategies["machine"] == "new":
  706. for stack in extruder_stacks:
  707. stack.setNextStack(global_stack)
  708. stack.containersChanged.emit(stack.getTop())
  709. # Actually change the active machine.
  710. Application.getInstance().setGlobalContainerStack(global_stack)
  711. # Notify everything/one that is to notify about changes.
  712. global_stack.containersChanged.emit(global_stack.getTop())
  713. # Load all the nodes / meshdata of the workspace
  714. nodes = self._3mf_mesh_reader.read(file_name)
  715. if nodes is None:
  716. nodes = []
  717. return nodes
  718. def _stripFileToId(self, file):
  719. mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
  720. file = mime_type.stripExtension(file)
  721. return file.replace("Cura/", "")
  722. def _getXmlProfileClass(self):
  723. return self._container_registry.getContainerForMimeType(MimeTypeDatabase.getMimeType("application/x-ultimaker-material-profile"))
  724. ## Get the list of ID's of all containers in a container stack by partially parsing it's serialized data.
  725. def _getContainerIdListFromSerialized(self, serialized):
  726. parser = configparser.ConfigParser(interpolation=None, empty_lines_in_values=False)
  727. parser.read_string(serialized)
  728. container_ids = []
  729. if "containers" in parser:
  730. for index, container_id in parser.items("containers"):
  731. container_ids.append(container_id)
  732. elif parser.has_option("general", "containers"):
  733. container_string = parser["general"].get("containers", "")
  734. container_list = container_string.split(",")
  735. container_ids = [container_id for container_id in container_list if container_id != ""]
  736. # HACK: there used to be 6 containers numbering from 0 to 5 in a stack,
  737. # now we have 7: index 5 becomes "definition_changes"
  738. if len(container_ids) == 6:
  739. # Hack; We used to not save the definition changes. Fix this.
  740. container_ids.insert(5, "empty")
  741. return container_ids
  742. def _getMachineNameFromSerializedStack(self, serialized):
  743. parser = configparser.ConfigParser(interpolation=None, empty_lines_in_values=False)
  744. parser.read_string(serialized)
  745. return parser["general"].get("name", "")
  746. def _getMaterialLabelFromSerialized(self, serialized):
  747. data = ET.fromstring(serialized)
  748. metadata = data.iterfind("./um:metadata/um:name/um:label", {"um": "http://www.ultimaker.com/material"})
  749. for entry in metadata:
  750. return entry.text