ThreeMFWorkspaceReader.py 56 KB

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