ThreeMFWorkspaceReader.py 68 KB

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