ThreeMFWorkspaceReader.py 64 KB

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