ThreeMFWorkspaceReader.py 44 KB

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