ui-theme 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ui_theme/clock.py ADDED
@@ -0,0 +1,141 @@
1
+ """One animation clock for every running effect.
2
+
3
+ Paint derives from one clock-owned instant: a target reads `animation.frame()`
4
+ without sampling wall time or holding a frame counter. A backend gives the
5
+ clock one timer (`schedule`). It ticks at the fastest visible effect's rate
6
+ (a hidden effect asks only for the tick at its finish),
7
+ repaints visible targets together when their shared cadence boundary changes,
8
+ gives each finished effect one last paint and stops ticking when nothing runs.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass
15
+ from time import monotonic
16
+ from typing import Generic, Protocol, TypeVar
17
+
18
+ from ui_theme.effects import Effect, Frame
19
+
20
+ FrameT = TypeVar("FrameT", bound=Frame, covariant=True)
21
+
22
+
23
+ class AnimationTarget(Protocol):
24
+ """Something an effect decorates, as the frontend sees it."""
25
+
26
+ @property
27
+ def animation_visible(self) -> bool:
28
+ """True while painting it would show on screen."""
29
+
30
+ def repaint(self) -> None:
31
+ """Ask the frontend to paint it again (it reads its frame when it paints)."""
32
+
33
+
34
+ @dataclass(frozen=True, eq=False)
35
+ class Animation(Generic[FrameT]):
36
+ """One effect's lifetime; the clock owns its target association and cadence."""
37
+
38
+ clock: AnimationClock
39
+ effect: Effect[FrameT]
40
+ started: float
41
+
42
+ @property
43
+ def elapsed(self) -> float:
44
+ return max(0.0, self.clock.time - self.started)
45
+
46
+ @property
47
+ def finished(self) -> bool:
48
+ return not self.clock.enabled or self.effect.finished(self.elapsed)
49
+
50
+ def frame(self) -> FrameT:
51
+ """What the effect shows now; its final frame once finished or when animation is off."""
52
+ return self.at(0.0)
53
+
54
+ def at(self, position: float) -> FrameT:
55
+ """What the effect shows now for a row `position` of the way through its target.
56
+
57
+ One body, so a row cannot lose the phase time a continuous effect reads from the
58
+ clock, nor the finished and animation-off answers. An effect that treats its rows
59
+ alike ignores the position (Effect.at).
60
+ """
61
+ if self.finished:
62
+ return self.effect.final
63
+ return self.effect.at(self.effect.phase_time(self.elapsed, self.clock.time), position)
64
+
65
+ def stop(self) -> None:
66
+ self.clock.running.pop(self, None)
67
+ self.clock.refresh()
68
+
69
+ def interval(self, target: AnimationTarget) -> float | None:
70
+ """When it next needs a tick: its cadence while seen, only its finish while hidden."""
71
+ if target.animation_visible:
72
+ return 1 / self.effect.frames_per_second
73
+ return self.effect.remaining(self.elapsed)
74
+
75
+
76
+ class AnimationClock:
77
+ """Runs every animation's cadence from one timer."""
78
+
79
+ def __init__(self, schedule: Callable[[float | None], None],
80
+ now: Callable[[], float] = monotonic, *, enabled: bool = True) -> None:
81
+ # `schedule(interval)` asks the backend to call `tick` every `interval`
82
+ # seconds, or to stop calling it when interval is None.
83
+ self.schedule = schedule
84
+ self.now = now
85
+ # One paint instant. Painting never samples wall time; ticks
86
+ # advance this instant and invalidate the due targets together.
87
+ self.time = now()
88
+ self.enabled = enabled
89
+ self.running: dict[Animation[Frame], AnimationTarget] = {}
90
+ self._interval: float | None = None
91
+
92
+ def start(self, effect: Effect[FrameT], target: AnimationTarget) -> Animation[FrameT]:
93
+ """Run an effect; independent effects on one target share this clock."""
94
+ animation: Animation[FrameT] = Animation(self, effect, self.now())
95
+ if self.enabled:
96
+ self.running[animation] = target
97
+ self.refresh()
98
+ return animation
99
+
100
+ def stop(self, target: AnimationTarget) -> None:
101
+ for animation, owner in tuple(self.running.items()):
102
+ if owner is target:
103
+ del self.running[animation]
104
+ self.refresh()
105
+
106
+ def tick(self) -> None:
107
+ previous = self.time
108
+ now = self.time = self.now()
109
+ repaint: set[AnimationTarget] = set()
110
+ visible: dict[AnimationTarget, bool] = {}
111
+ for animation, target in list(self.running.items()):
112
+ effect = animation.effect
113
+ finished = animation.finished
114
+ if finished:
115
+ del self.running[animation]
116
+ if target not in visible:
117
+ visible[target] = target.animation_visible
118
+ if finished or (visible[target]
119
+ and effect.cadence_time(previous) != effect.cadence_time(now)):
120
+ repaint.add(target)
121
+ for target in repaint:
122
+ target.repaint()
123
+ self._refresh(visible)
124
+
125
+ def refresh(self) -> None:
126
+ self._refresh({})
127
+
128
+ def _refresh(self, visible: dict[AnimationTarget, bool]) -> None:
129
+ def _interval(animation: Animation[Frame], target: AnimationTarget) -> float | None:
130
+ if target not in visible:
131
+ visible[target] = target.animation_visible
132
+ if visible[target]:
133
+ return 1 / animation.effect.frames_per_second
134
+ return animation.effect.remaining(animation.elapsed)
135
+ intervals = (_interval(a, t) for a, t in tuple(self.running.items()))
136
+ interval = min((seconds for seconds in intervals if seconds is not None and self.enabled), default=None)
137
+ if interval != self._interval:
138
+ if self._interval is None and interval is not None:
139
+ self.time = self.now()
140
+ self._interval = interval
141
+ self.schedule(interval)
ui_theme/colour.py ADDED
@@ -0,0 +1,223 @@
1
+ """Colour values a scheme states, and a terminal's palette.
2
+
3
+ A scheme states each of its colours as one of three kinds:
4
+
5
+ - `Rgb`: a 24-bit colour, optionally translucent;
6
+ - `AnsiColour`: one of a terminal's sixteen palette slots;
7
+ - `TerminalDefault`: the terminal's own default foreground or background.
8
+
9
+ The last two belong to terminals. A terminal backend can emit them natively, so
10
+ they follow the terminal's palette live (pywal recolours every open terminal).
11
+ Every other backend asks for `rgb()`, which reads them from the scheme's
12
+ `TerminalPalette`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from abc import ABC, abstractmethod
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass, replace
20
+ from typing import TYPE_CHECKING, Any, ClassVar
21
+
22
+ if TYPE_CHECKING:
23
+ from ui_theme.backend import TerminalBackend
24
+
25
+
26
+ class ThemeValue:
27
+ """A declared theme value knows how a backend writes its CSS variable."""
28
+
29
+ @abstractmethod
30
+ def variable[Palette](self, backend: TerminalBackend[Palette]) -> str:
31
+ """Write this value through the terminal backend that owns its format."""
32
+ raise NotImplementedError
33
+
34
+
35
+ class Colour(ThemeValue, ABC):
36
+ """A colour a scheme states."""
37
+
38
+ # True for colours the terminal supplies: they cannot be blended without
39
+ # reading them from a palette.
40
+ from_terminal: ClassVar[bool] = False
41
+
42
+ def variable[Palette](self, backend: TerminalBackend[Palette]) -> str:
43
+ return backend.colour_variable(self)
44
+
45
+ @abstractmethod
46
+ def rgb(self, palette: TerminalPalette, *, background: bool) -> Rgb:
47
+ """This colour in 24 bits, reading terminal colours from `palette`."""
48
+
49
+ @abstractmethod
50
+ def native(self, backend: TerminalBackend[Any]) -> Any:
51
+ """This colour as a terminal backend emits it."""
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Rgb(Colour):
56
+ """A 24-bit colour; its text form (pywal's) is `#rrggbb`."""
57
+
58
+ red: int
59
+ green: int
60
+ blue: int
61
+ alpha: float = 1.0
62
+
63
+ @classmethod
64
+ def parse(cls, text: str, alpha: float = 1.0) -> Rgb:
65
+ if not (isinstance(text, str) and len(text) == 7 and text[0] == "#"):
66
+ raise ValueError(f"Expected a #rrggbb colour, got {text!r}")
67
+ value = int(text[1:], 16)
68
+ return cls(value >> 16, (value >> 8) & 0xFF, value & 0xFF, alpha)
69
+
70
+ @property
71
+ def hex(self) -> str:
72
+ return f"#{self.red:02x}{self.green:02x}{self.blue:02x}"
73
+
74
+ @property
75
+ def triple(self) -> tuple[int, int, int]:
76
+ return self.red, self.green, self.blue
77
+
78
+ @property
79
+ def luminance(self) -> float:
80
+ """Relative luminance (sRGB), 0 for black and 1 for white."""
81
+
82
+ def linear(channel: int) -> float:
83
+ value = channel / 255
84
+ return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4
85
+
86
+ return 0.2126 * linear(self.red) + 0.7152 * linear(self.green) + 0.0722 * linear(self.blue)
87
+
88
+ @property
89
+ def brightness(self) -> float:
90
+ """Perceived brightness, 0 for black and 1 for white."""
91
+ return (299 * self.red + 587 * self.green + 114 * self.blue) / 255_000
92
+
93
+ @property
94
+ def inverse(self) -> Rgb:
95
+ return Rgb(255 - self.red, 255 - self.green, 255 - self.blue, self.alpha)
96
+
97
+ def with_alpha(self, alpha: float) -> Rgb:
98
+ return replace(self, alpha=alpha)
99
+
100
+ def blend(self, other: Rgb, amount: float, alpha: float | None = None) -> Rgb:
101
+ """The colour `amount` of the way from this one to `other` (0 is this, 1 is other)."""
102
+ if amount <= 0:
103
+ return self
104
+ if amount >= 1:
105
+ return other
106
+ return Rgb(
107
+ int(self.red + (other.red - self.red) * amount),
108
+ int(self.green + (other.green - self.green) * amount),
109
+ int(self.blue + (other.blue - self.blue) * amount),
110
+ self.alpha + (other.alpha - self.alpha) * amount if alpha is None else alpha,
111
+ )
112
+
113
+ def under(self, layer: Rgb) -> Rgb:
114
+ """This colour with a translucent `layer` painted over it."""
115
+ return self.blend(layer, layer.alpha, 1.0)
116
+
117
+ def contrast_text(self, alpha: float) -> Rgb:
118
+ """White or black, whichever reads on this colour, at `alpha`."""
119
+ return (WHITE if self.brightness < 0.5 else BLACK).with_alpha(alpha)
120
+
121
+ def rgb(self, palette: TerminalPalette, *, background: bool) -> Rgb:
122
+ return self
123
+
124
+ def native(self, backend: TerminalBackend[Any]) -> Any:
125
+ return backend.rgb(self)
126
+
127
+
128
+ WHITE = Rgb(255, 255, 255)
129
+ BLACK = Rgb(0, 0, 0)
130
+
131
+
132
+ @dataclass(frozen=True)
133
+ class AnsiColour(Colour):
134
+ """One of a terminal's sixteen palette colours."""
135
+
136
+ index: int
137
+
138
+ from_terminal = True
139
+ NAMES: ClassVar[tuple[str, ...]] = (
140
+ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white")
141
+
142
+ def __post_init__(self) -> None:
143
+ if not 0 <= self.index < 16:
144
+ raise ValueError(f"A terminal has ANSI colours 0-15, not {self.index}")
145
+
146
+ @property
147
+ def name(self) -> str:
148
+ base = self.NAMES[self.index % 8]
149
+ return f"bright_{base}" if self.index >= 8 else base
150
+
151
+ def rgb(self, palette: TerminalPalette, *, background: bool) -> Rgb:
152
+ return palette.ansi[self.index]
153
+
154
+ def native(self, backend: TerminalBackend[Any]) -> Any:
155
+ return backend.ansi(self)
156
+
157
+
158
+ (BLACK_ANSI, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE_ANSI,
159
+ BRIGHT_BLACK, BRIGHT_RED, BRIGHT_GREEN, BRIGHT_YELLOW, BRIGHT_BLUE, BRIGHT_MAGENTA, BRIGHT_CYAN,
160
+ BRIGHT_WHITE) = (AnsiColour(index) for index in range(16))
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class TerminalDefault(Colour):
165
+ """The terminal's default colour: its foreground for text, its background behind it."""
166
+
167
+ from_terminal = True
168
+
169
+ def rgb(self, palette: TerminalPalette, *, background: bool) -> Rgb:
170
+ return palette.background if background else palette.foreground
171
+
172
+ def native(self, backend: TerminalBackend[Any]) -> Any:
173
+ return backend.terminal_default()
174
+
175
+
176
+ TERMINAL_DEFAULT = TerminalDefault()
177
+
178
+
179
+ class PaletteSource(ABC):
180
+ """Where a scheme's terminal colours come from."""
181
+
182
+ @abstractmethod
183
+ def resolve(self, query: Callable[[], TerminalPalette]) -> TerminalPalette:
184
+ """Supply declared colours or ask the terminal that owns them."""
185
+
186
+
187
+ class TerminalOwnedPalette(PaletteSource):
188
+ def resolve(self, query: Callable[[], TerminalPalette]) -> TerminalPalette:
189
+ return query()
190
+
191
+
192
+ class TerminalPaletteRequired(RuntimeError):
193
+ """RGB rendering of terminal colours needs a palette from that terminal."""
194
+
195
+
196
+ def require_terminal_palette() -> TerminalPalette:
197
+ raise TerminalPaletteRequired("Query the terminal palette before resolving its colours")
198
+
199
+
200
+ @dataclass(frozen=True)
201
+ class TerminalPalette(PaletteSource):
202
+ """A terminal's colours: ANSI 0–15, the default foreground and background, the cursor."""
203
+
204
+ background: Rgb
205
+ foreground: Rgb
206
+ cursor: Rgb
207
+ ansi: tuple[Rgb, ...]
208
+
209
+ def resolve(self, query: Callable[[], TerminalPalette]) -> TerminalPalette:
210
+ return self
211
+
212
+ def __post_init__(self) -> None:
213
+ if len(self.ansi) != 16:
214
+ raise ValueError(f"A terminal palette has 16 ANSI colours, not {len(self.ansi)}")
215
+
216
+ @classmethod
217
+ def of(cls, background: str, foreground: str, *ansi: str) -> TerminalPalette:
218
+ return cls(Rgb.parse(background), Rgb.parse(foreground), Rgb.parse(foreground),
219
+ tuple(map(Rgb.parse, ansi)))
220
+
221
+ @property
222
+ def dark(self) -> bool:
223
+ return self.background.luminance < 0.5
ui_theme/depth.py ADDED
@@ -0,0 +1,48 @@
1
+ """How many colours a host terminal shows: a fact of terminal backends only.
2
+
3
+ Decided once, at launch, from what the terminal advertises: `COLORTERM`, then
4
+ terminfo, then the suffix of `TERM`. Painted rows keep their terminal
5
+ sequences, so the depth cannot change while an app runs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import curses
11
+ from collections.abc import Mapping
12
+ from typing import ClassVar
13
+
14
+
15
+ class ColourDepth:
16
+ # The terminal-standard name (COLORTERM, Rich, Textual) for this depth.
17
+ name: ClassVar[str]
18
+
19
+ @staticmethod
20
+ def of_terminal(environment: Mapping[str, str]) -> type[ColourDepth]:
21
+ if environment.get("COLORTERM", "").lower() in ("truecolor", "24bit"):
22
+ return TrueColourDepth
23
+ term = environment.get("TERM", "")
24
+ if not term or term in ("dumb", "unknown"):
25
+ return Ansi16Depth
26
+ try:
27
+ curses.setupterm(term, -1)
28
+ except curses.error:
29
+ # No terminfo entry for TERM: the name is all the terminal said.
30
+ pass
31
+ else:
32
+ if curses.tigetflag("Tc") == 1 or curses.tigetflag("RGB") == 1:
33
+ return TrueColourDepth
34
+ if curses.tigetnum("colors") >= 256:
35
+ return Palette256Depth
36
+ return Palette256Depth if term.endswith("256color") else Ansi16Depth
37
+
38
+
39
+ class TrueColourDepth(ColourDepth):
40
+ name = "truecolor"
41
+
42
+
43
+ class Palette256Depth(ColourDepth):
44
+ name = "256"
45
+
46
+
47
+ class Ansi16Depth(ColourDepth):
48
+ name = "standard"