ThreeMFWorkspaceReader.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 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 UM.Util import parseBool
  15. from .WorkspaceDialog import WorkspaceDialog
  16. import xml.etree.ElementTree as ET
  17. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  18. from cura.Settings.ExtruderManager import ExtruderManager
  19. from cura.Settings.ExtruderStack import ExtruderStack
  20. from cura.Settings.GlobalStack import GlobalStack
  21. from cura.Settings.CuraContainerStack import _ContainerIndexes
  22. from cura.QualityManager import QualityManager
  23. from configparser import ConfigParser
  24. import zipfile
  25. import io
  26. import configparser
  27. import os
  28. i18n_catalog = i18nCatalog("cura")
  29. ## Base implementation for reading 3MF workspace files.
  30. class ThreeMFWorkspaceReader(WorkspaceReader):
  31. def __init__(self):
  32. super().__init__()
  33. self._supported_extensions = [".3mf"]
  34. self._dialog = WorkspaceDialog()
  35. self._3mf_mesh_reader = None
  36. self._container_registry = ContainerRegistry.getInstance()
  37. # suffixes registered with the MineTypes don't start with a dot '.'
  38. self._definition_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(DefinitionContainer).preferredSuffix
  39. self._material_container_suffix = None # We have to wait until all other plugins are loaded before we can set it
  40. self._instance_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(InstanceContainer).preferredSuffix
  41. self._container_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ContainerStack).preferredSuffix
  42. self._extruder_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ExtruderStack).preferredSuffix
  43. self._global_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(GlobalStack).preferredSuffix
  44. # Certain instance container types are ignored because we make the assumption that only we make those types
  45. # of containers. They are:
  46. # - quality
  47. # - variant
  48. self._ignored_instance_container_types = {"quality", "variant"}
  49. self._resolve_strategies = {}
  50. self._id_mapping = {}
  51. # In Cura 2.5 and 2.6, the empty profiles used to have those long names
  52. self._old_empty_profile_id_dict = {"empty_%s" % k: "empty" for k in ["material", "variant"]}
  53. ## Get a unique name based on the old_id. This is different from directly calling the registry in that it caches results.
  54. # This has nothing to do with speed, but with getting consistent new naming for instances & objects.
  55. def getNewId(self, old_id):
  56. if old_id not in self._id_mapping:
  57. self._id_mapping[old_id] = self._container_registry.uniqueName(old_id)
  58. return self._id_mapping[old_id]
  59. ## Separates the given file list into a list of GlobalStack files and a list of ExtruderStack files.
  60. #
  61. # In old versions, extruder stack files have the same suffix as container stack files ".stack.cfg".
  62. #
  63. def _determineGlobalAndExtruderStackFiles(self, project_file_name, file_list):
  64. archive = zipfile.ZipFile(project_file_name, "r")
  65. global_stack_file_list = [name for name in file_list if name.endswith(self._global_stack_suffix)]
  66. extruder_stack_file_list = [name for name in file_list if name.endswith(self._extruder_stack_suffix)]
  67. # separate container stack files and extruder stack files
  68. files_to_determine = [name for name in file_list if name.endswith(self._container_stack_suffix)]
  69. for file_name in files_to_determine:
  70. # FIXME: HACK!
  71. # We need to know the type of the stack file, but we can only know it if we deserialize it.
  72. # The default ContainerStack.deserialize() will connect signals, which is not desired in this case.
  73. # Since we know that the stack files are INI files, so we directly use the ConfigParser to parse them.
  74. serialized = archive.open(file_name).read().decode("utf-8")
  75. stack_config = ConfigParser()
  76. stack_config.read_string(serialized)
  77. # sanity check
  78. if not stack_config.has_option("metadata", "type"):
  79. Logger.log("e", "%s in %s doesn't seem to be valid stack file", file_name, project_file_name)
  80. continue
  81. stack_type = stack_config.get("metadata", "type")
  82. if stack_type == "extruder_train":
  83. extruder_stack_file_list.append(file_name)
  84. elif stack_type == "machine":
  85. global_stack_file_list.append(file_name)
  86. else:
  87. Logger.log("w", "Unknown container stack type '%s' from %s in %s",
  88. stack_type, file_name, project_file_name)
  89. if len(global_stack_file_list) != 1:
  90. raise RuntimeError("More than one global stack file found: [%s]" % str(global_stack_file_list))
  91. return global_stack_file_list[0], extruder_stack_file_list
  92. ## read some info so we can make decisions
  93. # \param file_name
  94. # \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.
  95. def preRead(self, file_name, show_dialog=True, *args, **kwargs):
  96. self._3mf_mesh_reader = Application.getInstance().getMeshFileHandler().getReaderForFile(file_name)
  97. if self._3mf_mesh_reader and self._3mf_mesh_reader.preRead(file_name) == WorkspaceReader.PreReadResult.accepted:
  98. pass
  99. else:
  100. Logger.log("w", "Could not find reader that was able to read the scene data for 3MF workspace")
  101. return WorkspaceReader.PreReadResult.failed
  102. machine_name = ""
  103. machine_type = ""
  104. variant_type_name = i18n_catalog.i18nc("@label", "Nozzle")
  105. # Check if there are any conflicts, so we can ask the user.
  106. archive = zipfile.ZipFile(file_name, "r")
  107. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  108. # A few lists of containers in this project files.
  109. # When loading the global stack file, it may be associated with those containers, which may or may not be
  110. # in Cura already, so we need to provide them as alternative search lists.
  111. definition_container_list = []
  112. instance_container_list = []
  113. material_container_list = []
  114. resolve_strategy_keys = ["machine", "material", "quality_changes"]
  115. self._resolve_strategies = {k: None for k in resolve_strategy_keys}
  116. containers_found_dict = {k: False for k in resolve_strategy_keys}
  117. #
  118. # Read definition containers
  119. #
  120. machine_definition_container_count = 0
  121. extruder_definition_container_count = 0
  122. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  123. for each_definition_container_file in definition_container_files:
  124. container_id = self._stripFileToId(each_definition_container_file)
  125. definitions = self._container_registry.findDefinitionContainers(id=container_id)
  126. if not definitions:
  127. definition_container = DefinitionContainer(container_id)
  128. definition_container.deserialize(archive.open(each_definition_container_file).read().decode("utf-8"),
  129. file_name = each_definition_container_file)
  130. else:
  131. definition_container = definitions[0]
  132. definition_container_list.append(definition_container)
  133. definition_container_type = definition_container.getMetaDataEntry("type")
  134. if definition_container_type == "machine":
  135. machine_type = definition_container.getName()
  136. variant_type_name = definition_container.getMetaDataEntry("variants_name", variant_type_name)
  137. machine_definition_container_count += 1
  138. elif definition_container_type == "extruder":
  139. extruder_definition_container_count += 1
  140. else:
  141. Logger.log("w", "Unknown definition container type %s for %s",
  142. definition_container_type, each_definition_container_file)
  143. Job.yieldThread()
  144. # sanity check
  145. if machine_definition_container_count != 1:
  146. msg = "Expecting one machine definition container but got %s" % machine_definition_container_count
  147. Logger.log("e", msg)
  148. raise RuntimeError(msg)
  149. material_labels = []
  150. material_conflict = False
  151. xml_material_profile = self._getXmlProfileClass()
  152. if self._material_container_suffix is None:
  153. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).preferredSuffix
  154. if xml_material_profile:
  155. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  156. for material_container_file in material_container_files:
  157. container_id = self._stripFileToId(material_container_file)
  158. materials = self._container_registry.findInstanceContainers(id=container_id)
  159. material_labels.append(self._getMaterialLabelFromSerialized(archive.open(material_container_file).read().decode("utf-8")))
  160. if materials:
  161. containers_found_dict["material"] = True
  162. if not materials[0].isReadOnly(): # Only non readonly materials can be in conflict
  163. material_conflict = True
  164. Job.yieldThread()
  165. # Check if any quality_changes instance container is in conflict.
  166. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  167. quality_name = ""
  168. quality_type = ""
  169. num_settings_overriden_by_quality_changes = 0 # How many settings are changed by the quality changes
  170. num_settings_overriden_by_definition_changes = 0 # How many settings are changed by the definition changes
  171. num_user_settings = 0
  172. quality_changes_conflict = False
  173. definition_changes_conflict = False
  174. for each_instance_container_file in instance_container_files:
  175. container_id = self._stripFileToId(each_instance_container_file)
  176. instance_container = InstanceContainer(container_id)
  177. # Deserialize InstanceContainer by converting read data from bytes to string
  178. instance_container.deserialize(archive.open(each_instance_container_file).read().decode("utf-8"),
  179. file_name = each_instance_container_file)
  180. instance_container_list.append(instance_container)
  181. container_type = instance_container.getMetaDataEntry("type")
  182. if container_type == "quality_changes":
  183. quality_name = instance_container.getName()
  184. num_settings_overriden_by_quality_changes += len(instance_container._instances)
  185. # Check if quality changes already exists.
  186. quality_changes = self._container_registry.findInstanceContainers(id = container_id)
  187. if quality_changes:
  188. containers_found_dict["quality_changes"] = True
  189. # Check if there really is a conflict by comparing the values
  190. if quality_changes[0] != instance_container:
  191. quality_changes_conflict = True
  192. elif container_type == "definition_changes":
  193. definition_name = instance_container.getName()
  194. num_settings_overriden_by_definition_changes += len(instance_container._instances)
  195. # Check if definition changes already exists.
  196. definition_changes = self._container_registry.findInstanceContainers(id = container_id)
  197. # Check if there is any difference the loaded settings from the project file and the settings in Cura.
  198. if definition_changes:
  199. containers_found_dict["definition_changes"] = True
  200. # Check if there really is a conflict by comparing the values
  201. if definition_changes[0] != instance_container:
  202. definition_changes_conflict = True
  203. elif container_type == "quality":
  204. if not quality_name:
  205. quality_name = instance_container.getName()
  206. elif container_type == "user":
  207. num_user_settings += len(instance_container._instances)
  208. elif container_type in self._ignored_instance_container_types:
  209. # Ignore certain instance container types
  210. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  211. continue
  212. Job.yieldThread()
  213. # Load ContainerStack files and ExtruderStack files
  214. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(
  215. file_name, cura_file_names)
  216. machine_conflict = False
  217. # Because there can be cases as follows:
  218. # - the global stack exists but some/all of the extruder stacks DON'T exist
  219. # - the global stack DOESN'T exist but some/all of the extruder stacks exist
  220. # To simplify this, only check if the global stack exists or not
  221. container_id = self._stripFileToId(global_stack_file)
  222. serialized = archive.open(global_stack_file).read().decode("utf-8")
  223. machine_name = self._getMachineNameFromSerializedStack(serialized)
  224. stacks = self._container_registry.findContainerStacks(id = container_id)
  225. if stacks:
  226. global_stack = stacks[0]
  227. containers_found_dict["machine"] = True
  228. # Check if there are any changes at all in any of the container stacks.
  229. id_list = self._getContainerIdListFromSerialized(serialized)
  230. for index, container_id in enumerate(id_list):
  231. # take into account the old empty container IDs
  232. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  233. if global_stack.getContainer(index).getId() != container_id:
  234. machine_conflict = True
  235. break
  236. Job.yieldThread()
  237. # if the global stack is found, we check if there are conflicts in the extruder stacks
  238. if containers_found_dict["machine"] and not machine_conflict:
  239. for extruder_stack_file in extruder_stack_files:
  240. container_id = self._stripFileToId(extruder_stack_file)
  241. serialized = archive.open(extruder_stack_file).read().decode("utf-8")
  242. parser = configparser.ConfigParser()
  243. parser.read_string(serialized)
  244. # The check should be done for the extruder stack that's associated with the existing global stack,
  245. # and those extruder stacks may have different IDs.
  246. # So we check according to the positions
  247. position = str(parser["metadata"]["position"])
  248. if position not in global_stack.extruders:
  249. # The extruder position defined in the project doesn't exist in this global stack.
  250. # We can say that it is a machine conflict, but it is very hard to override the machine in this
  251. # case because we need to override the existing extruders and add the non-existing extruders.
  252. #
  253. # HACK:
  254. # To make this simple, we simply say that there is no machine conflict and create a new machine
  255. # by default.
  256. machine_conflict = False
  257. break
  258. existing_extruder_stack = global_stack.extruders[position]
  259. # check if there are any changes at all in any of the container stacks.
  260. id_list = self._getContainerIdListFromSerialized(serialized)
  261. for index, container_id in enumerate(id_list):
  262. # take into account the old empty container IDs
  263. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  264. if existing_extruder_stack.getContainer(index).getId() != container_id:
  265. machine_conflict = True
  266. break
  267. num_visible_settings = 0
  268. has_visible_settings_string = False
  269. try:
  270. temp_preferences = Preferences()
  271. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  272. temp_preferences.deserialize(serialized)
  273. visible_settings_string = temp_preferences.getValue("general/visible_settings")
  274. has_visible_settings_string = visible_settings_string is not None
  275. if visible_settings_string is not None:
  276. num_visible_settings = len(visible_settings_string.split(";"))
  277. active_mode = temp_preferences.getValue("cura/active_mode")
  278. if not active_mode:
  279. active_mode = Preferences.getInstance().getValue("cura/active_mode")
  280. except KeyError:
  281. # If there is no preferences file, it's not a workspace, so notify user of failure.
  282. Logger.log("w", "File %s is not a valid workspace.", file_name)
  283. return WorkspaceReader.PreReadResult.failed
  284. # In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  285. if not show_dialog:
  286. return WorkspaceReader.PreReadResult.accepted
  287. # prepare data for the dialog
  288. num_extruders = extruder_definition_container_count
  289. if num_extruders == 0:
  290. num_extruders = 1 # No extruder stacks found, which means there is one extruder
  291. extruders = num_extruders * [""]
  292. # Show the dialog, informing the user what is about to happen.
  293. self._dialog.setMachineConflict(machine_conflict)
  294. self._dialog.setQualityChangesConflict(quality_changes_conflict)
  295. self._dialog.setDefinitionChangesConflict(definition_changes_conflict)
  296. self._dialog.setMaterialConflict(material_conflict)
  297. self._dialog.setHasVisibleSettingsField(has_visible_settings_string)
  298. self._dialog.setNumVisibleSettings(num_visible_settings)
  299. self._dialog.setQualityName(quality_name)
  300. self._dialog.setQualityType(quality_type)
  301. self._dialog.setNumSettingsOverridenByQualityChanges(num_settings_overriden_by_quality_changes)
  302. self._dialog.setNumUserSettings(num_user_settings)
  303. self._dialog.setActiveMode(active_mode)
  304. self._dialog.setMachineName(machine_name)
  305. self._dialog.setMaterialLabels(material_labels)
  306. self._dialog.setMachineType(machine_type)
  307. self._dialog.setExtruders(extruders)
  308. self._dialog.setVariantType(variant_type_name)
  309. self._dialog.setHasObjectsOnPlate(Application.getInstance().platformActivity)
  310. self._dialog.show()
  311. # Block until the dialog is closed.
  312. self._dialog.waitForClose()
  313. if self._dialog.getResult() == {}:
  314. return WorkspaceReader.PreReadResult.cancelled
  315. self._resolve_strategies = self._dialog.getResult()
  316. #
  317. # There can be 3 resolve strategies coming from the dialog:
  318. # - new: create a new container
  319. # - override: override the existing container
  320. # - None: There is no conflict, which means containers with the same IDs may or may not be there already.
  321. # If there is an existing container, there is no conflict between them, and default to "override"
  322. # If there is no existing container, default to "new"
  323. #
  324. # Default values
  325. for key, strategy in self._resolve_strategies.items():
  326. if key not in containers_found_dict or strategy is not None:
  327. continue
  328. self._resolve_strategies[key] = "override" if containers_found_dict[key] else "new"
  329. return WorkspaceReader.PreReadResult.accepted
  330. ## Overrides an ExtruderStack in the given GlobalStack and returns the new ExtruderStack.
  331. def _overrideExtruderStack(self, global_stack, extruder_file_content, extruder_stack_file):
  332. # Get extruder position first
  333. extruder_config = configparser.ConfigParser()
  334. extruder_config.read_string(extruder_file_content)
  335. if not extruder_config.has_option("metadata", "position"):
  336. msg = "Could not find 'metadata/position' in extruder stack file"
  337. Logger.log("e", "Could not find 'metadata/position' in extruder stack file")
  338. raise RuntimeError(msg)
  339. extruder_position = extruder_config.get("metadata", "position")
  340. try:
  341. extruder_stack = global_stack.extruders[extruder_position]
  342. except KeyError:
  343. Logger.log("w", "Could not find the matching extruder stack to override for position %s", extruder_position)
  344. return None
  345. # Override the given extruder stack
  346. extruder_stack.deserialize(extruder_file_content, file_name = extruder_stack_file)
  347. # return the new ExtruderStack
  348. return extruder_stack
  349. ## Read the project file
  350. # Add all the definitions / materials / quality changes that do not exist yet. Then it loads
  351. # all the stacks into the container registry. In some cases it will reuse the container for the global stack.
  352. # It handles old style project files containing .stack.cfg as well as new style project files
  353. # containing global.cfg / extruder.cfg
  354. #
  355. # \param file_name
  356. def read(self, file_name):
  357. archive = zipfile.ZipFile(file_name, "r")
  358. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  359. # Create a shadow copy of the preferences (we don't want all of the preferences, but we do want to re-use its
  360. # parsing code.
  361. temp_preferences = Preferences()
  362. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  363. temp_preferences.deserialize(serialized)
  364. # Copy a number of settings from the temp preferences to the global
  365. global_preferences = Preferences.getInstance()
  366. visible_settings = temp_preferences.getValue("general/visible_settings")
  367. if visible_settings is None:
  368. Logger.log("w", "Workspace did not contain visible settings. Leaving visibility unchanged")
  369. else:
  370. global_preferences.setValue("general/visible_settings", visible_settings)
  371. categories_expanded = temp_preferences.getValue("cura/categories_expanded")
  372. if categories_expanded is None:
  373. Logger.log("w", "Workspace did not contain expanded categories. Leaving them unchanged")
  374. else:
  375. global_preferences.setValue("cura/categories_expanded", categories_expanded)
  376. Application.getInstance().expandedCategoriesChanged.emit() # Notify the GUI of the change
  377. self._id_mapping = {}
  378. # We don't add containers right away, but wait right until right before the stack serialization.
  379. # We do this so that if something goes wrong, it's easier to clean up.
  380. containers_to_add = []
  381. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(file_name, cura_file_names)
  382. global_stack = None
  383. extruder_stacks = []
  384. extruder_stacks_added = []
  385. container_stacks_added = []
  386. machine_extruder_count = None
  387. containers_added = []
  388. global_stack_id_original = self._stripFileToId(global_stack_file)
  389. global_stack_id_new = global_stack_id_original
  390. global_stack_name_original = self._getMachineNameFromSerializedStack(archive.open(global_stack_file).read().decode("utf-8"))
  391. global_stack_name_new = global_stack_name_original
  392. global_stack_need_rename = False
  393. extruder_stack_id_map = {} # new and old ExtruderStack IDs map
  394. if self._resolve_strategies["machine"] == "new":
  395. # We need a new id if the id already exists
  396. if self._container_registry.findContainerStacks(id = global_stack_id_original):
  397. global_stack_id_new = self.getNewId(global_stack_id_original)
  398. global_stack_need_rename = True
  399. global_stack_name_new = self._container_registry.uniqueName(global_stack_name_original)
  400. for each_extruder_stack_file in extruder_stack_files:
  401. old_container_id = self._stripFileToId(each_extruder_stack_file)
  402. new_container_id = old_container_id
  403. if self._container_registry.findContainerStacks(id = old_container_id):
  404. # get a new name for this extruder
  405. new_container_id = self.getNewId(old_container_id)
  406. extruder_stack_id_map[old_container_id] = new_container_id
  407. # TODO: For the moment we use pretty naive existence checking. If the ID is the same, we assume in quite a few
  408. # TODO: cases that the container loaded is the same (most notable in materials & definitions).
  409. # TODO: It might be possible that we need to add smarter checking in the future.
  410. Logger.log("d", "Workspace loading is checking definitions...")
  411. # Get all the definition files & check if they exist. If not, add them.
  412. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  413. for definition_container_file in definition_container_files:
  414. container_id = self._stripFileToId(definition_container_file)
  415. definitions = self._container_registry.findDefinitionContainers(id = container_id)
  416. if not definitions:
  417. definition_container = DefinitionContainer(container_id)
  418. definition_container.deserialize(archive.open(definition_container_file).read().decode("utf-8"),
  419. file_name = definition_container_file)
  420. self._container_registry.addContainer(definition_container)
  421. Job.yieldThread()
  422. Logger.log("d", "Workspace loading is checking materials...")
  423. material_containers = []
  424. # Get all the material files and check if they exist. If not, add them.
  425. xml_material_profile = self._getXmlProfileClass()
  426. if self._material_container_suffix is None:
  427. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).suffixes[0]
  428. if xml_material_profile:
  429. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  430. for material_container_file in material_container_files:
  431. container_id = self._stripFileToId(material_container_file)
  432. materials = self._container_registry.findInstanceContainers(id = container_id)
  433. if not materials:
  434. material_container = xml_material_profile(container_id)
  435. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"),
  436. file_name = material_container_file)
  437. containers_to_add.append(material_container)
  438. else:
  439. material_container = materials[0]
  440. if not material_container.isReadOnly(): # Only create new materials if they are not read only.
  441. if self._resolve_strategies["material"] == "override":
  442. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"),
  443. file_name = material_container_file)
  444. elif self._resolve_strategies["material"] == "new":
  445. # Note that we *must* deserialize it with a new ID, as multiple containers will be
  446. # auto created & added.
  447. material_container = xml_material_profile(self.getNewId(container_id))
  448. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"),
  449. file_name = material_container_file)
  450. containers_to_add.append(material_container)
  451. material_containers.append(material_container)
  452. Job.yieldThread()
  453. Logger.log("d", "Workspace loading is checking instance containers...")
  454. # Get quality_changes and user profiles saved in the workspace
  455. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  456. user_instance_containers = []
  457. quality_and_definition_changes_instance_containers = []
  458. for instance_container_file in instance_container_files:
  459. container_id = self._stripFileToId(instance_container_file)
  460. serialized = archive.open(instance_container_file).read().decode("utf-8")
  461. # HACK! we ignore "quality" and "variant" instance containers!
  462. parser = configparser.ConfigParser()
  463. parser.read_string(serialized)
  464. if not parser.has_option("metadata", "type"):
  465. Logger.log("w", "Cannot find metadata/type in %s, ignoring it", instance_container_file)
  466. continue
  467. if parser.get("metadata", "type") in self._ignored_instance_container_types:
  468. continue
  469. instance_container = InstanceContainer(container_id)
  470. # Deserialize InstanceContainer by converting read data from bytes to string
  471. instance_container.deserialize(serialized, file_name = instance_container_file)
  472. container_type = instance_container.getMetaDataEntry("type")
  473. Job.yieldThread()
  474. #
  475. # IMPORTANT:
  476. # If an instance container (or maybe other type of container) exists, and user chooses "Create New",
  477. # we need to rename this container and all references to it, and changing those references are VERY
  478. # HARD.
  479. #
  480. if container_type in self._ignored_instance_container_types:
  481. # Ignore certain instance container types
  482. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  483. continue
  484. elif container_type == "user":
  485. # Check if quality changes already exists.
  486. user_containers = self._container_registry.findInstanceContainers(id = container_id)
  487. if not user_containers:
  488. containers_to_add.append(instance_container)
  489. else:
  490. if self._resolve_strategies["machine"] == "override" or self._resolve_strategies["machine"] is None:
  491. instance_container = user_containers[0]
  492. instance_container.deserialize(archive.open(instance_container_file).read().decode("utf-8"),
  493. file_name = instance_container_file)
  494. instance_container.setDirty(True)
  495. elif self._resolve_strategies["machine"] == "new":
  496. # The machine is going to get a spiffy new name, so ensure that the id's of user settings match.
  497. old_extruder_id = instance_container.getMetaDataEntry("extruder", None)
  498. if old_extruder_id:
  499. new_extruder_id = extruder_stack_id_map[old_extruder_id]
  500. new_id = new_extruder_id + "_current_settings"
  501. instance_container._id = new_id
  502. instance_container.setName(new_id)
  503. instance_container.setMetaDataEntry("extruder", new_extruder_id)
  504. containers_to_add.append(instance_container)
  505. machine_id = instance_container.getMetaDataEntry("machine", None)
  506. if machine_id:
  507. new_machine_id = self.getNewId(machine_id)
  508. new_id = new_machine_id + "_current_settings"
  509. instance_container._id = new_id
  510. instance_container.setName(new_id)
  511. instance_container.setMetaDataEntry("machine", new_machine_id)
  512. containers_to_add.append(instance_container)
  513. user_instance_containers.append(instance_container)
  514. elif container_type in ("quality_changes", "definition_changes"):
  515. # Check if quality changes already exists.
  516. changes_containers = self._container_registry.findInstanceContainers(id = container_id)
  517. if not changes_containers:
  518. # no existing containers with the same ID, so we can safely add the new one
  519. containers_to_add.append(instance_container)
  520. else:
  521. # we have found existing container with the same ID, so we need to resolve according to the
  522. # selected strategy.
  523. if self._resolve_strategies[container_type] == "override":
  524. instance_container = changes_containers[0]
  525. instance_container.deserialize(archive.open(instance_container_file).read().decode("utf-8"),
  526. file_name = instance_container_file)
  527. instance_container.setDirty(True)
  528. elif self._resolve_strategies[container_type] == "new":
  529. # TODO: how should we handle the case "new" for quality_changes and definition_changes?
  530. instance_container.setName(self._container_registry.uniqueName(instance_container.getName()))
  531. new_changes_container_id = self.getNewId(instance_container.getId())
  532. instance_container._id = new_changes_container_id
  533. # TODO: we don't know the following is correct or not, need to verify
  534. # AND REFACTOR!!!
  535. if self._resolve_strategies["machine"] == "new":
  536. # The machine is going to get a spiffy new name, so ensure that the id's of user settings match.
  537. old_extruder_id = instance_container.getMetaDataEntry("extruder", None)
  538. # Note that in case of a quality_changes extruder means the definition id of the extruder stack
  539. # For the user settings, it means the actual extruder stack id it's assigned to.
  540. if old_extruder_id and old_extruder_id in extruder_stack_id_map:
  541. new_extruder_id = extruder_stack_id_map[old_extruder_id]
  542. instance_container.setMetaDataEntry("extruder", new_extruder_id)
  543. machine_id = instance_container.getMetaDataEntry("machine", None)
  544. if machine_id:
  545. new_machine_id = self.getNewId(machine_id)
  546. instance_container.setMetaDataEntry("machine", new_machine_id)
  547. containers_to_add.append(instance_container)
  548. elif self._resolve_strategies[container_type] is None:
  549. # The ID already exists, but nothing in the values changed, so do nothing.
  550. pass
  551. quality_and_definition_changes_instance_containers.append(instance_container)
  552. if container_type == "definition_changes":
  553. definition_changes_extruder_count = instance_container.getProperty("machine_extruder_count", "value")
  554. if definition_changes_extruder_count is not None:
  555. machine_extruder_count = definition_changes_extruder_count
  556. else:
  557. existing_container = self._container_registry.findInstanceContainers(id = container_id)
  558. if not existing_container:
  559. containers_to_add.append(instance_container)
  560. if global_stack_need_rename:
  561. if instance_container.getMetaDataEntry("machine"):
  562. instance_container.setMetaDataEntry("machine", global_stack_id_new)
  563. # Add all the containers right before we try to add / serialize the stack
  564. for container in containers_to_add:
  565. self._container_registry.addContainer(container)
  566. container.setDirty(True)
  567. containers_added.append(container)
  568. # Get the stack(s) saved in the workspace.
  569. Logger.log("d", "Workspace loading is checking stacks containers...")
  570. # load global stack file
  571. try:
  572. stack = None
  573. if self._resolve_strategies["machine"] == "override":
  574. container_stacks = self._container_registry.findContainerStacks(id = global_stack_id_original)
  575. stack = container_stacks[0]
  576. # HACK
  577. # There is a machine, check if it has authentication data. If so, keep that data.
  578. network_authentication_id = container_stacks[0].getMetaDataEntry("network_authentication_id")
  579. network_authentication_key = container_stacks[0].getMetaDataEntry("network_authentication_key")
  580. container_stacks[0].deserialize(archive.open(global_stack_file).read().decode("utf-8"),
  581. file_name = global_stack_file)
  582. if network_authentication_id:
  583. container_stacks[0].addMetaDataEntry("network_authentication_id", network_authentication_id)
  584. if network_authentication_key:
  585. container_stacks[0].addMetaDataEntry("network_authentication_key", network_authentication_key)
  586. elif self._resolve_strategies["machine"] == "new":
  587. # create a new global stack
  588. stack = GlobalStack(global_stack_id_new)
  589. # Deserialize stack by converting read data from bytes to string
  590. stack.deserialize(archive.open(global_stack_file).read().decode("utf-8"),
  591. file_name = global_stack_file)
  592. # Ensure a unique ID and name
  593. stack._id = global_stack_id_new
  594. # Extruder stacks are "bound" to a machine. If we add the machine as a new one, the id of the
  595. # bound machine also needs to change.
  596. if stack.getMetaDataEntry("machine", None):
  597. stack.setMetaDataEntry("machine", global_stack_id_new)
  598. # Only machines need a new name, stacks may be non-unique
  599. stack.setName(global_stack_name_new)
  600. container_stacks_added.append(stack)
  601. self._container_registry.addContainer(stack)
  602. containers_added.append(stack)
  603. else:
  604. Logger.log("e", "Resolve strategy of %s for machine is not supported", self._resolve_strategies["machine"])
  605. # Create a new definition_changes container if it was empty
  606. if stack.definitionChanges == self._container_registry.getEmptyInstanceContainer():
  607. stack.setDefinitionChanges(CuraStackBuilder.createDefinitionChangesContainer(stack, stack.getId() + "_settings"))
  608. global_stack = stack
  609. Job.yieldThread()
  610. except:
  611. Logger.logException("w", "We failed to serialize the stack. Trying to clean up.")
  612. # Something went really wrong. Try to remove any data that we added.
  613. for container in containers_added:
  614. self._container_registry.removeContainer(container.getId())
  615. return
  616. # load extruder stack files
  617. try:
  618. for extruder_stack_file in extruder_stack_files:
  619. container_id = self._stripFileToId(extruder_stack_file)
  620. extruder_file_content = archive.open(extruder_stack_file, "r").read().decode("utf-8")
  621. if self._resolve_strategies["machine"] == "override":
  622. # deserialize new extruder stack over the current ones (if any)
  623. stack = self._overrideExtruderStack(global_stack, extruder_file_content, extruder_stack_file)
  624. if stack is None:
  625. continue
  626. elif self._resolve_strategies["machine"] == "new":
  627. new_id = extruder_stack_id_map[container_id]
  628. stack = ExtruderStack(new_id)
  629. # HACK: the global stack can have a new name, so we need to make sure that this extruder stack
  630. # references to the new name instead of the old one. Normally, this can be done after
  631. # deserialize() by setting the metadata, but in the case of ExtruderStack, deserialize()
  632. # also does addExtruder() to its machine stack, so we have to make sure that it's pointing
  633. # to the right machine BEFORE deserialization.
  634. extruder_config = configparser.ConfigParser()
  635. extruder_config.read_string(extruder_file_content)
  636. extruder_config.set("metadata", "machine", global_stack_id_new)
  637. tmp_string_io = io.StringIO()
  638. extruder_config.write(tmp_string_io)
  639. extruder_file_content = tmp_string_io.getvalue()
  640. stack.deserialize(extruder_file_content, file_name = extruder_stack_file)
  641. # Ensure a unique ID and name
  642. stack._id = new_id
  643. self._container_registry.addContainer(stack)
  644. extruder_stacks_added.append(stack)
  645. containers_added.append(stack)
  646. else:
  647. Logger.log("w", "Unknown resolve strategy: %s", self._resolve_strategies["machine"])
  648. # Create a new definition_changes container if it was empty
  649. if stack.definitionChanges == self._container_registry.getEmptyInstanceContainer():
  650. stack.setDefinitionChanges(CuraStackBuilder.createDefinitionChangesContainer(stack, stack.getId() + "_settings"))
  651. if stack.getMetaDataEntry("type") == "extruder_train":
  652. extruder_stacks.append(stack)
  653. # If not extruder stacks were saved in the project file (pre 3.1) create one manually
  654. # We re-use the container registry's addExtruderStackForSingleExtrusionMachine method for this
  655. if not extruder_stacks:
  656. stack = self._container_registry.addExtruderStackForSingleExtrusionMachine(global_stack, "fdmextruder")
  657. if stack:
  658. if self._resolve_strategies["machine"] == "override":
  659. # in case the extruder is newly created (for a single-extrusion machine), we need to override
  660. # the existing extruder stack.
  661. existing_extruder_stack = global_stack.extruders[stack.getMetaDataEntry("position")]
  662. for idx in range(len(_ContainerIndexes.IndexTypeMap)):
  663. existing_extruder_stack.replaceContainer(idx, stack._containers[idx], postpone_emit = True)
  664. extruder_stacks.append(existing_extruder_stack)
  665. else:
  666. extruder_stacks.append(stack)
  667. except:
  668. Logger.logException("w", "We failed to serialize the stack. Trying to clean up.")
  669. # Something went really wrong. Try to remove any data that we added.
  670. for container in containers_added:
  671. self._container_registry.removeContainer(container.getId())
  672. return
  673. # Check quality profiles to make sure that if one stack has the "not supported" quality profile,
  674. # all others should have the same.
  675. #
  676. # This block code tries to fix the following problems in Cura 3.0 and earlier:
  677. # 1. The upgrade script can rename all "Not Supported" quality profiles to "empty_quality", but it cannot fix
  678. # the problem that the global stack the extruder stacks may have different quality profiles. The code
  679. # below loops over all stacks and make sure that if there is one stack with "Not Supported" profile, the
  680. # rest should also use the "Not Supported" profile.
  681. # 2. In earlier versions (at least 2.7 and 3.0), a wrong quality profile could be assigned to a stack. For
  682. # example, a UM3 can have a BB 0.8 variant with "aa04_pla_fast" quality profile enabled. To fix this,
  683. # in the code below we also check the actual available quality profiles for the machine.
  684. #
  685. has_not_supported = False
  686. for stack in [global_stack] + extruder_stacks:
  687. if stack.quality.getId() in ("empty", "empty_quality"):
  688. has_not_supported = True
  689. break
  690. # We filter out extruder stacks that are not actually used, for example the UM3 and custom FDM printer extruder count setting.
  691. extruder_stacks_in_use = extruder_stacks
  692. if machine_extruder_count is not None:
  693. extruder_stacks_in_use = extruder_stacks[:machine_extruder_count]
  694. available_quality = QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_stack,
  695. extruder_stacks_in_use)
  696. if not has_not_supported:
  697. has_not_supported = not available_quality
  698. quality_has_been_changed = False
  699. if has_not_supported:
  700. empty_quality_container = self._container_registry.findInstanceContainers(id = "empty_quality")[0]
  701. for stack in [global_stack] + extruder_stacks_in_use:
  702. stack.replaceContainer(_ContainerIndexes.Quality, empty_quality_container)
  703. empty_quality_changes_container = self._container_registry.findInstanceContainers(id = "empty_quality_changes")[0]
  704. for stack in [global_stack] + extruder_stacks_in_use:
  705. stack.replaceContainer(_ContainerIndexes.QualityChanges, empty_quality_changes_container)
  706. quality_has_been_changed = True
  707. else:
  708. empty_quality_changes_container = self._container_registry.findInstanceContainers(id="empty_quality_changes")[0]
  709. # The machine in the project has non-empty quality and there are usable qualities for this machine.
  710. # We need to check if the current quality_type is still usable for this machine, if not, then the quality
  711. # will be reset to the "preferred quality" if present, otherwise "normal".
  712. available_quality_types = [q.getMetaDataEntry("quality_type") for q in available_quality]
  713. if global_stack.quality.getMetaDataEntry("quality_type") not in available_quality_types:
  714. # We are here because the quality_type specified in the project is not supported any more,
  715. # so we need to switch it to the "preferred quality" if present, otherwise "normal".
  716. quality_has_been_changed = True
  717. # find the preferred quality
  718. preferred_quality_id = global_stack.getMetaDataEntry("preferred_quality", None)
  719. if preferred_quality_id is not None:
  720. definition_id = global_stack.definition.getId()
  721. definition_id = global_stack.definition.getMetaDataEntry("quality_definition", definition_id)
  722. if not parseBool(global_stack.getMetaDataEntry("has_machine_quality", "False")):
  723. definition_id = "fdmprinter"
  724. containers = self._container_registry.findInstanceContainers(id = preferred_quality_id,
  725. type = "quality",
  726. definition = definition_id)
  727. containers = [c for c in containers if not c.getMetaDataEntry("material", "")]
  728. if containers:
  729. global_stack.quality = containers[0]
  730. global_stack.qualityChanges = empty_quality_changes_container
  731. # also find the quality containers for the extruders
  732. for extruder_stack in extruder_stacks_in_use:
  733. search_criteria = {"id": preferred_quality_id,
  734. "type": "quality",
  735. "definition": definition_id}
  736. if global_stack.getMetaDataEntry("has_machine_materials") and extruder_stack.material.getId() not in ("empty", "empty_material"):
  737. search_criteria["material"] = extruder_stack.material.getId()
  738. containers = self._container_registry.findInstanceContainers(**search_criteria)
  739. if containers:
  740. extruder_stack.quality = containers[0]
  741. extruder_stack.qualityChanges = empty_quality_changes_container
  742. else:
  743. Logger.log("e", "Cannot find preferred quality for extruder [%s].", extruder_stack.getId())
  744. else:
  745. # we cannot find the preferred quality. THIS SHOULD NOT HAPPEN
  746. Logger.log("e", "Cannot find the preferred quality for machine [%s]", global_stack.getId())
  747. else:
  748. # The quality_type specified in the project file is usable, but the quality container itself may not
  749. # be correct. For example, for UM2, the quality container can be "draft" while it should be "um2_draft"
  750. # instead.
  751. # In this code branch, we try to fix those incorrect quality containers.
  752. #
  753. # ***IMPORTANT***: We only do this fix for single-extrusion machines.
  754. # We will first find the correct quality profile for the extruder, then apply the same
  755. # quality profile for the global stack.
  756. #
  757. if len(extruder_stacks) == 1:
  758. extruder_stack = extruder_stacks[0]
  759. search_criteria = {"type": "quality", "quality_type": global_stack.quality.getMetaDataEntry("quality_type")}
  760. search_criteria["definition"] = global_stack.definition.getId()
  761. if not parseBool(global_stack.getMetaDataEntry("has_machine_quality", "False")):
  762. search_criteria["definition"] = "fdmprinter"
  763. if global_stack.getMetaDataEntry("has_machine_materials") and extruder_stack.material.getId() not in ("empty", "empty_material"):
  764. search_criteria["material"] = extruder_stack.material.getId()
  765. containers = self._container_registry.findInstanceContainers(**search_criteria)
  766. if containers:
  767. new_quality_container = containers[0]
  768. extruder_stack.quality = new_quality_container
  769. global_stack.quality = new_quality_container
  770. # Replacing the old containers if resolve is "new".
  771. # When resolve is "new", some containers will get renamed, so all the other containers that reference to those
  772. # MUST get updated too.
  773. #
  774. if self._resolve_strategies["machine"] == "new":
  775. # A new machine was made, but it was serialized with the wrong user container. Fix that now.
  776. for container in user_instance_containers:
  777. # replacing the container ID for user instance containers for the extruders
  778. extruder_id = container.getMetaDataEntry("extruder", None)
  779. if extruder_id:
  780. for extruder in extruder_stacks:
  781. if extruder.getId() == extruder_id:
  782. extruder.userChanges = container
  783. continue
  784. # replacing the container ID for user instance containers for the machine
  785. machine_id = container.getMetaDataEntry("machine", None)
  786. if machine_id:
  787. if global_stack.getId() == machine_id:
  788. global_stack.userChanges = container
  789. continue
  790. changes_container_types = ("quality_changes", "definition_changes")
  791. if quality_has_been_changed:
  792. # DO NOT replace quality_changes if the current quality_type is not supported
  793. changes_container_types = ("definition_changes",)
  794. for changes_container_type in changes_container_types:
  795. if self._resolve_strategies[changes_container_type] == "new":
  796. # Quality changes needs to get a new ID, added to registry and to the right stacks
  797. for each_changes_container in quality_and_definition_changes_instance_containers:
  798. # NOTE: The renaming and giving new IDs are possibly redundant because they are done in the
  799. # instance container loading part.
  800. new_id = each_changes_container.getId()
  801. # Find the old (current) changes container in the global stack
  802. if changes_container_type == "quality_changes":
  803. old_container = global_stack.qualityChanges
  804. elif changes_container_type == "definition_changes":
  805. old_container = global_stack.definitionChanges
  806. # sanity checks
  807. # NOTE: The following cases SHOULD NOT happen!!!!
  808. if not old_container:
  809. Logger.log("e", "We try to get [%s] from the global stack [%s] but we got None instead!",
  810. changes_container_type, global_stack.getId())
  811. # Replace the quality/definition changes container if it's in the GlobalStack
  812. # NOTE: we can get an empty container here, but the IDs will not match,
  813. # so this comparison is fine.
  814. if self._id_mapping.get(old_container.getId()) == new_id:
  815. if changes_container_type == "quality_changes":
  816. global_stack.qualityChanges = each_changes_container
  817. elif changes_container_type == "definition_changes":
  818. global_stack.definitionChanges = each_changes_container
  819. continue
  820. # Replace the quality/definition changes container if it's in one of the ExtruderStacks
  821. for each_extruder_stack in extruder_stacks:
  822. changes_container = None
  823. if changes_container_type == "quality_changes":
  824. changes_container = each_extruder_stack.qualityChanges
  825. elif changes_container_type == "definition_changes":
  826. changes_container = each_extruder_stack.definitionChanges
  827. # sanity checks
  828. # NOTE: The following cases SHOULD NOT happen!!!!
  829. if not changes_container:
  830. Logger.log("e", "We try to get [%s] from the extruder stack [%s] but we got None instead!",
  831. changes_container_type, each_extruder_stack.getId())
  832. # NOTE: we can get an empty container here, but the IDs will not match,
  833. # so this comparison is fine.
  834. if self._id_mapping.get(changes_container.getId()) == new_id:
  835. if changes_container_type == "quality_changes":
  836. each_extruder_stack.qualityChanges = each_changes_container
  837. elif changes_container_type == "definition_changes":
  838. each_extruder_stack.definitionChanges = each_changes_container
  839. if self._resolve_strategies["material"] == "new":
  840. # the actual material instance container can have an ID such as
  841. # <material>_<machine>_<variant>
  842. # which cannot be determined immediately, so here we use a HACK to find the right new material
  843. # instance ID:
  844. # - get the old material IDs for all material
  845. # - find the old material with the longest common prefix in ID, that's the old material
  846. # - update the name by replacing the old prefix with the new
  847. # - find the new material container and set it to the stack
  848. old_to_new_material_dict = {}
  849. for each_material in material_containers:
  850. # find the material's old name
  851. for old_id, new_id in self._id_mapping.items():
  852. if each_material.getId() == new_id:
  853. old_to_new_material_dict[old_id] = each_material
  854. break
  855. # replace old material in global and extruder stacks with new
  856. self._replaceStackMaterialWithNew(global_stack, old_to_new_material_dict)
  857. if extruder_stacks:
  858. for each_extruder_stack in extruder_stacks:
  859. self._replaceStackMaterialWithNew(each_extruder_stack, old_to_new_material_dict)
  860. if extruder_stacks:
  861. for stack in extruder_stacks:
  862. ExtruderManager.getInstance().registerExtruder(stack, global_stack.getId())
  863. Logger.log("d", "Workspace loading is notifying rest of the code of changes...")
  864. if self._resolve_strategies["machine"] == "new":
  865. for stack in extruder_stacks:
  866. stack.setNextStack(global_stack)
  867. stack.containersChanged.emit(stack.getTop())
  868. # Actually change the active machine.
  869. Application.getInstance().setGlobalContainerStack(global_stack)
  870. # Notify everything/one that is to notify about changes.
  871. global_stack.containersChanged.emit(global_stack.getTop())
  872. # Load all the nodes / meshdata of the workspace
  873. nodes = self._3mf_mesh_reader.read(file_name)
  874. if nodes is None:
  875. nodes = []
  876. base_file_name = os.path.basename(file_name)
  877. if base_file_name.endswith(".curaproject.3mf"):
  878. base_file_name = base_file_name[:base_file_name.rfind(".curaproject.3mf")]
  879. self.setWorkspaceName(base_file_name)
  880. return nodes
  881. ## HACK: Replaces the material container in the given stack with a newly created material container.
  882. # This function is used when the user chooses to resolve material conflicts by creating new ones.
  883. def _replaceStackMaterialWithNew(self, stack, old_new_material_dict):
  884. # The material containers in the project file are 'parent' material such as "generic_pla",
  885. # but a material container used in a global/extruder stack is a 'child' material,
  886. # such as "generic_pla_ultimaker3_AA_0.4", which can be formalised as the following:
  887. #
  888. # <material_name>_<machine_name>_<variant_name>
  889. #
  890. # In the project loading, when a user chooses to resolve material conflicts by creating new ones,
  891. # the old 'parent' material ID and the new 'parent' material ID are known, but not the child material IDs.
  892. # In this case, the global stack and the extruder stacks need to use the newly created material, but the
  893. # material containers they use are 'child' material. So, here, we need to find the right 'child' material for
  894. # the stacks.
  895. #
  896. # This hack approach works as follows:
  897. # - No matter there is a child material or not, the actual material we are looking for has the prefix
  898. # "<material_name>", which is the old material name. For the material in a stack, we know that the new
  899. # material's ID will be "<new_material_name>_blabla..", so we just need to replace the old material ID
  900. # with the new one to get the new 'child' material.
  901. # - Because the material containers have IDs such as "m #nn", if we use simple prefix matching, there can
  902. # be a problem in the following scenario:
  903. # - there are two materials in the project file, namely "m #1" and "m #11"
  904. # - the child materials in use are for example: "m #1_um3_aa04", "m #11_um3_aa04"
  905. # - if we only check for a simple prefix match, then "m #11_um3_aa04" will match with "m #1", but they
  906. # are not the same material
  907. # To avoid this, when doing the prefix matching, we use the result with the longest mactching prefix.
  908. # find the old material ID
  909. old_material_id_in_stack = stack.material.getId()
  910. best_matching_old_material_id = None
  911. best_matching_old_meterial_prefix_length = -1
  912. for old_parent_material_id in old_new_material_dict:
  913. if len(old_parent_material_id) < best_matching_old_meterial_prefix_length:
  914. continue
  915. if len(old_parent_material_id) <= len(old_material_id_in_stack):
  916. if old_parent_material_id == old_material_id_in_stack[0:len(old_parent_material_id)]:
  917. best_matching_old_meterial_prefix_length = len(old_parent_material_id)
  918. best_matching_old_material_id = old_parent_material_id
  919. if best_matching_old_material_id is None:
  920. Logger.log("w", "Cannot find any matching old material ID for stack [%s] material [%s]. Something can go wrong",
  921. stack.getId(), old_material_id_in_stack)
  922. return
  923. # find the new material container
  924. new_material_id = old_new_material_dict[best_matching_old_material_id].getId() + old_material_id_in_stack[len(best_matching_old_material_id):]
  925. new_material_containers = self._container_registry.findInstanceContainers(id = new_material_id, type = "material")
  926. if not new_material_containers:
  927. Logger.log("e", "Cannot find new material container [%s]", new_material_id)
  928. return
  929. # replace the material in the given stack
  930. stack.material = new_material_containers[0]
  931. def _stripFileToId(self, file):
  932. mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
  933. file = mime_type.stripExtension(file)
  934. return file.replace("Cura/", "")
  935. def _getXmlProfileClass(self):
  936. return self._container_registry.getContainerForMimeType(MimeTypeDatabase.getMimeType("application/x-ultimaker-material-profile"))
  937. ## Get the list of ID's of all containers in a container stack by partially parsing it's serialized data.
  938. def _getContainerIdListFromSerialized(self, serialized):
  939. parser = configparser.ConfigParser(interpolation=None, empty_lines_in_values=False)
  940. parser.read_string(serialized)
  941. container_ids = []
  942. if "containers" in parser:
  943. for index, container_id in parser.items("containers"):
  944. container_ids.append(container_id)
  945. elif parser.has_option("general", "containers"):
  946. container_string = parser["general"].get("containers", "")
  947. container_list = container_string.split(",")
  948. container_ids = [container_id for container_id in container_list if container_id != ""]
  949. # HACK: there used to be 6 containers numbering from 0 to 5 in a stack,
  950. # now we have 7: index 5 becomes "definition_changes"
  951. if len(container_ids) == 6:
  952. # Hack; We used to not save the definition changes. Fix this.
  953. container_ids.insert(5, "empty")
  954. return container_ids
  955. def _getMachineNameFromSerializedStack(self, serialized):
  956. parser = configparser.ConfigParser(interpolation=None, empty_lines_in_values=False)
  957. parser.read_string(serialized)
  958. return parser["general"].get("name", "")
  959. def _getMaterialLabelFromSerialized(self, serialized):
  960. data = ET.fromstring(serialized)
  961. metadata = data.iterfind("./um:metadata/um:name/um:label", {"um": "http://www.ultimaker.com/material"})
  962. for entry in metadata:
  963. return entry.text