GlobalStack.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from collections import defaultdict
  4. import threading
  5. from typing import Any, Dict, Optional
  6. from PyQt5.QtCore import pyqtProperty
  7. from UM.Application import Application
  8. from UM.Decorators import override
  9. from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase
  10. from UM.Settings.ContainerStack import ContainerStack
  11. from UM.Settings.SettingInstance import InstanceState
  12. from UM.Settings.ContainerRegistry import ContainerRegistry
  13. from UM.Settings.Interfaces import PropertyEvaluationContext
  14. from UM.Logger import Logger
  15. from . import Exceptions
  16. from .CuraContainerStack import CuraContainerStack
  17. ## Represents the Global or Machine stack and its related containers.
  18. #
  19. class GlobalStack(CuraContainerStack):
  20. def __init__(self, container_id: str, *args, **kwargs):
  21. super().__init__(container_id, *args, **kwargs)
  22. self.addMetaDataEntry("type", "machine") # For backward compatibility
  23. self._extruders = {} # type: Dict[str, "ExtruderStack"]
  24. # This property is used to track which settings we are calculating the "resolve" for
  25. # and if so, to bypass the resolve to prevent an infinite recursion that would occur
  26. # if the resolve function tried to access the same property it is a resolve for.
  27. # Per thread we have our own resolving_settings, or strange things sometimes occur.
  28. self._resolving_settings = defaultdict(set) # keys are thread names
  29. ## Get the list of extruders of this stack.
  30. #
  31. # \return The extruders registered with this stack.
  32. @pyqtProperty("QVariantMap")
  33. def extruders(self) -> Dict[str, "ExtruderStack"]:
  34. return self._extruders
  35. @classmethod
  36. def getLoadingPriority(cls) -> int:
  37. return 2
  38. @classmethod
  39. def getConfigurationTypeFromSerialized(cls, serialized: str) -> Optional[str]:
  40. configuration_type = super().getConfigurationTypeFromSerialized(serialized)
  41. if configuration_type == "machine":
  42. return "machine_stack"
  43. return configuration_type
  44. ## Add an extruder to the list of extruders of this stack.
  45. #
  46. # \param extruder The extruder to add.
  47. #
  48. # \throws Exceptions.TooManyExtrudersError Raised when trying to add an extruder while we
  49. # already have the maximum number of extruders.
  50. def addExtruder(self, extruder: ContainerStack) -> None:
  51. position = extruder.getMetaDataEntry("position")
  52. if position is None:
  53. Logger.log("w", "No position defined for extruder {extruder}, cannot add it to stack {stack}", extruder = extruder.id, stack = self.id)
  54. return
  55. if any(item.getId() == extruder.id for item in self._extruders.values()):
  56. Logger.log("w", "Extruder [%s] has already been added to this stack [%s]", extruder.id, self.getId())
  57. return
  58. self._extruders[position] = extruder
  59. Logger.log("i", "Extruder[%s] added to [%s] at position [%s]", extruder.id, self.id, position)
  60. ## Overridden from ContainerStack
  61. #
  62. # This will return the value of the specified property for the specified setting,
  63. # unless the property is "value" and that setting has a "resolve" function set.
  64. # When a resolve is set, it will instead try and execute the resolve first and
  65. # then fall back to the normal "value" property.
  66. #
  67. # \param key The setting key to get the property of.
  68. # \param property_name The property to get the value of.
  69. #
  70. # \return The value of the property for the specified setting, or None if not found.
  71. @override(ContainerStack)
  72. def getProperty(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> Any:
  73. if not self.definition.findDefinitions(key = key):
  74. return None
  75. if context is None:
  76. context = PropertyEvaluationContext()
  77. context.pushContainer(self)
  78. # Handle the "resolve" property.
  79. if self._shouldResolve(key, property_name, context):
  80. current_thread = threading.current_thread()
  81. self._resolving_settings[current_thread.name].add(key)
  82. resolve = super().getProperty(key, "resolve", context)
  83. self._resolving_settings[current_thread.name].remove(key)
  84. if resolve is not None:
  85. return resolve
  86. # Handle the "limit_to_extruder" property.
  87. limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
  88. if limit_to_extruder is not None:
  89. if limit_to_extruder == -1:
  90. limit_to_extruder = int(Application.getInstance().getMachineManager().defaultExtruderPosition)
  91. limit_to_extruder = str(limit_to_extruder)
  92. if limit_to_extruder is not None and limit_to_extruder != "-1" and limit_to_extruder in self._extruders:
  93. if super().getProperty(key, "settable_per_extruder", context):
  94. result = self._extruders[str(limit_to_extruder)].getProperty(key, property_name, context)
  95. if result is not None:
  96. context.popContainer()
  97. return result
  98. else:
  99. Logger.log("e", "Setting {setting} has limit_to_extruder but is not settable per extruder!", setting = key)
  100. result = super().getProperty(key, property_name, context)
  101. context.popContainer()
  102. return result
  103. ## Overridden from ContainerStack
  104. #
  105. # This will simply raise an exception since the Global stack cannot have a next stack.
  106. @override(ContainerStack)
  107. def setNextStack(self, next_stack: ContainerStack) -> None:
  108. raise Exceptions.InvalidOperationError("Global stack cannot have a next stack!")
  109. # protected:
  110. # Determine whether or not we should try to get the "resolve" property instead of the
  111. # requested property.
  112. def _shouldResolve(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> bool:
  113. if property_name is not "value":
  114. # Do not try to resolve anything but the "value" property
  115. return False
  116. current_thread = threading.current_thread()
  117. if key in self._resolving_settings[current_thread.name]:
  118. # To prevent infinite recursion, if getProperty is called with the same key as
  119. # we are already trying to resolve, we should not try to resolve again. Since
  120. # this can happen multiple times when trying to resolve a value, we need to
  121. # track all settings that are being resolved.
  122. return False
  123. setting_state = super().getProperty(key, "state", context = context)
  124. if setting_state is not None and setting_state != InstanceState.Default:
  125. # When the user has explicitly set a value, we should ignore any resolve and
  126. # just return that value.
  127. return False
  128. return True
  129. ## private:
  130. global_stack_mime = MimeType(
  131. name = "application/x-cura-globalstack",
  132. comment = "Cura Global Stack",
  133. suffixes = ["global.cfg"]
  134. )
  135. MimeTypeDatabase.addMimeType(global_stack_mime)
  136. ContainerRegistry.addContainerTypeByName(GlobalStack, "global_stack", global_stack_mime.name)