ThreeMFWorkspaceReader.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from configparser import ConfigParser
  4. import zipfile
  5. import os
  6. import threading
  7. import xml.etree.ElementTree as ET
  8. from UM.Workspace.WorkspaceReader import WorkspaceReader
  9. from UM.Application import Application
  10. from UM.Logger import Logger
  11. from UM.i18n import i18nCatalog
  12. from UM.Signal import postponeSignals, CompressTechnique
  13. from UM.Settings.ContainerStack import ContainerStack
  14. from UM.Settings.DefinitionContainer import DefinitionContainer
  15. from UM.Settings.InstanceContainer import InstanceContainer
  16. from UM.Settings.ContainerRegistry import ContainerRegistry
  17. from UM.MimeTypeDatabase import MimeTypeDatabase
  18. from UM.Job import Job
  19. from UM.Preferences import Preferences
  20. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  21. from cura.Settings.ExtruderStack import ExtruderStack
  22. from cura.Settings.GlobalStack import GlobalStack
  23. from cura.Settings.CuraContainerStack import _ContainerIndexes
  24. from cura.CuraApplication import CuraApplication
  25. from .WorkspaceDialog import WorkspaceDialog
  26. i18n_catalog = i18nCatalog("cura")
  27. #
  28. # HACK:
  29. #
  30. # In project loading, when override the existing machine is selected, the stacks and containers that are correctly
  31. # active in the system will be overridden at runtime. Because the project loading is done in a different thread than
  32. # the Qt thread, something else can kick in the middle of the process. One of them is the rendering. It will access
  33. # the current stacks and container, which have not completely been updated yet, so Cura will crash in this case.
  34. #
  35. # This "@call_on_qt_thread" decorator makes sure that a function will always be called on the Qt thread (blocking).
  36. # It is applied to the read() function of project loading so it can be guaranteed that only after the project loading
  37. # process is completely done, everything else that needs to occupy the QT thread will be executed.
  38. #
  39. class InterCallObject:
  40. def __init__(self):
  41. self.finish_event = threading.Event()
  42. self.result = None
  43. def call_on_qt_thread(func):
  44. def _call_on_qt_thread_wrapper(*args, **kwargs):
  45. def _handle_call(ico, *args, **kwargs):
  46. ico.result = func(*args, **kwargs)
  47. ico.finish_event.set()
  48. inter_call_object = InterCallObject()
  49. new_args = tuple([inter_call_object] + list(args)[:])
  50. CuraApplication.getInstance().callLater(_handle_call, *new_args, **kwargs)
  51. inter_call_object.finish_event.wait()
  52. return inter_call_object.result
  53. return _call_on_qt_thread_wrapper
  54. class ContainerInfo:
  55. def __init__(self, file_name: str, serialized: str, parser: ConfigParser):
  56. self.file_name = file_name
  57. self.serialized = serialized
  58. self.parser = parser
  59. self.container = None
  60. self.definition_id = None
  61. class QualityChangesInfo:
  62. def __init__(self):
  63. self.name = None
  64. self.global_info = None
  65. self.extruder_info_dict = {}
  66. class MachineInfo:
  67. def __init__(self):
  68. self.container_id = None
  69. self.name = None
  70. self.definition_id = None
  71. self.quality_type = None
  72. self.custom_quality_name = None
  73. self.quality_changes_info = None
  74. self.variant_info = None
  75. self.definition_changes_info = None
  76. self.user_changes_info = None
  77. self.extruder_info_dict = {}
  78. class ExtruderInfo:
  79. def __init__(self):
  80. self.position = None
  81. self.enabled = True
  82. self.variant_info = None
  83. self.root_material_id = None
  84. self.definition_changes_info = None
  85. self.user_changes_info = None
  86. ## Base implementation for reading 3MF workspace files.
  87. class ThreeMFWorkspaceReader(WorkspaceReader):
  88. def __init__(self):
  89. super().__init__()
  90. self._supported_extensions = [".3mf"]
  91. self._dialog = WorkspaceDialog()
  92. self._3mf_mesh_reader = None
  93. self._container_registry = ContainerRegistry.getInstance()
  94. # suffixes registered with the MineTypes don't start with a dot '.'
  95. self._definition_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(DefinitionContainer).preferredSuffix
  96. self._material_container_suffix = None # We have to wait until all other plugins are loaded before we can set it
  97. self._instance_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(InstanceContainer).preferredSuffix
  98. self._container_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ContainerStack).preferredSuffix
  99. self._extruder_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ExtruderStack).preferredSuffix
  100. self._global_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(GlobalStack).preferredSuffix
  101. # Certain instance container types are ignored because we make the assumption that only we make those types
  102. # of containers. They are:
  103. # - quality
  104. # - variant
  105. self._ignored_instance_container_types = {"quality", "variant"}
  106. self._resolve_strategies = {}
  107. self._id_mapping = {}
  108. # In Cura 2.5 and 2.6, the empty profiles used to have those long names
  109. self._old_empty_profile_id_dict = {"empty_%s" % k: "empty" for k in ["material", "variant"]}
  110. self._is_same_machine_type = False
  111. self._old_new_materials = {}
  112. self._materials_to_select = {}
  113. self._machine_info = None
  114. def _clearState(self):
  115. self._is_same_machine_type = False
  116. self._id_mapping = {}
  117. self._old_new_materials = {}
  118. self._materials_to_select = {}
  119. self._machine_info = None
  120. ## Get a unique name based on the old_id. This is different from directly calling the registry in that it caches results.
  121. # This has nothing to do with speed, but with getting consistent new naming for instances & objects.
  122. def getNewId(self, old_id):
  123. if old_id not in self._id_mapping:
  124. self._id_mapping[old_id] = self._container_registry.uniqueName(old_id)
  125. return self._id_mapping[old_id]
  126. ## Separates the given file list into a list of GlobalStack files and a list of ExtruderStack files.
  127. #
  128. # In old versions, extruder stack files have the same suffix as container stack files ".stack.cfg".
  129. #
  130. def _determineGlobalAndExtruderStackFiles(self, project_file_name, file_list):
  131. archive = zipfile.ZipFile(project_file_name, "r")
  132. global_stack_file_list = [name for name in file_list if name.endswith(self._global_stack_suffix)]
  133. extruder_stack_file_list = [name for name in file_list if name.endswith(self._extruder_stack_suffix)]
  134. # separate container stack files and extruder stack files
  135. files_to_determine = [name for name in file_list if name.endswith(self._container_stack_suffix)]
  136. for file_name in files_to_determine:
  137. # FIXME: HACK!
  138. # We need to know the type of the stack file, but we can only know it if we deserialize it.
  139. # The default ContainerStack.deserialize() will connect signals, which is not desired in this case.
  140. # Since we know that the stack files are INI files, so we directly use the ConfigParser to parse them.
  141. serialized = archive.open(file_name).read().decode("utf-8")
  142. stack_config = ConfigParser(interpolation = None)
  143. stack_config.read_string(serialized)
  144. # sanity check
  145. if not stack_config.has_option("metadata", "type"):
  146. Logger.log("e", "%s in %s doesn't seem to be valid stack file", file_name, project_file_name)
  147. continue
  148. stack_type = stack_config.get("metadata", "type")
  149. if stack_type == "extruder_train":
  150. extruder_stack_file_list.append(file_name)
  151. elif stack_type == "machine":
  152. global_stack_file_list.append(file_name)
  153. else:
  154. Logger.log("w", "Unknown container stack type '%s' from %s in %s",
  155. stack_type, file_name, project_file_name)
  156. if len(global_stack_file_list) != 1:
  157. raise RuntimeError("More than one global stack file found: [%s]" % str(global_stack_file_list))
  158. return global_stack_file_list[0], extruder_stack_file_list
  159. ## read some info so we can make decisions
  160. # \param file_name
  161. # \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.
  162. def preRead(self, file_name, show_dialog=True, *args, **kwargs):
  163. self._clearState()
  164. self._3mf_mesh_reader = Application.getInstance().getMeshFileHandler().getReaderForFile(file_name)
  165. if self._3mf_mesh_reader and self._3mf_mesh_reader.preRead(file_name) == WorkspaceReader.PreReadResult.accepted:
  166. pass
  167. else:
  168. Logger.log("w", "Could not find reader that was able to read the scene data for 3MF workspace")
  169. return WorkspaceReader.PreReadResult.failed
  170. self._machine_info = MachineInfo()
  171. machine_type = ""
  172. variant_type_name = i18n_catalog.i18nc("@label", "Nozzle")
  173. # Check if there are any conflicts, so we can ask the user.
  174. archive = zipfile.ZipFile(file_name, "r")
  175. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  176. resolve_strategy_keys = ["machine", "material", "quality_changes"]
  177. self._resolve_strategies = {k: None for k in resolve_strategy_keys}
  178. containers_found_dict = {k: False for k in resolve_strategy_keys}
  179. #
  180. # Read definition containers
  181. #
  182. machine_definition_id = None
  183. machine_definition_container_count = 0
  184. extruder_definition_container_count = 0
  185. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  186. for definition_container_file in definition_container_files:
  187. container_id = self._stripFileToId(definition_container_file)
  188. definitions = self._container_registry.findDefinitionContainersMetadata(id = container_id)
  189. serialized = archive.open(definition_container_file).read().decode("utf-8")
  190. if not definitions:
  191. definition_container = DefinitionContainer.deserializeMetadata(serialized, container_id)[0]
  192. else:
  193. definition_container = definitions[0]
  194. definition_container_type = definition_container.get("type")
  195. if definition_container_type == "machine":
  196. machine_definition_id = container_id
  197. machine_type = definition_container["name"]
  198. variant_type_name = definition_container.get("variants_name", variant_type_name)
  199. machine_definition_container_count += 1
  200. elif definition_container_type == "extruder":
  201. extruder_definition_container_count += 1
  202. else:
  203. Logger.log("w", "Unknown definition container type %s for %s",
  204. definition_container_type, definition_container_file)
  205. Job.yieldThread()
  206. if machine_definition_container_count != 1:
  207. return WorkspaceReader.PreReadResult.failed # Not a workspace file but ordinary 3MF.
  208. material_labels = []
  209. material_conflict = False
  210. xml_material_profile = self._getXmlProfileClass()
  211. reverse_material_id_dict = {}
  212. if self._material_container_suffix is None:
  213. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).preferredSuffix
  214. if xml_material_profile:
  215. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  216. for material_container_file in material_container_files:
  217. container_id = self._stripFileToId(material_container_file)
  218. serialized = archive.open(material_container_file).read().decode("utf-8")
  219. metadata_list = xml_material_profile.deserializeMetadata(serialized, container_id)
  220. reverse_map = {metadata["id"]: container_id for metadata in metadata_list}
  221. reverse_material_id_dict.update(reverse_map)
  222. material_labels.append(self._getMaterialLabelFromSerialized(serialized))
  223. if self._container_registry.findContainersMetadata(id = container_id): #This material already exists.
  224. containers_found_dict["material"] = True
  225. if not self._container_registry.isReadOnly(container_id): # Only non readonly materials can be in conflict
  226. material_conflict = True
  227. Job.yieldThread()
  228. # Check if any quality_changes instance container is in conflict.
  229. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  230. quality_name = ""
  231. custom_quality_name = ""
  232. num_settings_overriden_by_quality_changes = 0 # How many settings are changed by the quality changes
  233. num_user_settings = 0
  234. quality_changes_conflict = False
  235. self._machine_info.quality_changes_info = QualityChangesInfo()
  236. quality_changes_info_list = []
  237. instance_container_info_dict = {} # id -> parser
  238. for instance_container_file_name in instance_container_files:
  239. container_id = self._stripFileToId(instance_container_file_name)
  240. serialized = archive.open(instance_container_file_name).read().decode("utf-8")
  241. # Qualities and variants don't have upgrades, so don't upgrade them
  242. parser = ConfigParser(interpolation = None)
  243. parser.read_string(serialized)
  244. container_type = parser["metadata"]["type"]
  245. if container_type not in ("quality", "variant"):
  246. serialized = InstanceContainer._updateSerialized(serialized, instance_container_file_name)
  247. parser = ConfigParser(interpolation = None)
  248. parser.read_string(serialized)
  249. container_info = ContainerInfo(instance_container_file_name, serialized, parser)
  250. instance_container_info_dict[container_id] = container_info
  251. container_type = parser["metadata"]["type"]
  252. if container_type == "quality_changes":
  253. quality_changes_info_list.append(container_info)
  254. if not parser.has_option("metadata", "position"):
  255. self._machine_info.quality_changes_info.name = parser["general"]["name"]
  256. self._machine_info.quality_changes_info.global_info = container_info
  257. else:
  258. position = parser["metadata"]["position"]
  259. self._machine_info.quality_changes_info.extruder_info_dict[position] = container_info
  260. custom_quality_name = parser["general"]["name"]
  261. values = parser["values"] if parser.has_section("values") else dict()
  262. num_settings_overriden_by_quality_changes += len(values)
  263. # Check if quality changes already exists.
  264. quality_changes = self._container_registry.findInstanceContainers(id = container_id)
  265. if quality_changes:
  266. containers_found_dict["quality_changes"] = True
  267. # Check if there really is a conflict by comparing the values
  268. instance_container = InstanceContainer(container_id)
  269. instance_container.deserialize(serialized, file_name = instance_container_file_name)
  270. if quality_changes[0] != instance_container:
  271. quality_changes_conflict = True
  272. elif container_type == "quality":
  273. if not quality_name:
  274. quality_name = parser["general"]["name"]
  275. elif container_type == "user":
  276. num_user_settings += len(parser["values"])
  277. elif container_type in self._ignored_instance_container_types:
  278. # Ignore certain instance container types
  279. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  280. continue
  281. Job.yieldThread()
  282. if self._machine_info.quality_changes_info.global_info is None:
  283. self._machine_info.quality_changes_info = None
  284. # Load ContainerStack files and ExtruderStack files
  285. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(
  286. file_name, cura_file_names)
  287. machine_conflict = False
  288. # Because there can be cases as follows:
  289. # - the global stack exists but some/all of the extruder stacks DON'T exist
  290. # - the global stack DOESN'T exist but some/all of the extruder stacks exist
  291. # To simplify this, only check if the global stack exists or not
  292. global_stack_id = self._stripFileToId(global_stack_file)
  293. serialized = archive.open(global_stack_file).read().decode("utf-8")
  294. machine_name = self._getMachineNameFromSerializedStack(serialized)
  295. stacks = self._container_registry.findContainerStacks(name = machine_name, type = "machine")
  296. self._is_same_machine_type = True
  297. if stacks:
  298. global_stack = stacks[0]
  299. containers_found_dict["machine"] = True
  300. # Check if there are any changes at all in any of the container stacks.
  301. id_list = self._getContainerIdListFromSerialized(serialized)
  302. for index, container_id in enumerate(id_list):
  303. # take into account the old empty container IDs
  304. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  305. if global_stack.getContainer(index).getId() != container_id:
  306. machine_conflict = True
  307. break
  308. self._is_same_machine_type = global_stack.definition.getId() == machine_definition_id
  309. # Get quality type
  310. parser = ConfigParser(interpolation = None)
  311. parser.read_string(serialized)
  312. quality_container_id = parser["containers"][str(_ContainerIndexes.Quality)]
  313. quality_type = instance_container_info_dict[quality_container_id].parser["metadata"]["quality_type"]
  314. # Get machine info
  315. serialized = archive.open(global_stack_file).read().decode("utf-8")
  316. serialized = GlobalStack._updateSerialized(serialized, global_stack_file)
  317. parser = ConfigParser(interpolation = None)
  318. parser.read_string(serialized)
  319. definition_changes_id = parser["containers"][str(_ContainerIndexes.DefinitionChanges)]
  320. if definition_changes_id not in ("empty", "empty_definition_changes"):
  321. self._machine_info.definition_changes_info = instance_container_info_dict[definition_changes_id]
  322. user_changes_id = parser["containers"][str(_ContainerIndexes.UserChanges)]
  323. if user_changes_id not in ("empty", "empty_user_changes"):
  324. self._machine_info.user_changes_info = instance_container_info_dict[user_changes_id]
  325. # Also check variant and material in case it doesn't have extruder stacks
  326. if not extruder_stack_files:
  327. position = "0"
  328. extruder_info = ExtruderInfo()
  329. extruder_info.position = position
  330. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  331. material_id = parser["containers"][str(_ContainerIndexes.Material)]
  332. if variant_id not in ("empty", "empty_variant"):
  333. extruder_info.variant_info = instance_container_info_dict[variant_id]
  334. if material_id not in ("empty", "empty_material"):
  335. root_material_id = reverse_material_id_dict[material_id]
  336. extruder_info.root_material_id = root_material_id
  337. self._machine_info.extruder_info_dict[position] = extruder_info
  338. else:
  339. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  340. if variant_id not in ("empty", "empty_variant"):
  341. self._machine_info.variant_info = instance_container_info_dict[variant_id]
  342. Job.yieldThread()
  343. # if the global stack is found, we check if there are conflicts in the extruder stacks
  344. for extruder_stack_file in extruder_stack_files:
  345. serialized = archive.open(extruder_stack_file).read().decode("utf-8")
  346. serialized = ExtruderStack._updateSerialized(serialized, extruder_stack_file)
  347. parser = ConfigParser(interpolation = None)
  348. parser.read_string(serialized)
  349. # The check should be done for the extruder stack that's associated with the existing global stack,
  350. # and those extruder stacks may have different IDs.
  351. # So we check according to the positions
  352. position = parser["metadata"]["position"]
  353. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  354. material_id = parser["containers"][str(_ContainerIndexes.Material)]
  355. extruder_info = ExtruderInfo()
  356. extruder_info.position = position
  357. if parser.has_option("metadata", "enabled"):
  358. extruder_info.enabled = parser["metadata"]["enabled"]
  359. if variant_id not in ("empty", "empty_variant"):
  360. extruder_info.variant_info = instance_container_info_dict[variant_id]
  361. if material_id not in ("empty", "empty_material"):
  362. root_material_id = reverse_material_id_dict[material_id]
  363. extruder_info.root_material_id = root_material_id
  364. definition_changes_id = parser["containers"][str(_ContainerIndexes.DefinitionChanges)]
  365. if definition_changes_id not in ("empty", "empty_definition_changes"):
  366. extruder_info.definition_changes_info = instance_container_info_dict[definition_changes_id]
  367. user_changes_id = parser["containers"][str(_ContainerIndexes.UserChanges)]
  368. if user_changes_id not in ("empty", "empty_user_changes"):
  369. extruder_info.user_changes_info = instance_container_info_dict[user_changes_id]
  370. self._machine_info.extruder_info_dict[position] = extruder_info
  371. if not machine_conflict and containers_found_dict["machine"]:
  372. if position not in global_stack.extruders:
  373. continue
  374. existing_extruder_stack = global_stack.extruders[position]
  375. # check if there are any changes at all in any of the container stacks.
  376. id_list = self._getContainerIdListFromSerialized(serialized)
  377. for index, container_id in enumerate(id_list):
  378. # take into account the old empty container IDs
  379. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  380. if existing_extruder_stack.getContainer(index).getId() != container_id:
  381. machine_conflict = True
  382. break
  383. num_visible_settings = 0
  384. try:
  385. temp_preferences = Preferences()
  386. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  387. temp_preferences.deserialize(serialized)
  388. visible_settings_string = temp_preferences.getValue("general/visible_settings")
  389. has_visible_settings_string = visible_settings_string is not None
  390. if visible_settings_string is not None:
  391. num_visible_settings = len(visible_settings_string.split(";"))
  392. active_mode = temp_preferences.getValue("cura/active_mode")
  393. if not active_mode:
  394. active_mode = Preferences.getInstance().getValue("cura/active_mode")
  395. except KeyError:
  396. # If there is no preferences file, it's not a workspace, so notify user of failure.
  397. Logger.log("w", "File %s is not a valid workspace.", file_name)
  398. return WorkspaceReader.PreReadResult.failed
  399. # In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  400. if not show_dialog:
  401. return WorkspaceReader.PreReadResult.accepted
  402. # prepare data for the dialog
  403. num_extruders = extruder_definition_container_count
  404. if num_extruders == 0:
  405. num_extruders = 1 # No extruder stacks found, which means there is one extruder
  406. extruders = num_extruders * [""]
  407. quality_name = custom_quality_name if custom_quality_name else quality_name
  408. self._machine_info.container_id = global_stack_id
  409. self._machine_info.name = machine_name
  410. self._machine_info.definition_id = machine_definition_id
  411. self._machine_info.quality_type = quality_type
  412. self._machine_info.custom_quality_name = quality_name
  413. if machine_conflict and not self._is_same_machine_type:
  414. machine_conflict = False
  415. # Show the dialog, informing the user what is about to happen.
  416. self._dialog.setMachineConflict(machine_conflict)
  417. self._dialog.setQualityChangesConflict(quality_changes_conflict)
  418. self._dialog.setMaterialConflict(material_conflict)
  419. self._dialog.setHasVisibleSettingsField(has_visible_settings_string)
  420. self._dialog.setNumVisibleSettings(num_visible_settings)
  421. self._dialog.setQualityName(quality_name)
  422. self._dialog.setQualityType(quality_type)
  423. self._dialog.setNumSettingsOverridenByQualityChanges(num_settings_overriden_by_quality_changes)
  424. self._dialog.setNumUserSettings(num_user_settings)
  425. self._dialog.setActiveMode(active_mode)
  426. self._dialog.setMachineName(machine_name)
  427. self._dialog.setMaterialLabels(material_labels)
  428. self._dialog.setMachineType(machine_type)
  429. self._dialog.setExtruders(extruders)
  430. self._dialog.setVariantType(variant_type_name)
  431. self._dialog.setHasObjectsOnPlate(Application.getInstance().platformActivity)
  432. self._dialog.show()
  433. # Block until the dialog is closed.
  434. self._dialog.waitForClose()
  435. if self._dialog.getResult() == {}:
  436. return WorkspaceReader.PreReadResult.cancelled
  437. self._resolve_strategies = self._dialog.getResult()
  438. #
  439. # There can be 3 resolve strategies coming from the dialog:
  440. # - new: create a new container
  441. # - override: override the existing container
  442. # - None: There is no conflict, which means containers with the same IDs may or may not be there already.
  443. # If there is an existing container, there is no conflict between them, and default to "override"
  444. # If there is no existing container, default to "new"
  445. #
  446. # Default values
  447. for key, strategy in self._resolve_strategies.items():
  448. if key not in containers_found_dict or strategy is not None:
  449. continue
  450. self._resolve_strategies[key] = "override" if containers_found_dict[key] else "new"
  451. return WorkspaceReader.PreReadResult.accepted
  452. ## Overrides an ExtruderStack in the given GlobalStack and returns the new ExtruderStack.
  453. def _overrideExtruderStack(self, global_stack, extruder_file_content, extruder_stack_file):
  454. # Get extruder position first
  455. extruder_config = ConfigParser(interpolation = None)
  456. extruder_config.read_string(extruder_file_content)
  457. if not extruder_config.has_option("metadata", "position"):
  458. msg = "Could not find 'metadata/position' in extruder stack file"
  459. Logger.log("e", "Could not find 'metadata/position' in extruder stack file")
  460. raise RuntimeError(msg)
  461. extruder_position = extruder_config.get("metadata", "position")
  462. try:
  463. extruder_stack = global_stack.extruders[extruder_position]
  464. except KeyError:
  465. Logger.log("w", "Could not find the matching extruder stack to override for position %s", extruder_position)
  466. return None
  467. # Override the given extruder stack
  468. extruder_stack.deserialize(extruder_file_content, file_name = extruder_stack_file)
  469. # return the new ExtruderStack
  470. return extruder_stack
  471. ## Read the project file
  472. # Add all the definitions / materials / quality changes that do not exist yet. Then it loads
  473. # all the stacks into the container registry. In some cases it will reuse the container for the global stack.
  474. # It handles old style project files containing .stack.cfg as well as new style project files
  475. # containing global.cfg / extruder.cfg
  476. #
  477. # \param file_name
  478. @call_on_qt_thread
  479. def read(self, file_name):
  480. container_registry = ContainerRegistry.getInstance()
  481. signals = [container_registry.containerAdded,
  482. container_registry.containerRemoved,
  483. container_registry.containerMetaDataChanged]
  484. #
  485. # We now have different managers updating their lookup tables upon container changes. It is critical to make
  486. # sure that the managers have a complete set of data when they update.
  487. #
  488. # In project loading, lots of the container-related signals are loosely emitted, which can create timing gaps
  489. # for incomplete data update or other kinds of issues to happen.
  490. #
  491. # To avoid this, we postpone all signals so they don't get emitted immediately. But, please also be aware that,
  492. # because of this, do not expect to have the latest data in the lookup tables in project loading.
  493. #
  494. with postponeSignals(*signals, compress = CompressTechnique.NoCompression):
  495. return self._read(file_name)
  496. def _read(self, file_name):
  497. application = CuraApplication.getInstance()
  498. material_manager = application.getMaterialManager()
  499. archive = zipfile.ZipFile(file_name, "r")
  500. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  501. # Create a shadow copy of the preferences (we don't want all of the preferences, but we do want to re-use its
  502. # parsing code.
  503. temp_preferences = Preferences()
  504. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  505. temp_preferences.deserialize(serialized)
  506. # Copy a number of settings from the temp preferences to the global
  507. global_preferences = Preferences.getInstance()
  508. visible_settings = temp_preferences.getValue("general/visible_settings")
  509. if visible_settings is None:
  510. Logger.log("w", "Workspace did not contain visible settings. Leaving visibility unchanged")
  511. else:
  512. global_preferences.setValue("general/visible_settings", visible_settings)
  513. global_preferences.setValue("cura/active_setting_visibility_preset", "custom")
  514. categories_expanded = temp_preferences.getValue("cura/categories_expanded")
  515. if categories_expanded is None:
  516. Logger.log("w", "Workspace did not contain expanded categories. Leaving them unchanged")
  517. else:
  518. global_preferences.setValue("cura/categories_expanded", categories_expanded)
  519. application.expandedCategoriesChanged.emit() # Notify the GUI of the change
  520. # If a machine with the same name is of a different type, always create a new one.
  521. if not self._is_same_machine_type or self._resolve_strategies["machine"] != "override":
  522. # We need to create a new machine
  523. machine_name = self._container_registry.uniqueName(self._machine_info.name)
  524. global_stack = CuraStackBuilder.createMachine(machine_name, self._machine_info.definition_id)
  525. extruder_stack_dict = global_stack.extruders
  526. self._container_registry.addContainer(global_stack)
  527. else:
  528. # Find the machine
  529. global_stack = self._container_registry.findContainerStacks(name = self._machine_info.name, type = "machine")[0]
  530. extruder_stacks = self._container_registry.findContainerStacks(machine = global_stack.getId(),
  531. type = "extruder_train")
  532. extruder_stack_dict = {stack.getMetaDataEntry("position"): stack for stack in extruder_stacks}
  533. Logger.log("d", "Workspace loading is checking definitions...")
  534. # Get all the definition files & check if they exist. If not, add them.
  535. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  536. for definition_container_file in definition_container_files:
  537. container_id = self._stripFileToId(definition_container_file)
  538. definitions = self._container_registry.findDefinitionContainersMetadata(id = container_id)
  539. if not definitions:
  540. definition_container = DefinitionContainer(container_id)
  541. definition_container.deserialize(archive.open(definition_container_file).read().decode("utf-8"),
  542. file_name = definition_container_file)
  543. self._container_registry.addContainer(definition_container)
  544. Job.yieldThread()
  545. Logger.log("d", "Workspace loading is checking materials...")
  546. # Get all the material files and check if they exist. If not, add them.
  547. xml_material_profile = self._getXmlProfileClass()
  548. if self._material_container_suffix is None:
  549. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).suffixes[0]
  550. if xml_material_profile:
  551. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  552. for material_container_file in material_container_files:
  553. to_deserialize_material = False
  554. container_id = self._stripFileToId(material_container_file)
  555. need_new_name = False
  556. materials = self._container_registry.findInstanceContainers(id = container_id)
  557. if not materials:
  558. # No material found, deserialize this material later and add it
  559. to_deserialize_material = True
  560. else:
  561. material_container = materials[0]
  562. old_material_root_id = material_container.getMetaDataEntry("base_file")
  563. if not self._container_registry.isReadOnly(old_material_root_id): # Only create new materials if they are not read only.
  564. to_deserialize_material = True
  565. if self._resolve_strategies["material"] == "override":
  566. # Remove the old materials and then deserialize the one from the project
  567. root_material_id = material_container.getMetaDataEntry("base_file")
  568. material_manager.removeMaterialByRootId(root_material_id)
  569. elif self._resolve_strategies["material"] == "new":
  570. # Note that we *must* deserialize it with a new ID, as multiple containers will be
  571. # auto created & added.
  572. container_id = self.getNewId(container_id)
  573. self._old_new_materials[old_material_root_id] = container_id
  574. need_new_name = True
  575. if to_deserialize_material:
  576. material_container = xml_material_profile(container_id)
  577. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"),
  578. file_name = container_id + "." + self._material_container_suffix)
  579. if need_new_name:
  580. new_name = ContainerRegistry.getInstance().uniqueName(material_container.getName())
  581. material_container.setName(new_name)
  582. material_container.setDirty(True)
  583. self._container_registry.addContainer(material_container)
  584. Job.yieldThread()
  585. # Handle quality changes if any
  586. self._processQualityChanges(global_stack)
  587. # Prepare the machine
  588. self._applyChangesToMachine(global_stack, extruder_stack_dict)
  589. Logger.log("d", "Workspace loading is notifying rest of the code of changes...")
  590. # Actually change the active machine.
  591. #
  592. # This is scheduled for later is because it depends on the Variant/Material/Qualitiy Managers to have the latest
  593. # data, but those managers will only update upon a container/container metadata changed signal. Because this
  594. # function is running on the main thread (Qt thread), although those "changed" signals have been emitted, but
  595. # they won't take effect until this function is done.
  596. # To solve this, we schedule _updateActiveMachine() for later so it will have the latest data.
  597. self._updateActiveMachine(global_stack)
  598. # Load all the nodes / meshdata of the workspace
  599. nodes = self._3mf_mesh_reader.read(file_name)
  600. if nodes is None:
  601. nodes = []
  602. base_file_name = os.path.basename(file_name)
  603. if base_file_name.endswith(".curaproject.3mf"):
  604. base_file_name = base_file_name[:base_file_name.rfind(".curaproject.3mf")]
  605. self.setWorkspaceName(base_file_name)
  606. return nodes
  607. def _processQualityChanges(self, global_stack):
  608. if self._machine_info.quality_changes_info is None:
  609. return
  610. application = CuraApplication.getInstance()
  611. quality_manager = application.getQualityManager()
  612. # If we have custom profiles, load them
  613. quality_changes_name = self._machine_info.quality_changes_info.name
  614. if self._machine_info.quality_changes_info is not None:
  615. Logger.log("i", "Loading custom profile [%s] from project file",
  616. self._machine_info.quality_changes_info.name)
  617. # Get the correct extruder definition IDs for quality changes
  618. from cura.Machines.QualityManager import getMachineDefinitionIDForQualitySearch
  619. machine_definition_id_for_quality = getMachineDefinitionIDForQualitySearch(global_stack.definition)
  620. machine_definition_for_quality = self._container_registry.findDefinitionContainers(id = machine_definition_id_for_quality)[0]
  621. quality_changes_info = self._machine_info.quality_changes_info
  622. quality_changes_quality_type = quality_changes_info.global_info.parser["metadata"]["quality_type"]
  623. quality_changes_name = quality_changes_info.name
  624. create_new = self._resolve_strategies.get("quality_changes") != "override"
  625. if create_new:
  626. container_info_dict = {None: self._machine_info.quality_changes_info.global_info}
  627. container_info_dict.update(quality_changes_info.extruder_info_dict)
  628. quality_changes_name = self._container_registry.uniqueName(quality_changes_name)
  629. for position, container_info in container_info_dict.items():
  630. extruder_stack = None
  631. if position is not None:
  632. extruder_stack = global_stack.extruders[position]
  633. container = quality_manager._createQualityChanges(quality_changes_quality_type,
  634. quality_changes_name,
  635. global_stack, extruder_stack)
  636. container_info.container = container
  637. container.setDirty(True)
  638. self._container_registry.addContainer(container)
  639. Logger.log("d", "Created new quality changes container [%s]", container.getId())
  640. else:
  641. # Find the existing containers
  642. quality_changes_containers = self._container_registry.findInstanceContainers(name = quality_changes_name,
  643. type = "quality_changes")
  644. for container in quality_changes_containers:
  645. extruder_position = container.getMetaDataEntry("position")
  646. if extruder_position is None:
  647. quality_changes_info.global_info.container = container
  648. else:
  649. if extruder_position not in quality_changes_info.extruder_info_dict:
  650. quality_changes_info.extruder_info_dict[extruder_position] = ContainerInfo(None, None, None)
  651. container_info = quality_changes_info.extruder_info_dict[extruder_position]
  652. container_info.container = container
  653. # If there is no quality changes for any extruder, create one.
  654. if not quality_changes_info.extruder_info_dict:
  655. container_info = ContainerInfo(None, None, None)
  656. quality_changes_info.extruder_info_dict["0"] = container_info
  657. extruder_stack = global_stack.extruders["0"]
  658. container = quality_manager._createQualityChanges(quality_changes_quality_type, quality_changes_name,
  659. global_stack, extruder_stack)
  660. container_info.container = container
  661. container.setDirty(True)
  662. self._container_registry.addContainer(container)
  663. Logger.log("d", "Created new quality changes container [%s]", container.getId())
  664. # Clear all existing containers
  665. quality_changes_info.global_info.container.clear()
  666. for container_info in quality_changes_info.extruder_info_dict.values():
  667. container_info.container.clear()
  668. # Loop over everything and override the existing containers
  669. global_info = quality_changes_info.global_info
  670. global_info.container.clear() # Clear all
  671. for key, value in global_info.parser["values"].items():
  672. if not machine_definition_for_quality.getProperty(key, "settable_per_extruder"):
  673. global_info.container.setProperty(key, "value", value)
  674. else:
  675. quality_changes_info.extruder_info_dict["0"].container.setProperty(key, "value", value)
  676. for position, container_info in quality_changes_info.extruder_info_dict.items():
  677. if container_info.parser is None:
  678. continue
  679. if container_info.container is None:
  680. extruder_stack = global_stack.extruders[position]
  681. container = quality_manager._createQualityChanges(quality_changes_quality_type, quality_changes_name,
  682. global_stack, extruder_stack)
  683. container_info.container = container
  684. for key, value in container_info.parser["values"].items():
  685. container_info.container.setProperty(key, "value", value)
  686. self._machine_info.quality_changes_info.name = quality_changes_name
  687. def _clearStack(self, stack):
  688. application = CuraApplication.getInstance()
  689. stack.definitionChanges.clear()
  690. stack.variant = application.empty_variant_container
  691. stack.material = application.empty_material_container
  692. stack.quality = application.empty_quality_container
  693. stack.qualityChanges = application.empty_quality_changes_container
  694. stack.userChanges.clear()
  695. def _applyDefinitionChanges(self, global_stack, extruder_stack_dict):
  696. values_to_set_for_extruders = {}
  697. if self._machine_info.definition_changes_info is not None:
  698. parser = self._machine_info.definition_changes_info.parser
  699. for key, value in parser["values"].items():
  700. if global_stack.getProperty(key, "settable_per_extruder"):
  701. values_to_set_for_extruders[key] = value
  702. else:
  703. global_stack.definitionChanges.setProperty(key, "value", value)
  704. for position, extruder_stack in extruder_stack_dict.items():
  705. if position not in self._machine_info.extruder_info_dict:
  706. continue
  707. extruder_info = self._machine_info.extruder_info_dict[position]
  708. if extruder_info.definition_changes_info is None:
  709. continue
  710. parser = extruder_info.definition_changes_info.parser
  711. for key, value in values_to_set_for_extruders.items():
  712. extruder_stack.definitionChanges.setProperty(key, "value", value)
  713. if parser is not None:
  714. for key, value in parser["values"].items():
  715. extruder_stack.definitionChanges.setProperty(key, "value", value)
  716. def _applyUserChanges(self, global_stack, extruder_stack_dict):
  717. values_to_set_for_extruder_0 = {}
  718. if self._machine_info.user_changes_info is not None:
  719. parser = self._machine_info.user_changes_info.parser
  720. for key, value in parser["values"].items():
  721. if global_stack.getProperty(key, "settable_per_extruder"):
  722. values_to_set_for_extruder_0[key] = value
  723. else:
  724. global_stack.userChanges.setProperty(key, "value", value)
  725. for position, extruder_stack in extruder_stack_dict.items():
  726. if position not in self._machine_info.extruder_info_dict:
  727. continue
  728. extruder_info = self._machine_info.extruder_info_dict[position]
  729. if extruder_info.user_changes_info is not None:
  730. parser = self._machine_info.extruder_info_dict[position].user_changes_info.parser
  731. if position == "0":
  732. for key, value in values_to_set_for_extruder_0.items():
  733. extruder_stack.userChanges.setProperty(key, "value", value)
  734. if parser is not None:
  735. for key, value in parser["values"].items():
  736. extruder_stack.userChanges.setProperty(key, "value", value)
  737. def _applyVariants(self, global_stack, extruder_stack_dict):
  738. application = CuraApplication.getInstance()
  739. variant_manager = application.getVariantManager()
  740. if self._machine_info.variant_info is not None:
  741. parser = self._machine_info.variant_info.parser
  742. variant_name = parser["general"]["name"]
  743. from cura.Machines.VariantManager import VariantType
  744. variant_type = VariantType.BUILD_PLATE
  745. node = variant_manager.getVariantNode(global_stack.definition.getId(), variant_name, variant_type)
  746. if node is not None:
  747. global_stack.variant = node.getContainer()
  748. for position, extruder_stack in extruder_stack_dict.items():
  749. if position not in self._machine_info.extruder_info_dict:
  750. continue
  751. extruder_info = self._machine_info.extruder_info_dict[position]
  752. if extruder_info.variant_info is None:
  753. continue
  754. parser = extruder_info.variant_info.parser
  755. variant_name = parser["general"]["name"]
  756. from cura.Machines.VariantManager import VariantType
  757. variant_type = VariantType.NOZZLE
  758. node = variant_manager.getVariantNode(global_stack.definition.getId(), variant_name, variant_type)
  759. if node is not None:
  760. extruder_stack.variant = node.getContainer()
  761. def _applyMaterials(self, global_stack, extruder_stack_dict):
  762. application = CuraApplication.getInstance()
  763. material_manager = application.getMaterialManager()
  764. # Force update lookup tables first
  765. material_manager.initialize()
  766. for position, extruder_stack in extruder_stack_dict.items():
  767. if position not in self._machine_info.extruder_info_dict:
  768. continue
  769. extruder_info = self._machine_info.extruder_info_dict[position]
  770. if extruder_info.root_material_id is None:
  771. continue
  772. root_material_id = extruder_info.root_material_id
  773. root_material_id = self._old_new_materials.get(root_material_id, root_material_id)
  774. # get material diameter of this extruder
  775. machine_material_diameter = extruder_stack.materialDiameter
  776. material_node = material_manager.getMaterialNode(global_stack.definition.getId(),
  777. extruder_stack.variant.getName(),
  778. machine_material_diameter,
  779. root_material_id)
  780. if material_node is not None:
  781. extruder_stack.material = material_node.getContainer()
  782. def _applyChangesToMachine(self, global_stack, extruder_stack_dict):
  783. # Clear all first
  784. self._clearStack(global_stack)
  785. for extruder_stack in extruder_stack_dict.values():
  786. self._clearStack(extruder_stack)
  787. self._applyDefinitionChanges(global_stack, extruder_stack_dict)
  788. self._applyUserChanges(global_stack, extruder_stack_dict)
  789. self._applyVariants(global_stack, extruder_stack_dict)
  790. self._applyMaterials(global_stack, extruder_stack_dict)
  791. # prepare the quality to select
  792. self._quality_changes_to_apply = None
  793. self._quality_type_to_apply = None
  794. if self._machine_info.quality_changes_info is not None:
  795. self._quality_changes_to_apply = self._machine_info.quality_changes_info.name
  796. else:
  797. self._quality_type_to_apply = self._machine_info.quality_type
  798. # Set enabled/disabled for extruders
  799. for position, extruder_stack in extruder_stack_dict.items():
  800. extruder_info = self._machine_info.extruder_info_dict.get(position)
  801. if not extruder_info:
  802. continue
  803. if "enabled" not in extruder_stack.getMetaData():
  804. extruder_stack.addMetaDataEntry("enabled", "True")
  805. extruder_stack.setMetaDataEntry("enabled", str(extruder_info.enabled))
  806. def _updateActiveMachine(self, global_stack):
  807. # Actually change the active machine.
  808. machine_manager = Application.getInstance().getMachineManager()
  809. material_manager = Application.getInstance().getMaterialManager()
  810. quality_manager = Application.getInstance().getQualityManager()
  811. # Force update the lookup maps first
  812. material_manager.initialize()
  813. quality_manager.initialize()
  814. machine_manager.setActiveMachine(global_stack.getId())
  815. if self._quality_changes_to_apply:
  816. quality_changes_group_dict = quality_manager.getQualityChangesGroups(global_stack)
  817. if self._quality_changes_to_apply not in quality_changes_group_dict:
  818. Logger.log("e", "Could not find quality_changes [%s]", self._quality_changes_to_apply)
  819. return
  820. quality_changes_group = quality_changes_group_dict[self._quality_changes_to_apply]
  821. machine_manager.setQualityChangesGroup(quality_changes_group, no_dialog = True)
  822. else:
  823. self._quality_type_to_apply = self._quality_type_to_apply.lower()
  824. quality_group_dict = quality_manager.getQualityGroups(global_stack)
  825. if self._quality_type_to_apply in quality_group_dict:
  826. quality_group = quality_group_dict[self._quality_type_to_apply]
  827. else:
  828. Logger.log("i", "Could not find quality type [%s], switch to default", self._quality_type_to_apply)
  829. preferred_quality_type = global_stack.getMetaDataEntry("preferred_quality_type")
  830. quality_group_dict = quality_manager.getQualityGroups(global_stack)
  831. quality_group = quality_group_dict.get(preferred_quality_type)
  832. if quality_group is None:
  833. Logger.log("e", "Could not get preferred quality type [%s]", preferred_quality_type)
  834. if quality_group is not None:
  835. machine_manager.setQualityGroup(quality_group, no_dialog = True)
  836. # Notify everything/one that is to notify about changes.
  837. global_stack.containersChanged.emit(global_stack.getTop())
  838. def _stripFileToId(self, file):
  839. mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
  840. file = mime_type.stripExtension(file)
  841. return file.replace("Cura/", "")
  842. def _getXmlProfileClass(self):
  843. return self._container_registry.getContainerForMimeType(MimeTypeDatabase.getMimeType("application/x-ultimaker-material-profile"))
  844. ## Get the list of ID's of all containers in a container stack by partially parsing it's serialized data.
  845. def _getContainerIdListFromSerialized(self, serialized):
  846. parser = ConfigParser(interpolation=None, empty_lines_in_values=False)
  847. parser.read_string(serialized)
  848. container_ids = []
  849. if "containers" in parser:
  850. for index, container_id in parser.items("containers"):
  851. container_ids.append(container_id)
  852. elif parser.has_option("general", "containers"):
  853. container_string = parser["general"].get("containers", "")
  854. container_list = container_string.split(",")
  855. container_ids = [container_id for container_id in container_list if container_id != ""]
  856. # HACK: there used to be 6 containers numbering from 0 to 5 in a stack,
  857. # now we have 7: index 5 becomes "definition_changes"
  858. if len(container_ids) == 6:
  859. # Hack; We used to not save the definition changes. Fix this.
  860. container_ids.insert(5, "empty")
  861. return container_ids
  862. def _getMachineNameFromSerializedStack(self, serialized):
  863. parser = ConfigParser(interpolation=None, empty_lines_in_values=False)
  864. parser.read_string(serialized)
  865. return parser["general"].get("name", "")
  866. def _getMaterialLabelFromSerialized(self, serialized):
  867. data = ET.fromstring(serialized)
  868. metadata = data.iterfind("./um:metadata/um:name/um:label", {"um": "http://www.ultimaker.com/material"})
  869. for entry in metadata:
  870. return entry.text