staticfx 2.0.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.

Potentially problematic release.


This version of staticfx might be problematic. Click here for more details.

Files changed (65) hide show
  1. staticfx/__init__.py +3 -0
  2. staticfx/__main__.py +5 -0
  3. staticfx/app/__init__.py +1 -0
  4. staticfx/app/app.py +335 -0
  5. staticfx/app/keymap.py +163 -0
  6. staticfx/app/player.py +143 -0
  7. staticfx/app/session.py +97 -0
  8. staticfx/cli/__init__.py +20 -0
  9. staticfx/cli/commands.py +293 -0
  10. staticfx/cli/parser.py +185 -0
  11. staticfx/core/__init__.py +1 -0
  12. staticfx/core/clock.py +30 -0
  13. staticfx/core/color.py +89 -0
  14. staticfx/core/frame.py +85 -0
  15. staticfx/core/glyphs.py +15 -0
  16. staticfx/core/keys.py +116 -0
  17. staticfx/core/renderer.py +84 -0
  18. staticfx/core/terminal.py +148 -0
  19. staticfx/effects/__init__.py +1 -0
  20. staticfx/effects/base.py +88 -0
  21. staticfx/effects/builtin/__init__.py +203 -0
  22. staticfx/effects/builtin/fields.py +404 -0
  23. staticfx/effects/builtin/geometry.py +77 -0
  24. staticfx/effects/builtin/particles.py +623 -0
  25. staticfx/effects/builtin/shapes.py +255 -0
  26. staticfx/effects/builtin/signals.py +298 -0
  27. staticfx/effects/builtin/simulations.py +439 -0
  28. staticfx/effects/builtin/terminal.py +362 -0
  29. staticfx/effects/curated.py +16 -0
  30. staticfx/effects/engine/__init__.py +11 -0
  31. staticfx/effects/engine/effect.py +267 -0
  32. staticfx/effects/engine/filters.py +115 -0
  33. staticfx/effects/engine/generate.py +203 -0
  34. staticfx/effects/engine/layers.py +396 -0
  35. staticfx/effects/engine/recipe.py +215 -0
  36. staticfx/effects/engine/schema.py +87 -0
  37. staticfx/effects/engine/warps.py +203 -0
  38. staticfx/effects/registry.py +103 -0
  39. staticfx/effects/spec.py +51 -0
  40. staticfx/integrations.py +48 -0
  41. staticfx/library/__init__.py +1 -0
  42. staticfx/library/config.py +122 -0
  43. staticfx/library/effects.py +159 -0
  44. staticfx/library/files.py +44 -0
  45. staticfx/library/legacy.py +180 -0
  46. staticfx/library/looks.py +134 -0
  47. staticfx/postfx.py +78 -0
  48. staticfx/py.typed +0 -0
  49. staticfx/themes.py +162 -0
  50. staticfx/ui/__init__.py +1 -0
  51. staticfx/ui/browser.py +269 -0
  52. staticfx/ui/dialogs.py +95 -0
  53. staticfx/ui/help.py +99 -0
  54. staticfx/ui/pickers.py +221 -0
  55. staticfx/ui/play.py +213 -0
  56. staticfx/ui/screen.py +39 -0
  57. staticfx/ui/settings.py +262 -0
  58. staticfx/ui/studio.py +433 -0
  59. staticfx/ui/widgets.py +196 -0
  60. staticfx-2.0.0.dist-info/METADATA +164 -0
  61. staticfx-2.0.0.dist-info/RECORD +65 -0
  62. staticfx-2.0.0.dist-info/WHEEL +5 -0
  63. staticfx-2.0.0.dist-info/entry_points.txt +2 -0
  64. staticfx-2.0.0.dist-info/licenses/LICENSE +21 -0
  65. staticfx-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,44 @@
