dimension.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """
  2. Layout dimensions are used to give the minimum, maximum and preferred
  3. dimensions for containers and controls.
  4. """
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING, Any, Callable, Union
  7. __all__ = [
  8. "Dimension",
  9. "D",
  10. "sum_layout_dimensions",
  11. "max_layout_dimensions",
  12. "AnyDimension",
  13. "to_dimension",
  14. "is_dimension",
  15. ]
  16. if TYPE_CHECKING:
  17. from typing_extensions import TypeGuard
  18. class Dimension:
  19. """
  20. Specified dimension (width/height) of a user control or window.
  21. The layout engine tries to honor the preferred size. If that is not
  22. possible, because the terminal is larger or smaller, it tries to keep in
  23. between min and max.
  24. :param min: Minimum size.
  25. :param max: Maximum size.
  26. :param weight: For a VSplit/HSplit, the actual size will be determined
  27. by taking the proportion of weights from all the children.
  28. E.g. When there are two children, one with a weight of 1,
  29. and the other with a weight of 2, the second will always be
  30. twice as big as the first, if the min/max values allow it.
  31. :param preferred: Preferred size.
  32. """
  33. def __init__(
  34. self,
  35. min: int | None = None,
  36. max: int | None = None,
  37. weight: int | None = None,
  38. preferred: int | None = None,
  39. ) -> None:
  40. if weight is not None:
  41. assert weight >= 0 # Also cannot be a float.
  42. assert min is None or min >= 0
  43. assert max is None or max >= 0
  44. assert preferred is None or preferred >= 0
  45. self.min_specified = min is not None
  46. self.max_specified = max is not None
  47. self.preferred_specified = preferred is not None
  48. self.weight_specified = weight is not None
  49. if min is None:
  50. min = 0 # Smallest possible value.
  51. if max is None: # 0-values are allowed, so use "is None"
  52. max = 1000**10 # Something huge.
  53. if preferred is None:
  54. preferred = min
  55. if weight is None:
  56. weight = 1
  57. self.min = min
  58. self.max = max
  59. self.preferred = preferred
  60. self.weight = weight
  61. # Don't allow situations where max < min. (This would be a bug.)
  62. if max < min:
  63. raise ValueError("Invalid Dimension: max < min.")
  64. # Make sure that the 'preferred' size is always in the min..max range.
  65. if self.preferred < self.min:
  66. self.preferred = self.min
  67. if self.preferred > self.max:
  68. self.preferred = self.max
  69. @classmethod
  70. def exact(cls, amount: int) -> Dimension:
  71. """
  72. Return a :class:`.Dimension` with an exact size. (min, max and
  73. preferred set to ``amount``).
  74. """
  75. return cls(min=amount, max=amount, preferred=amount)
  76. @classmethod
  77. def zero(cls) -> Dimension:
  78. """
  79. Create a dimension that represents a zero size. (Used for 'invisible'
  80. controls.)
  81. """
  82. return cls.exact(amount=0)
  83. def is_zero(self) -> bool:
  84. "True if this `Dimension` represents a zero size."
  85. return self.preferred == 0 or self.max == 0
  86. def __repr__(self) -> str:
  87. fields = []
  88. if self.min_specified:
  89. fields.append("min=%r" % self.min)
  90. if self.max_specified:
  91. fields.append("max=%r" % self.max)
  92. if self.preferred_specified:
  93. fields.append("preferred=%r" % self.preferred)
  94. if self.weight_specified:
  95. fields.append("weight=%r" % self.weight)
  96. return "Dimension(%s)" % ", ".join(fields)
  97. def sum_layout_dimensions(dimensions: list[Dimension]) -> Dimension:
  98. """
  99. Sum a list of :class:`.Dimension` instances.
  100. """
  101. min = sum(d.min for d in dimensions)
  102. max = sum(d.max for d in dimensions)
  103. preferred = sum(d.preferred for d in dimensions)
  104. return Dimension(min=min, max=max, preferred=preferred)
  105. def max_layout_dimensions(dimensions: list[Dimension]) -> Dimension:
  106. """
  107. Take the maximum of a list of :class:`.Dimension` instances.
  108. Used when we have a HSplit/VSplit, and we want to get the best width/height.)
  109. """
  110. if not len(dimensions):
  111. return Dimension.zero()
  112. # If all dimensions are size zero. Return zero.
  113. # (This is important for HSplit/VSplit, to report the right values to their
  114. # parent when all children are invisible.)
  115. if all(d.is_zero() for d in dimensions):
  116. return dimensions[0]
  117. # Ignore empty dimensions. (They should not reduce the size of others.)
  118. dimensions = [d for d in dimensions if not d.is_zero()]
  119. if dimensions:
  120. # Take the highest minimum dimension.
  121. min_ = max(d.min for d in dimensions)
  122. # For the maximum, we would prefer not to go larger than then smallest
  123. # 'max' value, unless other dimensions have a bigger preferred value.
  124. # This seems to work best:
  125. # - We don't want that a widget with a small height in a VSplit would
  126. # shrink other widgets in the split.
  127. # If it doesn't work well enough, then it's up to the UI designer to
  128. # explicitly pass dimensions.
  129. max_ = min(d.max for d in dimensions)
  130. max_ = max(max_, max(d.preferred for d in dimensions))
  131. # Make sure that min>=max. In some scenarios, when certain min..max
  132. # ranges don't have any overlap, we can end up in such an impossible
  133. # situation. In that case, give priority to the max value.
  134. # E.g. taking (1..5) and (8..9) would return (8..5). Instead take (8..8).
  135. if min_ > max_:
  136. max_ = min_
  137. preferred = max(d.preferred for d in dimensions)
  138. return Dimension(min=min_, max=max_, preferred=preferred)
  139. else:
  140. return Dimension()
  141. # Anything that can be converted to a dimension.
  142. AnyDimension = Union[
  143. None, # None is a valid dimension that will fit anything.
  144. int,
  145. Dimension,
  146. # Callable[[], 'AnyDimension'] # Recursive definition not supported by mypy.
  147. Callable[[], Any],
  148. ]
  149. def to_dimension(value: AnyDimension) -> Dimension:
  150. """
  151. Turn the given object into a `Dimension` object.
  152. """
  153. if value is None:
  154. return Dimension()
  155. if isinstance(value, int):
  156. return Dimension.exact(value)
  157. if isinstance(value, Dimension):
  158. return value
  159. if callable(value):
  160. return to_dimension(value())
  161. raise ValueError("Not an integer or Dimension object.")
  162. def is_dimension(value: object) -> TypeGuard[AnyDimension]:
  163. """
  164. Test whether the given value could be a valid dimension.
  165. (For usage in an assertion. It's not guaranteed in case of a callable.)
  166. """
  167. if value is None:
  168. return True
  169. if callable(value):
  170. return True # Assume it's a callable that doesn't take arguments.
  171. if isinstance(value, (int, Dimension)):
  172. return True
  173. return False
  174. # Common alias.
  175. D = Dimension
  176. # For backward-compatibility.
  177. LayoutDimension = Dimension