ContainerNode.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Optional
  4. from collections import OrderedDict
  5. from UM.Logger import Logger
  6. from UM.Settings.InstanceContainer import InstanceContainer
  7. ##
  8. # A metadata / container combination. Use getContainer() to get the container corresponding to the metadata.
  9. #
  10. # ContainerNode is a multi-purpose class. It has two main purposes:
  11. # 1. It encapsulates an InstanceContainer. It contains that InstanceContainer's
  12. # - metadata (Always)
  13. # - container (lazy-loaded when needed)
  14. # 2. It also serves as a node in a hierarchical InstanceContainer lookup table/tree.
  15. # This is used in Variant, Material, and Quality Managers.
  16. #
  17. class ContainerNode:
  18. __slots__ = ("metadata", "container", "children_map")
  19. def __init__(self, metadata: Optional[dict] = None):
  20. self.metadata = metadata
  21. self.container = None
  22. self.children_map = OrderedDict()
  23. def getChildNode(self, child_key: str) -> Optional["ContainerNode"]:
  24. return self.children_map.get(child_key)
  25. def getContainer(self) -> "InstanceContainer":
  26. if self.metadata is None:
  27. raise RuntimeError("Cannot get container for a ContainerNode without metadata")
  28. if self.container is None:
  29. container_id = self.metadata["id"]
  30. Logger.log("i", "Lazy-loading container [%s]", container_id)
  31. from UM.Settings.ContainerRegistry import ContainerRegistry
  32. container_list = ContainerRegistry.getInstance().findInstanceContainers(id = container_id)
  33. if not container_list:
  34. raise RuntimeError("Failed to lazy-load container [%s], cannot find it" % container_id)
  35. self.container = container_list[0]
  36. return self.container
  37. def __str__(self) -> str:
  38. return "%s[%s]" % (self.__class__.__name__, self.metadata.get("id"))