ContainerTree.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Job import Job # For our background task of loading MachineNodes lazily.
  4. from UM.JobQueue import JobQueue # For our background task of loading MachineNodes lazily.
  5. from UM.Logger import Logger
  6. from UM.Settings.ContainerRegistry import ContainerRegistry # To listen to containers being added.
  7. from UM.Signal import Signal
  8. import cura.CuraApplication # Imported like this to prevent circular dependencies.
  9. from cura.Machines.MachineNode import MachineNode
  10. from cura.Settings.GlobalStack import GlobalStack # To listen only to global stacks being added.
  11. from typing import Dict, List, Optional, TYPE_CHECKING
  12. import time
  13. if TYPE_CHECKING:
  14. from cura.Machines.QualityGroup import QualityGroup
  15. from cura.Machines.QualityChangesGroup import QualityChangesGroup
  16. from UM.Settings.ContainerStack import ContainerStack
  17. class ContainerTree:
  18. """This class contains a look-up tree for which containers are available at which stages of configuration.
  19. The tree starts at the machine definitions. For every distinct definition there will be one machine node here.
  20. All of the fallbacks for material choices, quality choices, etc. should be encoded in this tree. There must
  21. always be at least one child node (for nodes that have children) but that child node may be a node representing
  22. the empty instance container.
  23. """
  24. __instance = None # type: Optional["ContainerTree"]
  25. @classmethod
  26. def getInstance(cls):
  27. if cls.__instance is None:
  28. cls.__instance = ContainerTree()
  29. return cls.__instance
  30. def __init__(self) -> None:
  31. self.machines = self._MachineNodeMap() # Mapping from definition ID to machine nodes with lazy loading.
  32. self.materialsChanged = Signal() # Emitted when any of the material nodes in the tree got changed.
  33. cura.CuraApplication.CuraApplication.getInstance().initializationFinished.connect(self._onStartupFinished) # Start the background task to load more machine nodes after start-up is completed.
  34. def getCurrentQualityGroups(self) -> Dict[str, "QualityGroup"]:
  35. """Get the quality groups available for the currently activated printer.
  36. This contains all quality groups, enabled or disabled. To check whether the quality group can be activated,
  37. test for the ``QualityGroup.is_available`` property.
  38. :return: For every quality type, one quality group.
  39. """
  40. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  41. if global_stack is None:
  42. return {}
  43. variant_names = [extruder.variant.getName() for extruder in global_stack.extruderList]
  44. material_bases = [extruder.material.getMetaDataEntry("base_file") for extruder in global_stack.extruderList]
  45. extruder_enabled = [extruder.isEnabled for extruder in global_stack.extruderList]
  46. return self.machines[global_stack.definition.getId()].getQualityGroups(variant_names, material_bases, extruder_enabled)
  47. def getCurrentQualityChangesGroups(self) -> List["QualityChangesGroup"]:
  48. """Get the quality changes groups available for the currently activated printer.
  49. This contains all quality changes groups, enabled or disabled. To check whether the quality changes group can
  50. be activated, test for the ``QualityChangesGroup.is_available`` property.
  51. :return: A list of all quality changes groups.
  52. """
  53. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  54. if global_stack is None:
  55. return []
  56. variant_names = [extruder.variant.getName() for extruder in global_stack.extruderList]
  57. material_bases = [extruder.material.getMetaDataEntry("base_file") for extruder in global_stack.extruderList]
  58. extruder_enabled = [extruder.isEnabled for extruder in global_stack.extruderList]
  59. return self.machines[global_stack.definition.getId()].getQualityChangesGroups(variant_names, material_bases, extruder_enabled)
  60. def _onStartupFinished(self) -> None:
  61. """Ran after completely starting up the application."""
  62. currently_added = ContainerRegistry.getInstance().findContainerStacks() # Find all currently added global stacks.
  63. JobQueue.getInstance().add(self._MachineNodeLoadJob(self, currently_added))
  64. class _MachineNodeMap:
  65. """Dictionary-like object that contains the machines.
  66. This handles the lazy loading of MachineNodes.
  67. """
  68. def __init__(self) -> None:
  69. self._machines = {} # type: Dict[str, MachineNode]
  70. def __contains__(self, definition_id: str) -> bool:
  71. """Returns whether a printer with a certain definition ID exists.
  72. This is regardless of whether or not the printer is loaded yet.
  73. :param definition_id: The definition to look for.
  74. :return: Whether or not a printer definition exists with that name.
  75. """
  76. return len(ContainerRegistry.getInstance().findContainersMetadata(id = definition_id)) > 0
  77. def __getitem__(self, definition_id: str) -> MachineNode:
  78. """Returns a machine node for the specified definition ID.
  79. If the machine node wasn't loaded yet, this will load it lazily.
  80. :param definition_id: The definition to look for.
  81. :return: A machine node for that definition.
  82. """
  83. if definition_id not in self._machines:
  84. start_time = time.time()
  85. self._machines[definition_id] = MachineNode(definition_id)
  86. self._machines[definition_id].materialsChanged.connect(ContainerTree.getInstance().materialsChanged)
  87. Logger.log("d", "Adding container tree for {definition_id} took {duration} seconds.".format(definition_id = definition_id, duration = time.time() - start_time))
  88. return self._machines[definition_id]
  89. def get(self, definition_id: str, default: Optional[MachineNode] = None) -> Optional[MachineNode]:
  90. """Gets a machine node for the specified definition ID, with default.
  91. The default is returned if there is no definition with the specified ID. If the machine node wasn't
  92. loaded yet, this will load it lazily.
  93. :param definition_id: The definition to look for.
  94. :param default: The machine node to return if there is no machine with that definition (can be ``None``
  95. optionally or if not provided).
  96. :return: A machine node for that definition, or the default if there is no definition with the provided
  97. definition_id.
  98. """
  99. if definition_id not in self:
  100. return default
  101. return self[definition_id]
  102. def is_loaded(self, definition_id: str) -> bool:
  103. """Returns whether we've already cached this definition's node.
  104. :param definition_id: The definition that we may have cached.
  105. :return: ``True`` if it's cached.
  106. """
  107. return definition_id in self._machines
  108. class _MachineNodeLoadJob(Job):
  109. """Pre-loads all currently added printers as a background task so that switching printers in the interface is
  110. faster.
  111. """
  112. def __init__(self, tree_root: "ContainerTree", container_stacks: List["ContainerStack"]) -> None:
  113. """Creates a new background task.
  114. :param tree_root: The container tree instance. This cannot be obtained through the singleton static
  115. function since the instance may not yet be constructed completely.
  116. :param container_stacks: All of the stacks to pre-load the container trees for. This needs to be provided
  117. from here because the stacks need to be constructed on the main thread because they are QObject.
  118. """
  119. self.tree_root = tree_root
  120. self.container_stacks = container_stacks
  121. super().__init__()
  122. def run(self) -> None:
  123. """Starts the background task.
  124. The ``JobQueue`` will schedule this on a different thread.
  125. """
  126. Logger.log("d", "Started background loading of MachineNodes")
  127. for stack in self.container_stacks: # Load all currently-added containers.
  128. if not isinstance(stack, GlobalStack):
  129. continue
  130. # Allow a thread switch after every container.
  131. # Experimentally, sleep(0) didn't allow switching. sleep(0.1) or sleep(0.2) neither.
  132. # We're in no hurry though. Half a second is fine.
  133. time.sleep(0.5)
  134. definition_id = stack.definition.getId()
  135. if not self.tree_root.machines.is_loaded(definition_id):
  136. _ = self.tree_root.machines[definition_id]
  137. Logger.log("d", "All MachineNode loading completed")