GlobalStack.py 7.6 KB

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