ThreeMFWorkspaceReader.py 52 KB

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