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,203 @@
1
+ """Coordinate warps, applied before the layers are sampled.
2
+
3
+ A warp moves the point a layer is sampled at, so it bends, repeats or
4
+ mirrors the whole pattern without the layer knowing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from collections.abc import Callable
11
+
12
+ from staticfx.effects.engine.schema import Kind, Param, Params, registry
13
+
14
+ Warp = Callable[[float, float], tuple[float, float]]
15
+
16
+ sin, cos, hypot, atan2 = math.sin, math.cos, math.hypot, math.atan2
17
+
18
+
19
+ def rotate(p: Params, t: float) -> Warp:
20
+ angle = p["spin"] * t
21
+ c, s = cos(angle), sin(angle)
22
+ return lambda x, y: (x * c - y * s, x * s + y * c)
23
+
24
+
25
+ def zoom(p: Params, t: float) -> Warp:
26
+ factor = p["zoom"] * (1 + p["pulse"] * sin(t * p["pulse_rate"]))
27
+ return lambda x, y: (x * factor, y * factor)
28
+
29
+
30
+ def kaleidoscope(p: Params, t: float) -> Warp:
31
+ wedge = math.tau / p["segments"]
32
+ half = wedge / 2
33
+ spin = p["spin"] * t
34
+
35
+ def warp(x: float, y: float) -> tuple[float, float]:
36
+ angle = atan2(y, x) % wedge
37
+ if angle > half:
38
+ angle = wedge - angle
39
+ r = hypot(x, y)
40
+ return r * cos(angle + spin), r * sin(angle + spin)
41
+
42
+ return warp
43
+
44
+
45
+ def mirror(p: Params, t: float) -> Warp:
46
+ axis = p["axis"]
47
+ if axis == "x":
48
+ return lambda x, y: (abs(x), y)
49
+ if axis == "y":
50
+ return lambda x, y: (x, abs(y))
51
+ return lambda x, y: (abs(x), abs(y))
52
+
53
+
54
+ def tile(p: Params, t: float) -> Warp:
55
+ n, ox, oy = p["tiles"], t * p["drift_x"], t * p["drift_y"]
56
+ return lambda x, y: (((x * n + ox) % 1.0 - 0.5) * 2, ((y * n + oy) % 1.0 - 0.5) * 2)
57
+
58
+
59
+ def swirl(p: Params, t: float) -> Warp:
60
+ twist = p["twist"] * sin(t * 0.7 + 1.0)
61
+
62
+ def warp(x: float, y: float) -> tuple[float, float]:
63
+ angle = twist * math.exp(-hypot(x, y) * 1.5)
64
+ c, s = cos(angle), sin(angle)
65
+ return x * c - y * s, x * s + y * c
66
+
67
+ return warp
68
+
69
+
70
+ def wave(p: Params, t: float) -> Warp:
71
+ amp, freq = p["strength"], p["frequency"]
72
+ return lambda x, y: (x + amp * sin(y * freq + t), y + amp * sin(x * freq + t * 1.3))
73
+
74
+
75
+ def polar(p: Params, t: float) -> Warp:
76
+ return lambda x, y: (hypot(x, y), atan2(y, x) / math.pi)
77
+
78
+
79
+ def fold(p: Params, t: float) -> Warp:
80
+ offset, folds = p["offset"], p["folds"]
81
+ angle = p["angle"] + 0.15 * sin(t * 0.4)
82
+ c, s = cos(angle), sin(angle)
83
+
84
+ def warp(x: float, y: float) -> tuple[float, float]:
85
+ for _ in range(folds):
86
+ x, y = abs(x) - offset, abs(y) - offset
87
+ x, y = x * c - y * s, x * s + y * c
88
+ return x, y
89
+
90
+ return warp
91
+
92
+
93
+ def pixelate(p: Params, t: float) -> Warp:
94
+ q = p["resolution"]
95
+ return lambda x, y: (math.floor(x * q) / q, math.floor(y * q) / q)
96
+
97
+
98
+ def ripple(p: Params, t: float) -> Warp:
99
+ amp, freq, phase = p["strength"] * 0.5, p["frequency"], p["speed"] * t
100
+
101
+ def warp(x: float, y: float) -> tuple[float, float]:
102
+ r = hypot(x, y) + 1e-6
103
+ d = amp * sin(r * freq - phase)
104
+ return x + x / r * d, y + y / r * d
105
+
106
+ return warp
107
+
108
+
109
+ WARPS = registry(
110
+ Kind(
111
+ "rotate",
112
+ "Rotate",
113
+ rotate,
114
+ (Param("spin", "Spin", 0.2, -1.5, 1.5, 0.05),),
115
+ summary="spin the whole pattern",
116
+ ),
117
+ Kind(
118
+ "zoom",
119
+ "Zoom",
120
+ zoom,
121
+ (
122
+ Param("zoom", "Zoom", 1.5, 0.5, 3.0, 0.1),
123
+ Param("pulse", "Pulse", 0.3, 0.0, 0.8, 0.05),
124
+ Param("pulse_rate", "Pulse rate", 0.8, 0.1, 3.0, 0.1),
125
+ ),
126
+ summary="scale in and out, breathing",
127
+ ),
128
+ Kind(
129
+ "kaleidoscope",
130
+ "Kaleidoscope",
131
+ kaleidoscope,
132
+ (
133
+ Param("segments", "Segments", 6, 2, 16, 1, integer=True),
134
+ Param("spin", "Spin", 0.2, -1.0, 1.0, 0.05),
135
+ ),
136
+ summary="mirror into wedges around the centre",
137
+ ),
138
+ Kind(
139
+ "mirror",
140
+ "Mirror",
141
+ mirror,
142
+ (Param("axis", "Axis", "xy", choices=("x", "y", "xy")),),
143
+ summary="reflect across an axis",
144
+ ),
145
+ Kind(
146
+ "tile",
147
+ "Tile",
148
+ tile,
149
+ (
150
+ Param("tiles", "Tiles", 2.0, 1.0, 6.0, 0.25),
151
+ Param("drift_x", "Drift across", 0.2, -1.0, 1.0, 0.05),
152
+ Param("drift_y", "Drift down", 0.1, -1.0, 1.0, 0.05),
153
+ ),
154
+ summary="repeat in a drifting grid",
155
+ ),
156
+ Kind(
157
+ "swirl",
158
+ "Swirl",
159
+ swirl,
160
+ (Param("twist", "Twist", 2.0, -6.0, 6.0, 0.25),),
161
+ summary="twist the middle like stirred paint",
162
+ ),
163
+ Kind(
164
+ "wave",
165
+ "Wave",
166
+ wave,
167
+ (
168
+ Param("strength", "Strength", 0.3, 0.0, 1.0, 0.05),
169
+ Param("frequency", "Frequency", 3.0, 0.5, 10.0, 0.25),
170
+ ),
171
+ summary="wobble sideways in waves",
172
+ ),
173
+ Kind("polar", "Polar", polar, summary="unroll circles into lines"),
174
+ Kind(
175
+ "fold",
176
+ "Fold",
177
+ fold,
178
+ (
179
+ Param("offset", "Offset", 0.3, 0.0, 1.0, 0.05),
180
+ Param("angle", "Angle", 0.7, 0.0, 3.14, 0.05),
181
+ Param("folds", "Folds", 2, 1, 4, 1, integer=True),
182
+ ),
183
+ summary="fold space over on itself",
184
+ ),
185
+ Kind(
186
+ "pixelate",
187
+ "Pixelate",
188
+ pixelate,
189
+ (Param("resolution", "Resolution", 8.0, 2.0, 24.0, 1.0),),
190
+ summary="chunky low-resolution blocks",
191
+ ),
192
+ Kind(
193
+ "ripple",
194
+ "Ripple",
195
+ ripple,
196
+ (
197
+ Param("strength", "Strength", 0.3, 0.0, 1.0, 0.05),
198
+ Param("frequency", "Frequency", 10.0, 2.0, 24.0, 0.5),
199
+ Param("speed", "Speed", 2.0, -6.0, 6.0, 0.25),
200
+ ),
201
+ summary="rings travelling out from the centre",
202
+ ),
203
+ )
@@ -0,0 +1,103 @@
1
+ """Every effect the app can play, in a stable order."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from collections.abc import Iterator
7
+
8
+ from staticfx.effects.base import Effect
9
+ from staticfx.effects.builtin import builtin_specs
10
+ from staticfx.effects.curated import EXCLUDED, GALLERY
11
+ from staticfx.effects.engine import GENERATED_COUNT, describe, generate
12
+ from staticfx.effects.spec import BUILTIN, GENERATED, USER, EffectSpec, recipe_spec
13
+
14
+ GENERATED_CATEGORY = "Generated"
15
+ USER_CATEGORY = "My Effects"
16
+ USER_PREFIX = "my_"
17
+
18
+
19
+ def generated_key(seed: int) -> str:
20
+ return f"proc_{seed:03d}"
21
+
22
+
23
+ class Registry:
24
+ """Built-ins first, then generated effects, then the user's own.
25
+
26
+ Generated effects that failed the quality gate (see ``tools/curate.py``)
27
+ are left out entirely.
28
+ """
29
+
30
+ def __init__(self) -> None:
31
+ self._specs: dict[str, EffectSpec] = {spec.key: spec for spec in builtin_specs()}
32
+ for seed in range(GENERATED_COUNT):
33
+ if seed not in EXCLUDED:
34
+ recipe, label = generate(seed)
35
+ key = generated_key(seed)
36
+ self._specs[key] = recipe_spec(
37
+ key, label, describe(recipe), GENERATED_CATEGORY, GENERATED, recipe
38
+ )
39
+ self.gallery = tuple(generated_key(seed) for seed in GALLERY if seed not in EXCLUDED)
40
+
41
+ def __contains__(self, key: object) -> bool:
42
+ return key in self._specs
43
+
44
+ def __len__(self) -> int:
45
+ return len(self._specs)
46
+
47
+ def __iter__(self) -> Iterator[str]:
48
+ return iter(self._specs)
49
+
50
+ def __getitem__(self, key: str) -> EffectSpec:
51
+ return self._specs[key]
52
+
53
+ def keys(self) -> list[str]:
54
+ return list(self._specs)
55
+
56
+ def specs(self) -> list[EffectSpec]:
57
+ return list(self._specs.values())
58
+
59
+ def count(self, kind: str) -> int:
60
+ return sum(1 for spec in self._specs.values() if spec.kind == kind)
61
+
62
+ def make(
63
+ self, key: str, rng: random.Random, unicode: bool = False, ascii_only: bool = False
64
+ ) -> Effect:
65
+ return self._specs[key].create(rng, unicode=unicode, ascii_only=ascii_only)
66
+
67
+ def resolve(self, name: str | int) -> str:
68
+ """Turn what a user typed into a key; raises ``KeyError`` if nothing matches.
69
+
70
+ Accepts, in order of preference: an exact key (``plasma``, ``proc_042``,
71
+ ``my_sunrise``), the ``proc42`` shorthand, a position in the list, and
72
+ a display name (``"Matrix Rain"``). Built-ins win name clashes, so a
73
+ user effect called "Plasma" never hides the built-in one.
74
+ """
75
+ text = str(name).strip().lower()
76
+ if text in self._specs:
77
+ return text
78
+ if text.startswith("proc") and text[4:].lstrip("_").isdigit():
79
+ key = generated_key(int(text[4:].lstrip("_")))
80
+ if key in self._specs:
81
+ return key
82
+ if text.isdigit() and int(text) < len(self._specs):
83
+ return self.keys()[int(text)]
84
+ for spec in self._specs.values():
85
+ if spec.label.lower() == text:
86
+ return spec.key
87
+ if USER_PREFIX + text in self._specs:
88
+ return USER_PREFIX + text
89
+ raise KeyError(name)
90
+
91
+ def put_user(self, spec: EffectSpec) -> None:
92
+ """Add or replace one of the user's effects."""
93
+ if spec.kind != USER or not spec.key.startswith(USER_PREFIX):
94
+ raise ValueError(f"not a user effect: {spec.key}")
95
+ self._specs[spec.key] = spec
96
+
97
+ def remove_user(self, key: str) -> None:
98
+ if self._specs[key].kind != USER:
99
+ raise ValueError(f"only your own effects can be removed, not {key}")
100
+ del self._specs[key]
101
+
102
+
103
+ __all__ = ["BUILTIN", "GENERATED", "GENERATED_CATEGORY", "USER", "USER_CATEGORY", "Registry"]
@@ -0,0 +1,51 @@
1
+ """What the registry knows about an effect before it is created."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+
9
+ from staticfx.effects.base import Effect
10
+ from staticfx.effects.engine import EngineEffect, Recipe
11
+
12
+ Factory = Callable[..., Effect]
13
+
14
+ BUILTIN, GENERATED, USER = "builtin", "generated", "user"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class EffectSpec:
19
+ key: str
20
+ label: str
21
+ description: str
22
+ category: str
23
+ factory: Factory
24
+ kind: str = BUILTIN
25
+ tags: tuple[str, ...] = ()
26
+ recipe: Recipe | None = None
27
+
28
+ @property
29
+ def editable(self) -> bool:
30
+ """Recipe effects can be opened in the Studio; hand-written built-ins can't."""
31
+ return self.recipe is not None
32
+
33
+ def create(self, rng: random.Random, unicode: bool = False, ascii_only: bool = False) -> Effect:
34
+ effect = self.factory(rng, unicode=unicode and not ascii_only)
35
+ effect.ascii_only = ascii_only
36
+ return effect
37
+
38
+ def search_text(self) -> str:
39
+ words = (self.label, self.key, self.category, self.description, *self.tags)
40
+ return " ".join(words).lower()
41
+
42
+
43
+ def recipe_spec(
44
+ key: str, label: str, description: str, category: str, kind: str, recipe: Recipe
45
+ ) -> EffectSpec:
46
+ """A spec for an effect drawn by the procedural engine."""
47
+
48
+ def factory(rng: random.Random, unicode: bool = False) -> Effect:
49
+ return EngineEffect(rng, unicode, recipe=recipe)
50
+
51
+ return EffectSpec(key, label, description, category, factory, kind, recipe=recipe)
@@ -0,0 +1,48 @@
1
+ """System information (fastfetch / neofetch) drawn over an effect."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+
9
+ from staticfx.core.frame import Frame
10
+ from staticfx.themes import Theme
11
+
12
+ TOOLS = {"fastfetch": ["fastfetch", "--pipe"], "neofetch": ["neofetch", "--stdout"]}
13
+ ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
14
+ TIMEOUT = 10
15
+
16
+
17
+ def system_info(tool: str | None = None) -> str:
18
+ """Output of ``tool`` (or the first one installed), without colour codes.
19
+
20
+ Raises ``RuntimeError`` with a readable message if nothing usable is installed.
21
+ """
22
+ names = [tool] if tool else list(TOOLS)
23
+ for name in names:
24
+ if shutil.which(name):
25
+ try:
26
+ result = subprocess.run(
27
+ TOOLS[name], capture_output=True, text=True, timeout=TIMEOUT, check=True
28
+ )
29
+ except (OSError, subprocess.SubprocessError) as exc:
30
+ raise RuntimeError(f"{name} failed: {exc}") from None
31
+ return ANSI.sub("", result.stdout).expandtabs()
32
+ wanted = tool or "fastfetch or neofetch"
33
+ raise RuntimeError(f"{wanted} is not installed")
34
+
35
+
36
+ def overlay(frame: Frame, theme: Theme, text: str) -> None:
37
+ """Dim the effect and print ``text`` over it, vertically centred on the left."""
38
+ frame.dim(0.35)
39
+ lines = [line.rstrip() for line in text.strip("\n").splitlines()]
40
+ top = max(0, (frame.height - len(lines)) // 2)
41
+ for y, line in enumerate(lines[: frame.height], top):
42
+ frame.fill(2, y, len(line) + 2, 1)
43
+ label, sep, value = line.partition(":")
44
+ if sep and len(label) < 24: # "OS: Arch Linux": colour the label
45
+ frame.text(3, y, label + sep, theme.accent)
46
+ frame.text(4 + len(label), y, value, theme.bright)
47
+ else:
48
+ frame.text(3, y, line, theme.bright)
@@ -0,0 +1 @@
1
+ """Everything the user saves: settings, their own effects and their looks."""
@@ -0,0 +1,122 @@
1
+ """Settings, kept in ``config.json``.
2
+
3
+ Loading never fails: a missing file gives the defaults, and any value that
4
+ is the wrong type or out of range is replaced by its default with a warning.
5
+ A hand-edited typo can't stop the app from starting.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from dataclasses import asdict, dataclass, field, fields
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from staticfx import themes
16
+ from staticfx.library.files import atomic_write
17
+
18
+ VERSION = 3
19
+ CHARACTERS = ("auto", "katakana", "ascii")
20
+ COLOURS = ("auto", "truecolor", "256")
21
+ FPS_RANGE = (5, 60)
22
+ SPEED_RANGE = (0.1, 5.0)
23
+ AUTO_RANGE = (3.0, 600.0)
24
+ LIST_LIMIT = 500
25
+
26
+
27
+ @dataclass
28
+ class Settings:
29
+ effect: str = "matrix"
30
+ theme: str = themes.DEFAULT
31
+ speed: float = 1.0
32
+ fps: int = 30
33
+ crt: bool = False
34
+ glitch: bool = False
35
+ recolour: bool = False
36
+ characters: str = "auto" # "auto", "katakana" or "ascii"
37
+ colour: str = "auto" # "auto", "truecolor" or "256"
38
+ allow_flashing: bool = False # unlocks the Strobe theme
39
+ auto_seconds: float = 12.0 # how long each effect plays in auto-cycle
40
+ favorites: list[str] = field(default_factory=list)
41
+ recent: list[str] = field(default_factory=list)
42
+ keybinds: dict[str, str] = field(default_factory=dict) # only the user's changes
43
+ seen_welcome: bool = False
44
+ imported_plugins: bool = False # 1.x plugins folder already copied into effects/
45
+
46
+ def to_json(self) -> str:
47
+ return json.dumps({"version": VERSION, **asdict(self)}, indent=2) + "\n"
48
+
49
+
50
+ def _migrate(data: dict[str, Any]) -> dict[str, Any]:
51
+ """Rename 1.x keys to their current names."""
52
+ data = dict(data)
53
+ if "rainbow" in data:
54
+ data.setdefault("recolour", data.pop("rainbow"))
55
+ if data.pop("use_256_color", False):
56
+ data.setdefault("colour", "256")
57
+ if data.pop("unicode", False):
58
+ data.setdefault("characters", "katakana")
59
+ if data.get("version", 1) < 2:
60
+ data.pop("keybinds", None) # 1.x saved the whole key map, which pinned old defaults
61
+ return data
62
+
63
+
64
+ def _check(name: str, value: Any, default: Any) -> Any:
65
+ """``value`` cleaned up for setting ``name``; raises ``ValueError`` if unusable."""
66
+ if name == "theme":
67
+ return themes.normalize(str(value))
68
+ if name in ("characters", "colour"):
69
+ options = CHARACTERS if name == "characters" else COLOURS
70
+ if value not in options:
71
+ raise ValueError(f"must be one of {', '.join(options)}")
72
+ return value
73
+ if isinstance(default, bool):
74
+ if not isinstance(value, bool):
75
+ raise ValueError("must be true or false")
76
+ return value
77
+ if isinstance(default, (int, float)):
78
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
79
+ raise ValueError("must be a number")
80
+ low, high = {"fps": FPS_RANGE, "speed": SPEED_RANGE, "auto_seconds": AUTO_RANGE}[name]
81
+ value = min(high, max(low, value))
82
+ return int(value) if isinstance(default, int) else float(value)
83
+ if isinstance(default, list):
84
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
85
+ raise ValueError("must be a list of effect names")
86
+ return list(dict.fromkeys(value))[:LIST_LIMIT]
87
+ if isinstance(default, dict):
88
+ if not isinstance(value, dict):
89
+ raise ValueError('must be an object like {"y": "crt"}')
90
+ return {str(k): str(v) for k, v in value.items()}
91
+ if not isinstance(value, str) or not value:
92
+ raise ValueError("must be a non-empty string")
93
+ return value
94
+
95
+
96
+ def load(path: Path) -> tuple[Settings, list[str]]:
97
+ """Read ``path``. Returns the settings and warnings about anything ignored."""
98
+ settings = Settings()
99
+ if not path.exists():
100
+ return settings, []
101
+ try:
102
+ data = json.loads(path.read_text(encoding="utf-8"))
103
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
104
+ return settings, [f"{path.name} is unreadable ({exc}); using default settings"]
105
+ if not isinstance(data, dict):
106
+ return settings, [f"{path.name} is not a JSON object; using default settings"]
107
+
108
+ warnings = []
109
+ data = _migrate(data)
110
+ for f in fields(Settings):
111
+ if f.name not in data:
112
+ continue
113
+ default = getattr(settings, f.name)
114
+ try:
115
+ setattr(settings, f.name, _check(f.name, data[f.name], default))
116
+ except ValueError as exc:
117
+ warnings.append(f"{path.name}: ignoring '{f.name}' ({exc})")
118
+ return settings, warnings
119
+
120
+
121
+ def save(settings: Settings, path: Path) -> None:
122
+ atomic_write(path, settings.to_json())
@@ -0,0 +1,159 @@
1
+ """The user's own effects: ``.sfx`` files in ``<data dir>/effects``.
2
+
3
+ A ``.sfx`` file is JSON (documented in ``docs/EFFECT_FORMAT.md``)::
4
+
5
+ {"format": "staticfx-effect", "version": 3, "name": "Neon Sunrise",
6
+ "description": "", "created": "2026-11-07", "recipe": {...}}
7
+
8
+ The file name is the effect's identity: ``neon_sunrise.sfx`` plays as
9
+ ``my_neon_sunrise``. Files from StaticFX 1.x are converted when read.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import time
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from staticfx.effects.engine import Recipe
21
+ from staticfx.library.files import atomic_write, clean_name, slugify
22
+ from staticfx.library.legacy import recipe_from_plugin, recipe_from_v2
23
+
24
+ FORMAT = "staticfx-effect"
25
+ VERSION = 3
26
+ SUFFIX = ".sfx"
27
+ DESCRIPTION_LIMIT = 200
28
+
29
+
30
+ @dataclass
31
+ class UserEffect:
32
+ id: str
33
+ name: str
34
+ recipe: Recipe
35
+ description: str = ""
36
+ created: str = field(default_factory=lambda: time.strftime("%Y-%m-%d"))
37
+
38
+ @property
39
+ def key(self) -> str:
40
+ return f"my_{self.id}"
41
+
42
+ def to_json(self) -> str:
43
+ data = {
44
+ "format": FORMAT,
45
+ "version": VERSION,
46
+ "name": self.name,
47
+ "description": self.description,
48
+ "created": self.created,
49
+ "recipe": self.recipe.to_dict(),
50
+ }
51
+ return json.dumps(data, indent=2) + "\n"
52
+
53
+
54
+ def parse(text: str, ident: str) -> UserEffect:
55
+ """Read any supported ``.sfx`` version. Raises ``ValueError`` explaining what's wrong."""
56
+ try:
57
+ data: Any = json.loads(text)
58
+ except json.JSONDecodeError as exc:
59
+ raise ValueError(f"not valid JSON (line {exc.lineno}: {exc.msg})") from None
60
+ if not isinstance(data, dict):
61
+ raise ValueError("not a StaticFX effect file")
62
+
63
+ if data.get("format") == "sfx": # a 1.x plugin
64
+ name = clean_name(str(data.get("name") or ident))
65
+ return UserEffect(ident, name, recipe_from_plugin(data), str(data.get("description", "")))
66
+ if data.get("format") != FORMAT:
67
+ raise ValueError("not a StaticFX effect file")
68
+
69
+ version = data.get("version", 0)
70
+ if not isinstance(version, int) or version < 2:
71
+ raise ValueError(f"unsupported version {version!r}")
72
+ if version > VERSION:
73
+ raise ValueError("made by a newer StaticFX - please upgrade")
74
+ recipe = (
75
+ Recipe.from_dict(data.get("recipe"))
76
+ if version == VERSION
77
+ else recipe_from_v2(data.get("recipe"))
78
+ )
79
+
80
+ return UserEffect(
81
+ id=ident,
82
+ name=clean_name(str(data.get("name", ""))) or "Untitled",
83
+ recipe=recipe,
84
+ description=str(data.get("description", ""))[:DESCRIPTION_LIMIT],
85
+ created=str(data.get("created", "")),
86
+ )
87
+
88
+
89
+ class EffectLibrary:
90
+ def __init__(self, directory: Path) -> None:
91
+ self.directory = directory
92
+
93
+ def path(self, ident: str) -> Path:
94
+ return self.directory / f"{ident}{SUFFIX}"
95
+
96
+ def unique_id(self, name: str) -> str:
97
+ """A file stem for ``name`` that isn't taken yet (``sunrise``, ``sunrise_2``, ...).
98
+
99
+ A leading "my" is dropped, so "My Sunrise" plays as ``my_sunrise``
100
+ rather than ``my_my_sunrise``.
101
+ """
102
+ base = slugify(name)
103
+ if base.startswith("my_") and len(base) > 3:
104
+ base = base[3:]
105
+ ident, number = base, 2
106
+ while self.path(ident).exists():
107
+ ident, number = f"{base}_{number}", number + 1
108
+ return ident
109
+
110
+ def load(self) -> tuple[list[UserEffect], list[str]]:
111
+ """Every readable effect, plus a message for each file that wasn't."""
112
+ effects: list[UserEffect] = []
113
+ problems: list[str] = []
114
+ if not self.directory.is_dir():
115
+ return effects, problems
116
+ for path in sorted(self.directory.glob(f"*{SUFFIX}")):
117
+ try:
118
+ effects.append(parse(path.read_text(encoding="utf-8"), path.stem))
119
+ except (OSError, UnicodeDecodeError, ValueError) as exc:
120
+ problems.append(f"{path.name}: {exc}")
121
+ return effects, problems
122
+
123
+ def save(self, effect: UserEffect) -> Path:
124
+ path = self.path(effect.id)
125
+ atomic_write(path, effect.to_json())
126
+ return path
127
+
128
+ def delete(self, ident: str) -> None:
129
+ self.path(ident).unlink(missing_ok=True)
130
+
131
+ def import_file(self, source: Path) -> UserEffect:
132
+ """Validate ``source`` and copy it in under a fresh id (never overwriting)."""
133
+ try:
134
+ text = source.read_text(encoding="utf-8")
135
+ except (OSError, UnicodeDecodeError) as exc:
136
+ raise ValueError(f"can't read {source}: {exc}") from None
137
+ effect = parse(text, "imported")
138
+ effect.id = self.unique_id(effect.name)
139
+ self.save(effect)
140
+ return effect
141
+
142
+ def import_legacy_plugins(self, folder: Path) -> tuple[int, list[str]]:
143
+ """Copy 1.x plugins from ``folder`` into the library. Returns (count, problems)."""
144
+ count, problems = 0, []
145
+ for path in sorted(folder.glob(f"*{SUFFIX}")) if folder.is_dir() else []:
146
+ try:
147
+ effect = parse(path.read_text(encoding="utf-8"), path.stem)
148
+ except (OSError, UnicodeDecodeError, ValueError) as exc:
149
+ problems.append(f"plugins/{path.name}: {exc}")
150
+ continue
151
+ effect.id = self.unique_id(effect.name)
152
+ self.save(effect)
153
+ count += 1
154
+ return count, problems
155
+
156
+
157
+ def export(effect: UserEffect, destination: Path) -> Path:
158
+ atomic_write(destination, effect.to_json())
159
+ return destination