1
+ """Where user data lives, and writing it safely."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ NAME_LIMIT = 40
11
+
12
+
13
+ def default_data_dir() -> Path:
14
+ """``$XDG_CONFIG_HOME/staticfx``, falling back to ``~/.config/staticfx``."""
15
+ base = os.environ.get("XDG_CONFIG_HOME")
16
+ return (Path(base) if base else Path.home() / ".config") / "staticfx"
17
+
18
+
19
+ def atomic_write(path: Path, text: str) -> None:
20
+ """Write ``text`` so that ``path`` is never left half-written.
21
+
22
+ The data goes to a temporary file in the same directory, which is then
23
+ renamed over the target; a rename within one filesystem is atomic.
24
+ """
25
+ path.parent.mkdir(parents=True, exist_ok=True)
26
+ fd, temp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
27
+ try:
28
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
29
+ stream.write(text)
30
+ os.replace(temp, path)
31
+ except BaseException:
32
+ Path(temp).unlink(missing_ok=True)
33
+ raise
34
+
35
+
36
+ def clean_name(name: str) -> str:
37
+ """Collapse whitespace and cap the length of a user-supplied name."""
38
+ return " ".join(str(name).split())[:NAME_LIMIT]
39
+
40
+
41
+ def slugify(name: str) -> str:
42
+ """A safe file stem: lowercase letters, digits and underscores."""
43
+ slug = re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")
44
+ return slug[:32] or "effect"
@@ -0,0 +1,180 @@
1
+ """Reading files written by StaticFX 1.x.
2
+
3
+ 1.x had two incompatible formats that both used the ``.sfx`` extension:
4
+
5
+ * **Studio effects** (``"format": "staticfx-effect"``, version 2) stored the
6
+ recipe with terse keys - ``tfs``, ``pal``, ``f``, ``cre`` - and kind names
7
+ that were later renamed.
8
+ * **Plugins** (``"format": "sfx"``, version 1), read from a hidden
9
+ ``plugins/`` folder, described a single generator from a second engine that
10
+ no longer exists. They are translated to the nearest equivalent layer.
11
+
12
+ Both are converted to today's :class:`Recipe` on load; nothing is written
13
+ back until the user saves.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ from staticfx.core.color import RGB, parse_hex
21
+ from staticfx.effects.engine.generate import filter_params, layer_params, warp_params
22
+ from staticfx.effects.engine.layers import LAYERS, MANDELBROT_SPOTS
23
+ from staticfx.effects.engine.recipe import CHARSETS, Palette, Recipe, Stage
24
+
25
+ RENAMED = {
26
+ "kaleido": "kaleidoscope",
27
+ "warp": "wave",
28
+ "pixel": "pixelate",
29
+ "mandel": "mandelbrot",
30
+ "hex": "hexagons",
31
+ "lissa": "lissajous",
32
+ "vnoise": "noise",
33
+ "saw": "sawtooth",
34
+ }
35
+ BLENDS = {
36
+ "add": "average",
37
+ "mul": "multiply",
38
+ "max": "lighten",
39
+ "min": "darken",
40
+ "diff": "difference",
41
+ "screen": "screen",
42
+ "mod": "wrap",
43
+ "warp": "displace",
44
+ }
45
+ METRICS = {"euclid": "circle", "manhattan": "diamond", "chebyshev": "square", "mink": "star"}
46
+ SHAPES = {"tri": "triangle"}
47
+ VORONOI = {"edge": "edges", "cell": "distance", "id": "cells"}
48
+
49
+ # Defaults for every original parameter, so partial files still convert.
50
+ WARP_DEFAULTS = {
51
+ "rate": 0.2, "base": 1.5, "amp": 0.3, "zrate": 0.8, "n": 6, "rot": 0.2, "mode": "xy",
52
+ "s": 2.0, "dx": 0.2, "dy": 0.1, "k": 2.0, "freq": 3.0, "c": 0.3, "ang": 0.7,
53
+ "iters": 2, "q": 8.0, "rfreq": 10.0, "rrate": 2.0,
54
+ } # fmt: skip
55
+ LAYER_DEFAULTS = {
56
+ "f": 6.0, "f2": 6.0, "sp": 1.0, "n": 4, "k": 4, "metric": "euclid", "shape": "ring",
57
+ "mode": "edge", "cre": -0.6, "cim": 0.2, "mpt": (-0.745, 0.113), "vseed": 1,
58
+ } # fmt: skip
59
+ FILTER_DEFAULTS = {"g": 1.2, "n": 4, "k": 3, "pw": 1.0, "c": 0.3}
60
+
61
+
62
+ def _pairs(value: Any, what: str) -> list[tuple[str, dict]]:
63
+ if not isinstance(value, list):
64
+ raise ValueError(f"'{what}' must be a list")
65
+ pairs = []
66
+ for entry in value:
67
+ if not (
68
+ isinstance(entry, (list, tuple)) and len(entry) == 2 and isinstance(entry[1], dict)
69
+ ):
70
+ raise ValueError(f"each entry in '{what}' must be [kind, {{params}}]")
71
+ kind = str(entry[0])
72
+ pairs.append((RENAMED.get(kind, kind), entry[1]))
73
+ return pairs
74
+
75
+
76
+ def _nearest_spot(point: Any) -> str:
77
+ try:
78
+ x, y = float(point[0]), float(point[1])
79
+ except (TypeError, ValueError, IndexError):
80
+ return "seahorse"
81
+ return min(
82
+ MANDELBROT_SPOTS,
83
+ key=lambda s: abs(MANDELBROT_SPOTS[s][0] - x) + abs(MANDELBROT_SPOTS[s][1] - y),
84
+ )
85
+
86
+
87
+ def recipe_from_v2(data: Any) -> Recipe:
88
+ """Convert a 1.x Studio recipe. Raises ``ValueError`` when it can't be read."""
89
+ if not isinstance(data, dict):
90
+ raise ValueError("recipe must be an object")
91
+ try:
92
+ layers = []
93
+ for kind, raw in _pairs(data.get("layers"), "layers"):
94
+ v = {**LAYER_DEFAULTS, **raw}
95
+ v["metric"] = METRICS.get(v["metric"], "circle")
96
+ v["shape"] = SHAPES.get(v["shape"], v["shape"])
97
+ v["mode"] = VORONOI.get(v["mode"], "edges")
98
+ v["spot"] = _nearest_spot(v["mpt"])
99
+ v["seed"] = v["vseed"]
100
+ layers.append(Stage(kind, layer_params(kind, v, float(v["sp"]))))
101
+ if not 1 <= len(layers) <= 3:
102
+ raise ValueError("a recipe needs 1-3 layers")
103
+ for layer, op in zip(layers[1:], data.get("ops", []), strict=False):
104
+ layer.blend = BLENDS.get(op, "average")
105
+
106
+ warps = [
107
+ Stage(kind, warp_params(kind, {**WARP_DEFAULTS, **raw}))
108
+ for kind, raw in _pairs(data.get("tfs", []), "tfs")
109
+ ]
110
+ filters = [
111
+ Stage(kind, filter_params(kind, {**FILTER_DEFAULTS, **raw}))
112
+ for kind, raw in _pairs(data.get("posts", []), "posts")
113
+ ]
114
+
115
+ pal = data.get("pal", ["theme"])
116
+ if pal[0] == "rainbow":
117
+ palette = Palette("rainbow", float(pal[1]), float(pal[2]), float(pal[3]) % 1.0)
118
+ elif pal[0] == "duo":
119
+ palette = Palette("duo", first=RGB(*map(int, pal[1])), second=RGB(*map(int, pal[2])))
120
+ else:
121
+ palette = Palette("angular" if pal[0] == "angular" else "theme")
122
+
123
+ return Recipe(
124
+ layers=layers,
125
+ warps=warps[:3],
126
+ filters=filters[:3],
127
+ speed=min(6.0, max(0.05, float(data.get("speed", 1.0)))),
128
+ charset=CHARSETS[int(data.get("ramp_pick", 0)) % len(CHARSETS)],
129
+ glyph_rain=data.get("style") == "glyph",
130
+ dither=bool(data.get("dither", False)),
131
+ palette=palette,
132
+ trail=min(0.98, max(0.0, float(data.get("trail", 0.0)))),
133
+ pulse=float(data.get("pulse_rate", 2.0)) if data.get("pulse") else 0.0,
134
+ scanlines=bool(data.get("scan", False)),
135
+ glitch=bool(data.get("glitch", False)),
136
+ sparkle=min(0.05, max(0.0, float(data.get("sparkle", 0.0)))),
137
+ seed=int(data.get("seed", 0)),
138
+ )
139
+ except (KeyError, TypeError, IndexError) as exc: # unknown kind, malformed value
140
+ raise ValueError(f"unreadable 1.x recipe ({exc.__class__.__name__}: {exc})") from None
141
+
142
+
143
+ # The 1.x plugin engine's generators and the layer each now becomes.
144
+ PLUGIN_GENERATORS = {
145
+ "field": "flow",
146
+ "noise": "noise",
147
+ "waves": "grid",
148
+ "particles": "sources",
149
+ "grid": "checker",
150
+ "spiral": "spiral",
151
+ "radial": "rings",
152
+ "cellular": "voronoi",
153
+ }
154
+
155
+
156
+ def recipe_from_plugin(data: dict) -> Recipe:
157
+ """Best-effort conversion of a 1.x plugin definition."""
158
+ generator = data.get("generator")
159
+ if generator not in PLUGIN_GENERATORS:
160
+ raise ValueError(f"unknown plugin generator {generator!r}")
161
+ kind = PLUGIN_GENERATORS[generator]
162
+ params = data.get("parameters") or {}
163
+ layer = {"speed": params.get("speed", 1.0)} if isinstance(params, dict) else {}
164
+ if kind == "voronoi":
165
+ layer["style"] = "cells"
166
+ colours = []
167
+ for text in data.get("palette") or []:
168
+ try:
169
+ colours.append(parse_hex(str(text)))
170
+ except ValueError:
171
+ continue
172
+ palette = (
173
+ Palette("duo", first=colours[0], second=colours[-1]) if len(colours) >= 2 else Palette()
174
+ )
175
+ seed = data.get("seed", 0)
176
+ return Recipe(
177
+ layers=[Stage(kind, LAYERS[kind].clean(layer))],
178
+ palette=palette,
179
+ seed=seed if isinstance(seed, int) and seed >= 0 else 0,
180
+ )
@@ -0,0 +1,134 @@
1
+ """Looks: an effect plus a theme, speed and filters, saved under a name."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict, dataclass
7
+ from pathlib import Path
8
+
9
+ from staticfx import themes
10
+ from staticfx.library.files import atomic_write, clean_name
11
+
12
+ SPEED_MIN, SPEED_MAX = 0.1, 5.0
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Look:
17
+ name: str
18
+ effect: str
19
+ theme: str = themes.DEFAULT
20
+ speed: float = 1.0
21
+ crt: bool = False
22
+ glitch: bool = False
23
+ recolour: bool = False
24
+ note: str = "" # a short description shown in the menu (built-in looks only)
25
+
26
+
27
+ BUILTIN_LOOKS = (
28
+ Look("Classic Matrix", "matrix", "matrix", note="Where it all started"),
29
+ Look(
30
+ "Terminal Breach",
31
+ "decrypt_scramble",
32
+ "matrix",
33
+ crt=True,
34
+ glitch=True,
35
+ note="Movie-hacker decryption on a CRT",
36
+ ),
37
+ Look("Cyber Rain", "matrix", "cyberpunk", crt=True, recolour=True, note="Neon rain"),
38
+ Look(
39
+ "System Override", "terminal_boot", "toxic", glitch=True, note="A boot sequence going wrong"
40
+ ),
41
+ Look(
42
+ "Signal Intercept",
43
+ "signal_scramble",
44
+ "mono",
45
+ crt=True,
46
+ glitch=True,
47
+ note="Black-and-white scope traces",
48
+ ),
49
+ Look("Neon Intrusion", "circuit", "cyberpunk", glitch=True, note="Glitching circuit traces"),
50
+ Look("Synthwave", "grid_wave", "rose", crt=True, note="An endless neon floor"),
51
+ Look("Deep Sea", "ocean_waves", "ocean", speed=0.7, note="Slow rolling waves"),
52
+ Look("Campfire", "fire", "inferno", note="Pull up a chair"),
53
+ Look("Deep Space", "starfield", "arctic", speed=0.6, note="Drifting through the stars"),
54
+ Look("Winter Night", "snowfall", "arctic", note="Quiet snow"),
55
+ Look("Hanami", "sakura_rain", "sakura", note="Cherry blossom season"),
56
+ )
57
+
58
+
59
+ class LookStore:
60
+ """The user's saved looks, kept in ``looks.json``."""
61
+
62
+ def __init__(self, path: Path | None) -> None:
63
+ self.path = path # None keeps looks in memory only
64
+ self.looks: list[Look] = []
65
+
66
+ def load(self) -> list[str]:
67
+ """Read the file. Returns problems; a bad file or entry is skipped, never fatal."""
68
+ self.looks = []
69
+ if self.path is None or not self.path.exists():
70
+ return []
71
+ try:
72
+ data = json.loads(self.path.read_text(encoding="utf-8"))
73
+ entries = data["looks"]
74
+ if not isinstance(entries, list):
75
+ raise TypeError
76
+ except (OSError, UnicodeDecodeError, ValueError, KeyError, TypeError):
77
+ return [f"{self.path.name} is unreadable; your saved looks were not loaded"]
78
+
79
+ problems = []
80
+ for entry in entries:
81
+ try:
82
+ theme = themes.normalize(str(entry.get("theme", themes.DEFAULT)))
83
+ self.looks.append(
84
+ Look(
85
+ name=clean_name(entry["name"]) or "Untitled",
86
+ effect=str(entry["effect"]),
87
+ theme=theme,
88
+ speed=min(SPEED_MAX, max(SPEED_MIN, float(entry.get("speed", 1.0)))),
89
+ crt=bool(entry.get("crt", False)),
90
+ glitch=bool(entry.get("glitch", False)),
91
+ # "recolor" is the 1.x spelling
92
+ recolour=bool(entry.get("recolour", entry.get("recolor", False))),
93
+ )
94
+ )
95
+ except (AttributeError, KeyError, TypeError, ValueError):
96
+ problems.append(f"{self.path.name}: skipped a malformed look")
97
+ return problems
98
+
99
+ def save(self) -> None:
100
+ if self.path is None:
101
+ return
102
+ looks = []
103
+ for look in self.looks:
104
+ data = asdict(look)
105
+ del data["note"]
106
+ looks.append(data)
107
+ atomic_write(self.path, json.dumps({"version": 2, "looks": looks}, indent=2) + "\n")
108
+
109
+ def find(self, name: str) -> Look | None:
110
+ wanted = name.strip().lower()
111
+ return next((look for look in self.looks if look.name.lower() == wanted), None)
112
+
113
+ def put(self, look: Look) -> bool:
114
+ """Add ``look``, replacing one with the same name. True if it replaced one."""
115
+ existing = self.find(look.name)
116
+ if existing is not None:
117
+ self.looks[self.looks.index(existing)] = look
118
+ else:
119
+ self.looks.append(look)
120
+ self.save()
121
+ return existing is not None
122
+
123
+ def remove(self, name: str) -> None:
124
+ existing = self.find(name)
125
+ if existing is not None:
126
+ self.looks.remove(existing)
127
+ self.save()
128
+
129
+
130
+ def find_look(name: str, store: LookStore) -> Look | None:
131
+ """A saved look by name, falling back to the built-in ones."""
132
+ wanted = name.strip().lower()
133
+ builtin = next((look for look in BUILTIN_LOOKS if look.name.lower() == wanted), None)
134
+ return store.find(name) or builtin
staticfx/postfx.py ADDED
@@ -0,0 +1,78 @@
1
+ """Filters applied to the finished frame, on top of any effect and theme.
2
+
3
+ * **CRT** darkens every other row, like scanlines on a tube.
4
+ * **Glitch** occasionally tears a band of rows sideways.
5
+ * **Recolour** repaints everything with a diagonal rainbow, keeping each
6
+ cell's original brightness so the effect's shading survives.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import random
12
+ from dataclasses import dataclass, field
13
+
14
+ from staticfx.core.color import RGB, hsv
15
+ from staticfx.core.frame import Frame
16
+
17
+ SCANLINE_FACTOR = 0.7
18
+ GLITCH_CHANCE = 0.3 # per frame
19
+ RECOLOUR_SPEED = 0.15 # hue turns per second
20
+
21
+
22
+ def scanlines(frame: Frame) -> None:
23
+ for row in frame.cells[1::2]:
24
+ for cell in row:
25
+ if cell.char != " ":
26
+ r, g, b = cell.color
27
+ cell.color = RGB(
28
+ int(r * SCANLINE_FACTOR), int(g * SCANLINE_FACTOR), int(b * SCANLINE_FACTOR)
29
+ )
30
+
31
+
32
+ def tear(frame: Frame, rng: random.Random) -> None:
33
+ """Shift one to three bands of rows sideways (blank where they slid away)."""
34
+ width, height = frame.width, frame.height
35
+ for _ in range(rng.randint(1, 3)):
36
+ top = rng.randrange(height)
37
+ shift = rng.choice((-1, 1)) * rng.randint(1, max(1, width // 16))
38
+ for row in frame.cells[top : top + rng.randint(1, max(1, height // 8))]:
39
+ snapshot = [(cell.char, cell.color) for cell in row]
40
+ for x, cell in enumerate(row):
41
+ source = x - shift
42
+ if 0 <= source < width:
43
+ cell.char, cell.color = snapshot[source]
44
+ else:
45
+ cell.char = " "
46
+
47
+
48
+ def recolour(frame: Frame, offset: float) -> None:
49
+ span = max(1, frame.width + frame.height - 2)
50
+ for y, row in enumerate(frame.cells):
51
+ for x, cell in enumerate(row):
52
+ if cell.char != " ":
53
+ r, g, b = cell.color
54
+ level = max(r, g, b) / 255
55
+ cell.color = hsv((x + y) / span + offset, 1.0, 0.3 + 0.7 * level)
56
+
57
+
58
+ @dataclass
59
+ class PostFX:
60
+ crt: bool = False
61
+ glitch: bool = False
62
+ recolour: bool = False
63
+ rng: random.Random = field(default_factory=random.Random, repr=False)
64
+ _hue: float = 0.0
65
+
66
+ def update(self, dt: float) -> None:
67
+ self._hue = (self._hue + dt * RECOLOUR_SPEED) % 1.0
68
+
69
+ def apply(self, frame: Frame) -> None:
70
+ if self.recolour:
71
+ recolour(frame, self._hue)
72
+ if self.crt:
73
+ scanlines(frame)
74
+ if self.glitch and self.rng.random() < GLITCH_CHANCE:
75
+ tear(frame, self.rng)
76
+
77
+ def active(self) -> list[str]:
78
+ return [name for name in ("crt", "glitch", "recolour") if getattr(self, name)]
staticfx/py.typed ADDED
File without changes
staticfx/themes.py ADDED
@@ -0,0 +1,162 @@
1
+ """Colour themes.
2
+
3
+ A theme is a colour ramp from 0.0 (darkest) to 1.0 (brightest) plus an
4
+ accent colour for highlights. Effects compute a brightness per cell and look
5
+ the colour up with :meth:`Theme.ramp`, which is why any effect works with any
6
+ theme.
7
+
8
+ Two themes are animated and rebuilt every frame: ``rainbow`` drifts through
9
+ the hue wheel and ``strobe`` flashes. Strobe is a photosensitivity risk, so
10
+ it is hidden unless the user opts in (see ``Settings.allow_flashing``).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import random
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass, field
18
+
19
+ from staticfx.core.color import RGB, gradient, hsv, parse_hex
20
+
21
+ RAMP_SIZE = 256
22
+
23
+
24
+ @dataclass(eq=False)
25
+ class Theme:
26
+ key: str
27
+ label: str
28
+ accent: RGB
29
+ lut: tuple[RGB, ...] = field(repr=False)
30
+ flashing: bool = False
31
+
32
+ def ramp(self, value: float) -> RGB:
33
+ if value <= 0.0:
34
+ return self.lut[0]
35
+ if value >= 1.0:
36
+ return self.lut[-1]
37
+ return self.lut[int(value * (RAMP_SIZE - 1))]
38
+
39
+ @property
40
+ def primary(self) -> RGB:
41
+ return self.ramp(0.55)
42
+
43
+ @property
44
+ def bright(self) -> RGB:
45
+ return self.lut[-1]
46
+
47
+
48
+ def _lut(curve: Callable[[float], RGB]) -> tuple[RGB, ...]:
49
+ return tuple(curve(i / (RAMP_SIZE - 1)) for i in range(RAMP_SIZE))
50
+
51
+
52
+ def _from_hex(key: str, label: str, accent: str, ramp: str) -> Theme:
53
+ """A theme from an accent colour and evenly spaced ramp colours, darkest first."""
54
+ colours = [parse_hex(code) for code in ramp.split()]
55
+ last = len(colours) - 1
56
+ stops = [(i / last, colour) for i, colour in enumerate(colours)]
57
+ return Theme(key, label, parse_hex(accent), _lut(lambda t: gradient(stops, t)))
58
+
59
+
60
+ # key, label, accent, ramp from dark to bright
61
+ _PALETTES = (
62
+ ("matrix", "Matrix", "#78ff78", "#004614 #00ff46 #dcffdc"),
63
+ ("cyberpunk", "Cyberpunk", "#ff00aa", "#371450 #b400ff #fff5ff"),
64
+ ("ocean", "Ocean", "#50f0ff", "#0a2d4b #00b4ff #dcffff"),
65
+ ("fire", "Fire", "#ffeb46", "#5a1400 #ff4600 #fffad2"),
66
+ ("toxic", "Toxic", "#e6ff50", "#194b00 #64ff00 #f5ffdc"),
67
+ ("sakura", "Sakura", "#ffaadc", "#4b0f32 #ff50aa #fff5fa"),
68
+ ("amber", "Amber", "#ffdc50", "#4b2800 #ffaa00 #fff5c8"),
69
+ ("mono", "Monochrome", "#ffffff", "#373737 #a0a0a0 #ffffff"),
70
+ ("inferno", "Inferno", "#ffc85a", "#0a0000 #55000a #cd200a #ff7a14 #ffe87a"),
71
+ ("arctic", "Arctic", "#98deff", "#000a14 #003e5c #2a98ca #98deff #ffffff"),
72
+ ("rose", "Neon Rose", "#ff6eb4", "#14000a #5a0028 #dc1478 #ff6eb4 #ffdcf0"),
73
+ ("sunset", "Sunset", "#ffb36b", "#120018 #5a1046 #c2305a #ff7a3c #ffd59a"),
74
+ ("vaporwave", "Vaporwave", "#fffb96", "#12002a #5b2a86 #ff71ce #01cdfe #e6fffb"),
75
+ ("dracula", "Dracula", "#50fa7b", "#1e1f29 #6272a4 #bd93f9 #ff79c6 #f8f8f2"),
76
+ ("nord", "Nord", "#a3be8c", "#2e3440 #4c566a #5e81ac #88c0d0 #eceff4"),
77
+ ("gruvbox", "Gruvbox", "#b8bb26", "#1d2021 #665c54 #d79921 #fe8019 #fbf1c7"),
78
+ ("solarized", "Solarized", "#b58900", "#002b36 #073642 #268bd2 #2aa198 #fdf6e3"),
79
+ ("catppuccin", "Catppuccin", "#f9e2af", "#1e1e2e #45475a #89b4fa #cba6f7 #f5e0dc"),
80
+ ("tokyonight", "Tokyo Night", "#9ece6a", "#1a1b26 #414868 #7aa2f7 #bb9af7 #c0caf5"),
81
+ ("forest", "Forest", "#d4ff7a", "#031a0c #0f4d26 #2e8b57 #9acd32 #f0ffe0"),
82
+ ("blood", "Blood Moon", "#ff4040", "#120000 #4a0000 #a00010 #e0202a #ffd0d0"),
83
+ ("gold", "Gold", "#ffe680", "#1a1000 #5c4000 #c99a00 #ffd34d #fff8dc"),
84
+ ("lavender", "Lavender", "#e0c3fc", "#140c1e #3d2b5a #8a6fc4 #c8b6ff #f8f2ff"),
85
+ ("copper", "Copper", "#ffb07a", "#140800 #4d2310 #b5622a #e8955a #ffe4cc"),
86
+ ("bubblegum", "Bubblegum", "#fff07a", "#1a0712 #7a2a5c #ff6fb5 #8ef6ff #ffffff"),
87
+ )
88
+
89
+ STATIC_THEMES = {key: _from_hex(key, *rest) for key, *rest in _PALETTES}
90
+ ANIMATED = ("rainbow", "strobe")
91
+ LABELS = {
92
+ **{k: t.label for k, t in STATIC_THEMES.items()},
93
+ "rainbow": "Rainbow",
94
+ "strobe": "Strobe",
95
+ }
96
+ ALIASES = {
97
+ "monochrome": "mono",
98
+ "cyber": "cyberpunk",
99
+ "arctic blue": "arctic",
100
+ "neon rose": "rose",
101
+ "tokyo night": "tokyonight",
102
+ "blood moon": "blood",
103
+ }
104
+ DEFAULT = "matrix"
105
+
106
+
107
+ def normalize(name: str) -> str:
108
+ """Canonical key for ``name`` (case-insensitive, aliases resolved).
109
+
110
+ Raises ``ValueError`` listing the valid names when there is no such theme.
111
+ """
112
+ key = name.strip().lower()
113
+ key = ALIASES.get(key, key)
114
+ if key not in LABELS:
115
+ raise ValueError(f"unknown theme '{name}' (choose from: {', '.join(LABELS)})")
116
+ return key
117
+
118
+
119
+ def names(allow_flashing: bool = False) -> list[str]:
120
+ return [key for key in LABELS if allow_flashing or key != "strobe"]
121
+
122
+
123
+ def rainbow(position: float) -> Theme:
124
+ """The hue wheel, rotated by ``position`` (advance it over time to animate)."""
125
+
126
+ def curve(t: float) -> RGB:
127
+ saturation = 1.0 if t < 0.92 else max(0.0, 1.0 - (t - 0.92) * 9.0)
128
+ return hsv(position + t * 0.65, saturation, 0.12 + 0.88 * t**0.75)
129
+
130
+ return Theme("rainbow", "Rainbow", hsv(position + 0.5), _lut(curve))
131
+
132
+
133
+ class Strobe:
134
+ """Random hue jumps on a fast irregular beat, with a decaying flash."""
135
+
136
+ def __init__(self, rng: random.Random) -> None:
137
+ self.rng = rng
138
+ self.hue = 0.0
139
+ self.flash = 0.0
140
+ self.white = False
141
+ self._beat = 0.0
142
+
143
+ def update(self, dt: float) -> None:
144
+ self._beat -= dt
145
+ if self._beat <= 0.0:
146
+ self._beat = self.rng.uniform(0.07, 0.2)
147
+ self.hue = self.rng.random()
148
+ self.flash = 1.0
149
+ self.white = self.rng.random() < 0.12
150
+ self.flash *= 0.5 ** (dt * 13.0)
151
+
152
+ def theme(self) -> Theme:
153
+ hue, flash, white = self.hue, self.flash, self.white
154
+
155
+ def curve(t: float) -> RGB:
156
+ if white and flash > 0.5:
157
+ saturation = 0.12
158
+ else:
159
+ saturation = 1.0 if t < 0.93 else max(0.0, 1.0 - (t - 0.93) * 10.0)
160
+ return hsv(hue + t * 0.45, saturation, min(1.0, 0.12 + 0.88 * t**0.7 + flash * 0.35))
161
+
162
+ return Theme("strobe", "Strobe", hsv(hue + 0.5), _lut(curve), flashing=True)
@@ -0,0 +1 @@
1
+ """Screens and the drawing primitives they share."""