File size: 10,519 Bytes
2c3c408 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | from __future__ import annotations
from enum import Enum, unique
from fractions import Fraction
from functools import lru_cache
import re
from typing import Iterable, NamedTuple
import rich.repr
from ..geometry import Offset, Size, clamp
class ScalarError(Exception):
pass
class ScalarResolveError(ScalarError):
pass
class ScalarParseError(ScalarError):
pass
@unique
class Unit(Enum):
"""Enumeration of the various units inherited from CSS."""
CELLS = 1
FRACTION = 2
PERCENT = 3
WIDTH = 4
HEIGHT = 5
VIEW_WIDTH = 6
VIEW_HEIGHT = 7
AUTO = 8
UNIT_EXCLUDES_BORDER = {Unit.CELLS, Unit.FRACTION, Unit.VIEW_WIDTH, Unit.VIEW_HEIGHT}
UNIT_SYMBOL = {
Unit.CELLS: "",
Unit.FRACTION: "fr",
Unit.PERCENT: "%",
Unit.WIDTH: "w",
Unit.HEIGHT: "h",
Unit.VIEW_WIDTH: "vw",
Unit.VIEW_HEIGHT: "vh",
}
SYMBOL_UNIT = {v: k for k, v in UNIT_SYMBOL.items()}
_MATCH_SCALAR = re.compile(r"^(-?\d+\.?\d*)(fr|%|w|h|vw|vh)?$").match
def _resolve_cells(
value: float, size: Size, viewport: Size, fraction_unit: Fraction
) -> Fraction:
"""Resolves explicit cell size, i.e. width: 10
Args:
value (float): Scalar value.
size (Size): Size of widget.
viewport (Size): Size of viewport.
fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction.
Returns:
Fraction: Resolved unit.
"""
return Fraction(value)
def _resolve_fraction(
value: float, size: Size, viewport: Size, fraction_unit: Fraction
) -> Fraction:
"""Resolves a fraction unit i.e. width: 2fr
Args:
value (float): Scalar value.
size (Size): Size of widget.
viewport (Size): Size of viewport.
fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction.
Returns:
Fraction: Resolved unit.
"""
return fraction_unit * Fraction(value)
def _resolve_width(
value: float, size: Size, viewport: Size, fraction_unit: Fraction
) -> Fraction:
"""Resolves width unit i.e. width: 50w.
Args:
value (float): Scalar value.
size (Size): Size of widget.
viewport (Size): Size of viewport.
fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction.
Returns:
Fraction: Resolved unit.
"""
return Fraction(value) * Fraction(size.width, 100)
def _resolve_height(
value: float, size: Size, viewport: Size, fraction_unit: Fraction
) -> Fraction:
"""Resolves height unit, i.e. height: 12h.
Args:
value (float): Scalar value.
size (Size): Size of widget.
viewport (Size): Size of viewport.
fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction.
Returns:
Fraction: Resolved unit.
"""
return Fraction(value) * Fraction(size.height, 100)
def _resolve_view_width(
value: float, size: Size, viewport: Size, fraction_unit: Fraction
) -> Fraction:
"""Resolves view width unit, i.e. width: 25vw.
Args:
value (float): Scalar value.
size (Size): Size of widget.
viewport (Size): Size of viewport.
fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction.
Returns:
Fraction: Resolved unit.
"""
return Fraction(value) * Fraction(viewport.width, 100)
def _resolve_view_height(
value: float, size: Size, viewport: Size, fraction_unit: Fraction
) -> Fraction:
"""Resolves view height unit, i.e. height: 25vh.
Args:
value (float): Scalar value.
size (Size): Size of widget.
viewport (Size): Size of viewport.
fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction.
Returns:
Fraction: Resolved unit.
"""
return Fraction(value) * Fraction(viewport.height, 100)
RESOLVE_MAP = {
Unit.CELLS: _resolve_cells,
Unit.FRACTION: _resolve_fraction,
Unit.WIDTH: _resolve_width,
Unit.HEIGHT: _resolve_height,
Unit.VIEW_WIDTH: _resolve_view_width,
Unit.VIEW_HEIGHT: _resolve_view_height,
}
def get_symbols(units: Iterable[Unit]) -> list[str]:
"""Get symbols for an iterable of units.
Args:
units (Iterable[Unit]): A number of units.
Returns:
list[str]: List of symbols.
"""
return [UNIT_SYMBOL[unit] for unit in units]
class Scalar(NamedTuple):
"""A numeric value and a unit."""
value: float
unit: Unit
percent_unit: Unit
def __str__(self) -> str:
value, unit, _ = self
if unit == Unit.AUTO:
return "auto"
return f"{int(value) if value.is_integer() else value}{self.symbol}"
@property
def is_cells(self) -> bool:
"""Check if the Scalar is explicit cells."""
return self.unit == Unit.CELLS
@property
def is_percent(self) -> bool:
"""Check if the Scalar is a percentage unit."""
return self.unit == Unit.PERCENT
@property
def is_fraction(self) -> bool:
"""Check if the unit is a fraction."""
return self.unit == Unit.FRACTION
@property
def excludes_border(self) -> bool:
return self.unit in UNIT_EXCLUDES_BORDER
@property
def cells(self) -> int | None:
"""Check if the unit is explicit cells."""
value, unit, _ = self
return int(value) if unit == Unit.CELLS else None
@property
def fraction(self) -> int | None:
"""Get the fraction value, or None if not a value."""
value, unit, _ = self
return int(value) if unit == Unit.FRACTION else None
@property
def symbol(self) -> str:
"""Get the symbol of this unit."""
return UNIT_SYMBOL[self.unit]
@property
def is_auto(self) -> bool:
"""Check if this is an auto unit."""
return self.unit == Unit.AUTO
@classmethod
def from_number(cls, value: float) -> Scalar:
"""Create a scalar with cells unit.
Args:
value (float): A number of cells.
Returns:
Scalar: New Scalar.
"""
return cls(float(value), Unit.CELLS, Unit.WIDTH)
@classmethod
def parse(cls, token: str, percent_unit: Unit = Unit.WIDTH) -> Scalar:
"""Parse a string in to a Scalar
Args:
token (str): A string containing a scalar, e.g. "3.14fr"
Raises:
ScalarParseError: If the value is not a valid scalar
Returns:
Scalar: New scalar
"""
if token.lower() == "auto":
scalar = cls(1.0, Unit.AUTO, Unit.AUTO)
else:
match = _MATCH_SCALAR(token)
if match is None:
raise ScalarParseError(f"{token!r} is not a valid scalar")
value, unit_name = match.groups()
scalar = cls(float(value), SYMBOL_UNIT[unit_name or ""], percent_unit)
return scalar
@lru_cache(maxsize=4096)
def resolve_dimension(
self, size: Size, viewport: Size, fraction_unit: Fraction | None = None
) -> Fraction:
"""Resolve scalar with units in to a dimensions.
Args:
size (tuple[int, int]): Size of the container.
viewport (tuple[int, int]): Size of the viewport (typically terminal size)
Raises:
ScalarResolveError: If the unit is unknown.
Returns:
int: A size (in cells)
"""
value, unit, percent_unit = self
if unit == Unit.PERCENT:
unit = percent_unit
try:
dimension = RESOLVE_MAP[unit](
value, size, viewport, fraction_unit or Fraction(1)
)
except KeyError:
raise ScalarResolveError(f"expected dimensions; found {str(self)!r}")
return dimension
def copy_with(
self,
value: float | None = None,
unit: Unit | None = None,
percent_unit: Unit | None = None,
) -> Scalar:
"""Get a copy of this Scalar, with values optionally modified
Args:
value (float | None): The new value, or None to keep the same value
unit (Unit | None): The new unit, or None to keep the same unit
percent_unit (Unit | None): The new percent_unit, or None to keep the same percent_unit
"""
return Scalar(
value if value is not None else self.value,
unit if unit is not None else self.unit,
percent_unit if percent_unit is not None else self.percent_unit,
)
@rich.repr.auto(angular=True)
class ScalarOffset(NamedTuple):
"""An Offset with two scalars, used to animate between to Scalars."""
x: Scalar
y: Scalar
@classmethod
def null(cls) -> ScalarOffset:
"""Get a null scalar offset (0, 0)."""
return NULL_SCALAR
@classmethod
def from_offset(cls, offset: tuple[int, int]) -> ScalarOffset:
"""Create a Scalar offset from a tuple of integers.
Args:
offset (tuple[int, int]): Offset in cells.
Returns:
ScalarOffset: New offset.
"""
x, y = offset
return cls(
Scalar(x, Unit.CELLS, Unit.WIDTH),
Scalar(y, Unit.CELLS, Unit.HEIGHT),
)
def __bool__(self) -> bool:
x, y = self
return bool(x.value or y.value)
def __rich_repr__(self) -> rich.repr.Result:
yield None, str(self.x)
yield None, str(self.y)
def resolve(self, size: Size, viewport: Size) -> Offset:
"""Resolve the offset in to cells.
Args:
size (Size): Size of container.
viewport (Size): Size of viewport.
Returns:
Offset: Offset in cells.
"""
x, y = self
return Offset(
round(x.resolve_dimension(size, viewport)),
round(y.resolve_dimension(size, viewport)),
)
NULL_SCALAR = ScalarOffset(Scalar.from_number(0), Scalar.from_number(0))
def percentage_string_to_float(string: str) -> float:
"""Convert a string percentage e.g. '20%' to a float e.g. 20.0.
Args:
string (str): The percentage string to convert.
"""
string = string.strip()
if string.endswith("%"):
float_percentage = clamp(float(string[:-1]) / 100.0, 0.0, 1.0)
else:
float_percentage = float(string)
return float_percentage
if __name__ == "__main__":
print(Scalar.parse("3.14fr"))
s = Scalar.parse("23")
print(repr(s))
print(repr(s.cells))
|