mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-01 16:58:06 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d69dfbbaee | ||
|
|
ec96422803 | ||
|
|
8d57a748a7 | ||
|
|
e2acbfb566 | ||
|
|
3872a68ff7 | ||
|
|
989162d28f | ||
|
|
cdf03fb107 | ||
|
|
6a9d8014e5 | ||
|
|
c90129285c |
@@ -48,3 +48,4 @@ config/backups/
|
||||
|
||||
# Starlark apps runtime storage (installed .star files and cached renders)
|
||||
/starlark-apps/
|
||||
skin_renders/
|
||||
|
||||
@@ -31,6 +31,14 @@
|
||||
- Plugin configs stored in `config/config.json`, NOT in plugin directories — safe across reinstalls
|
||||
- Third-party plugins can use their own repo URL with empty `plugin_path`
|
||||
|
||||
## Skin System (visual overlays for sports scoreboards)
|
||||
- Skins live in `skins/<skin-id>/` (skin.json + skin.py), NOT in plugin dirs — plugin reinstall deletes plugin dirs
|
||||
- Core: `src/skin_system/` (ScoreboardSkin, SkinContext, runtime); hook: `SportsCore._render_game()` in `src/base_classes/sports.py`
|
||||
- Skins render onto `ctx.canvas` only; fallback to built-in renderer on `False`/exception (3 strikes disables for session)
|
||||
- View-model guaranteed keys are frozen (see `test/test_skin_system.py::TestViewModelContract`) — renaming keys in `_extract_game_details_common` or sport extractors breaks published skins
|
||||
- Validate skins headlessly: `python scripts/validate_skin.py --skin <id>`; docs: `docs/SKIN_SYSTEM.md`, `docs/CREATING_SKINS.md`
|
||||
- Skins are NOT monorepo plugins: no manifest bump / update_registry.py needed
|
||||
|
||||
## Common Pitfalls
|
||||
- paho-mqtt 2.x needs `callback_api_version=mqtt.CallbackAPIVersion.VERSION1` for v1 compat
|
||||
- BasePlugin uses `get_logger()` from `src.logging_config`, not standard `logging.getLogger()`
|
||||
|
||||
@@ -440,6 +440,16 @@ See the [Plugin Store documentation](https://github.com/ChuckBuilds/ledmatrix-pl
|
||||
|
||||
For plugin development, check out the [Hello World Plugin](https://github.com/ChuckBuilds/ledmatrix-hello-world) repository as a starter template.
|
||||
|
||||
### Visual Skins for Scoreboards
|
||||
|
||||
Want a different look for a sports scoreboard without forking the plugin?
|
||||
**Skins** restyle the live/recent/upcoming screens while the plugin keeps
|
||||
handling data, scheduling, caching, and vegas mode. Install one with
|
||||
`git clone <skin repo> skins/<skin-id>`, select it in the plugin's config,
|
||||
and you're done — see [docs/SKIN_SYSTEM.md](docs/SKIN_SYSTEM.md) (how it
|
||||
works) and [docs/CREATING_SKINS.md](docs/CREATING_SKINS.md) (build your own,
|
||||
including a ready-made Claude Code prompt).
|
||||
|
||||
2. **Built-in Managers Deprecated**: The built-in managers (hockey, football, stocks, etc.) are now deprecated and have been moved to the plugin system. **You must install replacement plugins from the Plugin Store** in the web interface instead. The plugin system provides the same functionality with better maintainability and extensibility.
|
||||
</details>
|
||||
|
||||
|
||||
@@ -130,7 +130,18 @@
|
||||
"plugin_order": [],
|
||||
"excluded_plugins": [],
|
||||
"target_fps": 125,
|
||||
"buffer_ahead": 2
|
||||
"buffer_ahead": 2,
|
||||
"intra_plugin_gap": 8,
|
||||
"auto_trim": true,
|
||||
"trim_threshold": 10,
|
||||
"content_padding": 8,
|
||||
"min_plugin_width": 8,
|
||||
"lead_in_width": 0,
|
||||
"plugins_per_cycle": 6,
|
||||
"max_plugin_width_ratio": 3.0,
|
||||
"dynamic_duration_enabled": true,
|
||||
"min_cycle_duration": 60,
|
||||
"max_cycle_duration": 240
|
||||
}
|
||||
},
|
||||
"sync": {
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
# Creating Skins
|
||||
|
||||
A skin restyles a sports scoreboard (live / recent / upcoming) without
|
||||
forking the plugin: the plugin keeps fetching data, scheduling, caching, and
|
||||
doing vegas mode; your skin only draws. Architecture background:
|
||||
[SKIN_SYSTEM.md](SKIN_SYSTEM.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp -r skins/example-classic-baseball skins/my-skin
|
||||
# edit skins/my-skin/skin.json -> set id ("my-skin"), name, author, class_name
|
||||
# edit skins/my-skin/skin.py -> rename the class, start restyling
|
||||
python scripts/validate_skin.py --skin my-skin
|
||||
```
|
||||
|
||||
The validator renders your skin against bundled fixture games at several
|
||||
panel sizes with **no hardware, no network, no running service**, saves PNGs
|
||||
(plus 4x previews) to `skin_renders/`, and fails loudly on errors. Iterate:
|
||||
edit → validate → look at the PNGs.
|
||||
|
||||
To see it on your matrix, add to your plugin's section in `config/config.json`:
|
||||
|
||||
```json
|
||||
"baseball-scoreboard": {
|
||||
"skin": "my-skin",
|
||||
"skin_options": { }
|
||||
}
|
||||
```
|
||||
|
||||
or pick it from the **Visual Skin** dropdown in the web UI (it appears once a
|
||||
matching skin is installed). `"skin"` also accepts a per-mode mapping:
|
||||
`{"live": "my-skin", "recent": "built-in"}`.
|
||||
|
||||
## The manifest (`skin.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-skin",
|
||||
"name": "My Skin",
|
||||
"version": "1.0.0",
|
||||
"author": "you",
|
||||
"description": "What it looks like",
|
||||
"skin_api_version": "1.0.0",
|
||||
"targets": {
|
||||
"sports": ["baseball"],
|
||||
"sport_keys": ["mlb", "milb"],
|
||||
"plugins": []
|
||||
},
|
||||
"entry_point": "skin.py",
|
||||
"class_name": "MySkin",
|
||||
"modes": ["live", "recent", "upcoming"],
|
||||
"preview": "preview.png"
|
||||
}
|
||||
```
|
||||
|
||||
Field notes: `id` must equal the directory name; `skin_api_version`'s major
|
||||
version must match the host's `SKIN_API_VERSION` or the skin is refused at
|
||||
load; `targets` takes sport families (`sports`), exact sport keys
|
||||
(`sport_keys`), and/or exact plugin ids (`plugins`) — any match applies.
|
||||
|
||||
## The renderer (`skin.py`)
|
||||
|
||||
```python
|
||||
from src.skin_system.skin_base import ScoreboardSkin, SkinContext
|
||||
|
||||
class MySkin(ScoreboardSkin):
|
||||
def render_live(self, ctx: SkinContext, game: dict) -> bool:
|
||||
score = f"{game.get('away_score', '0')}-{game.get('home_score', '0')}"
|
||||
fit = ctx.layout.fit_text(score, ctx.layout.bounds)
|
||||
ctx.draw_fit(fit, ctx.layout.bounds)
|
||||
return True # True = "I drew it"; False = use the built-in layout
|
||||
```
|
||||
|
||||
Implement only the modes you care about — anything else falls back to the
|
||||
plugin's built-in rendering. Return `False` to decline a specific game (e.g.
|
||||
a layout that only makes sense while a game is live).
|
||||
|
||||
### The rules (they keep your skin from breaking the display)
|
||||
|
||||
1. **Draw only onto `ctx.canvas`** (via the helpers or `ctx.draw`). Never
|
||||
reassign `ctx.canvas`, never touch the display or call any update method.
|
||||
2. **No I/O in render paths.** No network, no file loads per frame —
|
||||
`render_live` runs every display pass, and a slow render stalls the whole
|
||||
matrix (the host warns at >150 ms). Use `ctx.load_logo` (cached) and
|
||||
`cache_key=` for images.
|
||||
3. **Derive everything from `(ctx, game)`.** Skins must be stateless: the
|
||||
live/recent/upcoming modes each get their own instance.
|
||||
4. **Always `.get()` optional keys.** Only the guaranteed keys below are
|
||||
promised to exist.
|
||||
5. **Never hardcode pixel positions for the panel.** Use `ctx.width`/
|
||||
`ctx.height`, `ctx.layout` regions and `fit_text` — your skin will be run
|
||||
at sizes you didn't test (64x32, 128x64, vegas cards).
|
||||
6. **No third-party dependencies.** Stdlib + PIL + what `ctx` provides.
|
||||
|
||||
A skin that raises 3 renders in a row is disabled until the service restarts
|
||||
(the built-in layout takes over), so a bug is cosmetic — but check your logs.
|
||||
|
||||
## SkinContext reference
|
||||
|
||||
| Member | What it is |
|
||||
|---|---|
|
||||
| `ctx.canvas` / `ctx.draw` | Fresh RGB `PIL.Image` at display size + its `ImageDraw` (raw-PIL escape hatch) |
|
||||
| `ctx.width`, `ctx.height` | Canvas size — the only size truth |
|
||||
| `ctx.layout` | `LayoutContext` (see [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md)): `bounds`, `fit_text`, `fit_text_proportional`, `fit_image`, `px`, `by_tier` |
|
||||
| `ctx.draw_fit(fit, box, color, align, valign)` | Draw a `fit_text` result aligned in a `Region` (handles BDF fonts) |
|
||||
| `ctx.draw_text(text, x, y, color, font)` | Positioned text (handles BDF fonts) |
|
||||
| `ctx.draw_image(img, box, mode, align, valign, cache_key)` | Fit + paste an image with alpha; no-ops on `None` |
|
||||
| `ctx.load_logo("home" \| "away")` | Team logo as RGBA, or `None` (always handle `None`). Cached after first use; see note below |
|
||||
| `ctx.draw_text_outlined(text, (x, y), font, fill, outline_color)` | The classic scorebug outlined text (TTF fonts only) |
|
||||
| `ctx.fonts` | The host's font dict — keys `score`, `time`, `team`, `status`, `detail`, `rank` |
|
||||
| `ctx.options` | Your user's `skin_options` from config |
|
||||
| `ctx.sport`, `ctx.view_model_version`, `ctx.logger` | Context metadata + logger |
|
||||
|
||||
**A note on `ctx.load_logo` vs the no-I/O rule:** `load_logo` is the one
|
||||
sanctioned exception. It goes through the host's logo cache — after the
|
||||
first call per team it's a pure in-memory lookup. If a logo file is missing
|
||||
on disk, the *first* call may download it, exactly like the built-in
|
||||
renderer does for the same game (a skin is never worse than built-in here).
|
||||
Always pass a stable `cache_key` when drawing it, never load image files
|
||||
yourself in a render path, and always handle `None`.
|
||||
|
||||
The default layout idiom — carve regions, then fit text into them:
|
||||
|
||||
```python
|
||||
from src.adaptive_layout import scoreboard_regions
|
||||
|
||||
regions = scoreboard_regions(ctx.layout.bounds, ctx=ctx.layout)
|
||||
ctx.draw_image(ctx.load_logo("away"), regions.away_slot, cache_key=f"logo:{game.get('away_abbr')}")
|
||||
ctx.draw_image(ctx.load_logo("home"), regions.home_slot, cache_key=f"logo:{game.get('home_abbr')}")
|
||||
fit = ctx.layout.fit_text("3-5", regions.score_area)
|
||||
ctx.draw_fit(fit, regions.score_area)
|
||||
```
|
||||
|
||||
`Region` supports `split_h`/`split_v`/`inset`/`top_band`/`bottom_band`/
|
||||
`left_col`/`right_col` for custom carves. Raw `ctx.draw.rectangle/polygon/
|
||||
ellipse/...` is always available for custom marks (see the bases diamond in
|
||||
the example skin).
|
||||
|
||||
## The game view model
|
||||
|
||||
Guaranteed for every sport (view model v1.0 — renaming these breaks skins and
|
||||
is treated as a breaking change upstream):
|
||||
|
||||
| Key | Notes |
|
||||
|---|---|
|
||||
| `id` | Event id (string) |
|
||||
| `status_text` | Display-ready status, e.g. `"Final"`, `"7:30 PM"`, `"Bot 7th"` |
|
||||
| `is_live`, `is_final`, `is_upcoming`, `is_halftime` | Booleans |
|
||||
| `game_date`, `game_time` | Pre-formatted local date/time strings |
|
||||
| `start_time_utc` | UTC `datetime` |
|
||||
| `home_abbr`, `away_abbr` | Team abbreviations (can be 2–5 chars — fit, don't assume) |
|
||||
| `home_id`, `away_id` | Team ids |
|
||||
| `home_score`, `away_score` | **Strings**, not ints |
|
||||
| `home_record`, `away_record` | `"58-33"` or `""` (0-0 records are blanked) |
|
||||
| `home_logo_path`, `away_logo_path` | Prefer `ctx.load_logo` over touching these |
|
||||
|
||||
Sport extras (present for that sport, still `.get()` defensively):
|
||||
|
||||
- **baseball**: `inning` (int), `inning_half` (`"top"`/`"bottom"`), `balls`,
|
||||
`strikes`, `outs` (ints), `bases_occupied` (`[first, second, third]`
|
||||
booleans), `series_summary` (str)
|
||||
- **football**: `period`, `period_text`, `clock`, `home_timeouts`,
|
||||
`away_timeouts`, `down_distance_text`, `down_distance_text_long`,
|
||||
`is_redzone`, `possession`, `possession_indicator` (`"home"`/`"away"`),
|
||||
`scoring_event`
|
||||
- **basketball**: `period`, `period_text`, `clock`
|
||||
- **hockey**: `period`, `period_text`, `clock`, `power_play`, `penalties`,
|
||||
`home_shots`, `away_shots`
|
||||
|
||||
Optional everywhere (only when the user enabled the feature): `odds` (dict),
|
||||
`series_summary`, rankings-related fields.
|
||||
|
||||
Fixture copies of these dicts live in `src/skin_system/fixtures/` — that's
|
||||
exactly what the validator feeds your skin.
|
||||
|
||||
## Vegas mode
|
||||
|
||||
You get vegas support for free: vegas captures the normal display output,
|
||||
which is already your skin's rendering. Optionally implement
|
||||
`render_vegas_card(ctx, game)` to return a purpose-built card at
|
||||
`ctx.width x ctx.height` (sizes vary — never assume 128x32).
|
||||
|
||||
## Building a skin with Claude Code
|
||||
|
||||
Skins are ideal Claude Code projects: small, isolated, and verifiable with
|
||||
one command. Paste this to start:
|
||||
|
||||
> You are building a **display skin** for LEDMatrix — a visual overlay for a
|
||||
> sports scoreboard on a small LED matrix (commonly 128x32 or 64x32 pixels).
|
||||
> First read `docs/CREATING_SKINS.md` and the reference skin in
|
||||
> `skins/example-classic-baseball/`.
|
||||
>
|
||||
> Rules:
|
||||
> - Create/modify files ONLY under `skins/<my-skin-id>/`. Do NOT modify
|
||||
> anything in `src/`, `scripts/`, the plugins, or any other skin.
|
||||
> - Render only from the `game` dict and `ctx` helpers. No network calls, no
|
||||
> per-frame file I/O, no new pip dependencies, no touching the display —
|
||||
> draw onto `ctx.canvas` and return True.
|
||||
> - Use `ctx.layout` regions and `fit_text` for positioning so the skin works
|
||||
> at any panel size; use `.get()` for every optional game key.
|
||||
> - After every change run
|
||||
> `python scripts/validate_skin.py --skin <my-skin-id>` and LOOK at the
|
||||
> PNGs it writes to `skin_renders/` (the `_x4.png` files are easiest to
|
||||
> read). Iterate until it passes and looks right at both 128x32 and 64x32.
|
||||
>
|
||||
> What I want it to look like: <describe your layout — where logos, score,
|
||||
> status go; colors; what shows during live vs upcoming vs final>
|
||||
|
||||
Tips that keep Claude (and you) out of trouble:
|
||||
|
||||
- One mode at a time: get `render_live` right before touching the others —
|
||||
unimplemented modes automatically use the built-in look.
|
||||
- Ask for edge-case renders: long team abbreviations, missing logos
|
||||
(`ctx.load_logo` returning `None`), 0-0 records, extra innings/OT.
|
||||
- If the render looks cramped at 64x32, ask Claude to use
|
||||
`ctx.layout.by_tier(...)` to drop elements on small panels rather than
|
||||
shrinking everything.
|
||||
- Never let it "fix" a problem by editing `src/` — if the skin can't do
|
||||
something within its directory, that's a feature request, not a workaround.
|
||||
|
||||
## Pre-publish checklist
|
||||
|
||||
- [ ] `python scripts/validate_skin.py --skin <id> --size 128x32 --size 64x32 --size 128x64` passes
|
||||
- [ ] Looked at every PNG in `skin_renders/` — nothing clipped or overlapping
|
||||
- [ ] Handles a missing logo (`None`) without crashing — temporarily point a
|
||||
fixture's logo path at a nonexistent file to test
|
||||
- [ ] Long abbreviations (`"TA&M"`, 4–5 chars) don't overflow
|
||||
- [ ] No render warning above the time budget
|
||||
- [ ] `skin.json`: `id` matches the directory, `version` set,
|
||||
`skin_api_version` matches the host, targets correct
|
||||
- [ ] `preview.png` added (grab your favorite `_x4` render)
|
||||
- [ ] Tested on real hardware if you have it — a Pi is much slower than your
|
||||
dev machine
|
||||
|
||||
Distribute by publishing the directory as a git repo (users
|
||||
`git clone <repo> skins/<id>`), or submit it to the plugin registry as an
|
||||
entry with `"type": "skin"` (see [SKIN_SYSTEM.md](SKIN_SYSTEM.md) §Distribution).
|
||||
|
||||
**Trust note:** a skin is Python running inside the display service — the
|
||||
same trust level as a plugin. Review code before installing skins from
|
||||
others.
|
||||
@@ -10,6 +10,12 @@ This guide explains how to set up a development workflow for plugins that are ma
|
||||
> scale. Existing plugins keep their classic rendering unless they adopt
|
||||
> those APIs; nothing migrates automatically.
|
||||
|
||||
> **Just want a different look for an existing sports scoreboard?** You may
|
||||
> not need a plugin at all — a **skin** restyles the live/recent/upcoming
|
||||
> rendering while the plugin keeps handling data, scheduling, caching, and
|
||||
> vegas mode, in ~100 lines of drawing code. See
|
||||
> [CREATING_SKINS.md](CREATING_SKINS.md).
|
||||
|
||||
## Overview
|
||||
|
||||
When developing plugins in separate repositories, you need a way to:
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# Skin System Architecture
|
||||
|
||||
Skins are user-installable **visual overlays** for the sports scoreboards.
|
||||
A skin replaces only the *look* of a scoreboard — the host plugin keeps doing
|
||||
data fetching, scheduling, caching, dedup, live-priority takeover, and vegas
|
||||
mode. If you only want to **build** a skin, read
|
||||
[CREATING_SKINS.md](CREATING_SKINS.md); this document explains how the system
|
||||
works and why it is shaped this way.
|
||||
|
||||
## Why skins instead of forks
|
||||
|
||||
Before skins, changing a scoreboard's layout meant forking the whole plugin
|
||||
(e.g. the community MLB scoreboard fork). The fork gets the new look but loses
|
||||
everything the maintained plugin keeps earning: duration/scheduling behavior,
|
||||
vegas mode support, caching and background-fetch improvements, bug fixes. It
|
||||
also silently drifts: every upstream improvement now has to be re-ported by
|
||||
hand.
|
||||
|
||||
A skin inverts that trade. The plugin remains stock and keeps updating through
|
||||
the store; the skin is ~100 lines of pure rendering code that receives the
|
||||
plugin's already-fetched data each frame. Uninstalling the skin (or the skin
|
||||
crashing) simply restores the built-in look.
|
||||
|
||||
```text
|
||||
(unchanged) (the skin seam)
|
||||
ESPN API ──► update() ──► game view model ──► _render_game() ──► display
|
||||
fetching (a dict) │ │
|
||||
caching │ └─ built-in
|
||||
scheduling └─ skin.render_<mode>(ctx, game)
|
||||
live priority draws onto ctx.canvas
|
||||
```
|
||||
|
||||
## The render funnel
|
||||
|
||||
Every sports scoreboard (baseball, football, basketball, hockey — anything
|
||||
built on `src/base_classes/sports.py`) renders through exactly one seam:
|
||||
`SportsCore._render_game(game, force_clear)`.
|
||||
|
||||
1. The mode class's `display()` (live, `SportsUpcoming`, `SportsRecent`)
|
||||
picks `self.current_game` and calls `_render_game`.
|
||||
2. `_render_game` lazily loads the configured skin (once, on first render —
|
||||
a broken skin can never block plugin startup).
|
||||
3. If a skin is active, the host builds a `SkinContext` — a fresh black
|
||||
canvas at the current display size plus layout/font/logo helpers — and
|
||||
calls the skin's `render_live` / `render_recent` / `render_upcoming`
|
||||
with a **copy** of the game dict.
|
||||
4. If the skin returns `True`, the canvas is composited onto the display.
|
||||
If it returns `False`, isn't implemented for that mode, or raises, the
|
||||
built-in `_draw_scorebug_layout` runs instead.
|
||||
|
||||
Key properties that fall out of this design:
|
||||
|
||||
- **Per-mode fallback.** A skin that only implements `render_live` gets the
|
||||
stock recent/upcoming screens for free.
|
||||
- **Three strikes.** A skin that raises 3 times in a row is disabled for the
|
||||
rest of the session (one loud error log per failure); the display never
|
||||
goes dark. Restarting the service re-arms it.
|
||||
- **Copies, not references.** Skins receive a shallow copy of the game dict,
|
||||
so a buggy skin cannot corrupt the plugin's scheduling state.
|
||||
- **Vegas mode works untouched.** Vegas capture falls back to grabbing the
|
||||
regular `display()` output, which is already skin-rendered. Skins can
|
||||
additionally implement `render_vegas_card` for purpose-built scroll cards,
|
||||
and hosts can call `SportsCore.render_skin_card(game, size)` to use it.
|
||||
- **Hot-loop caution.** `render_live` runs every display-loop pass during a
|
||||
live game. The host logs a warning when a skin render exceeds 150 ms, and
|
||||
`scripts/validate_skin.py` enforces a budget at development time — but
|
||||
Python cannot forcibly time-out a stuck render, so a skin that blocks
|
||||
(network I/O, giant image ops) stalls the display. This is why the rules
|
||||
in CREATING_SKINS.md ban I/O in render paths.
|
||||
|
||||
## The view model contract
|
||||
|
||||
The `game` dict a skin receives is the plugin's already-extracted view model
|
||||
(`SportsCore._extract_game_details_common` plus per-sport extras from
|
||||
`src/base_classes/{baseball,basketball,football,hockey}.py`).
|
||||
|
||||
- **Guaranteed keys (view model v1.0)** — always present for every sport:
|
||||
`id`, `game_time`, `game_date`, `start_time_utc` (a UTC `datetime`),
|
||||
`status_text`, `is_live`, `is_final`, `is_upcoming`, `is_halftime`,
|
||||
`home_abbr`/`away_abbr`, `home_id`/`away_id`, `home_score`/`away_score`
|
||||
(**strings**), `home_logo_path`/`away_logo_path`, `home_record`/`away_record`.
|
||||
- **Sport extras** — documented per sport in CREATING_SKINS.md (e.g. baseball
|
||||
adds `inning`, `inning_half`, `balls`, `strikes`, `outs`, `bases_occupied`).
|
||||
- **Optional keys** (`odds`, rankings, `series_summary`, …) are present only
|
||||
when the feature is enabled — skins must always use `.get()`.
|
||||
|
||||
Versioning policy: additive changes bump the minor version
|
||||
(`VIEW_MODEL_VERSION` in `src/skin_system/skin_base.py`, surfaced to skins as
|
||||
`ctx.view_model_version`); renaming or removing a guaranteed key requires a
|
||||
major bump plus a compat shim. `test/test_skin_system.py::TestViewModelContract`
|
||||
fails CI if a guaranteed key disappears from the extractor.
|
||||
|
||||
Separately, `SKIN_API_VERSION` versions the Python API (`ScoreboardSkin`,
|
||||
`SkinContext`). The loader refuses a skin whose manifest declares a different
|
||||
major version and falls back to the built-in renderer with a clear
|
||||
"skin needs an update" log line.
|
||||
|
||||
## Package layout and lifecycle
|
||||
|
||||
```text
|
||||
skins/<skin-id>/
|
||||
skin.json # manifest (required)
|
||||
skin.py # ScoreboardSkin subclass (required)
|
||||
preview.png # optional, shown by the web UI
|
||||
assets/ # optional skin-local images
|
||||
helpers.py ... # optional extra modules (namespaced per skin at import)
|
||||
```
|
||||
|
||||
Skins live in the central `skins/` directory — deliberately **not** inside the
|
||||
plugin's directory, because plugin reinstall/update deletes the whole plugin
|
||||
directory and a skin must survive that. One skin can also target several
|
||||
plugins (mlb + milb).
|
||||
|
||||
Lifecycle: discovered lazily on first render → manifest validated → API major
|
||||
version gated → module imported under a namespaced `sys.modules` key (two
|
||||
skins can both ship a `helpers.py`, same scheme plugins use) → instantiated
|
||||
with `(manifest, options)`. Every failure logs and falls back to built-in.
|
||||
|
||||
Skins should be **stateless**: the live, recent, and upcoming mode classes
|
||||
each hold their own skin instance, so derive everything from `(ctx, game)`.
|
||||
|
||||
## Selection and configuration
|
||||
|
||||
Inside the plugin's own config section in `config/config.json`:
|
||||
|
||||
```json
|
||||
"baseball-scoreboard": {
|
||||
"skin": "retro-baseball",
|
||||
"skin_options": { "accent_color": [255, 80, 0] }
|
||||
}
|
||||
```
|
||||
|
||||
`"skin"` is either one id for all modes or a per-mode mapping
|
||||
(`{"live": "retro-baseball", "recent": "built-in"}`). Absent, empty, or
|
||||
`"built-in"` means the stock renderer. Because this rides the plugin's config
|
||||
section, it persists across plugin reinstalls like every other setting.
|
||||
|
||||
The web UI shows a **Visual Skin** dropdown for plugins that have matching
|
||||
skins installed: `SchemaManager.inject_skin_selector` adds an enum to the
|
||||
*served* schema only. Validation never sees the enum — so a config that
|
||||
references an uninstalled skin stays valid (rendering just falls back), and
|
||||
the currently-configured value is always kept selectable. `GET /api/v3/skins`
|
||||
lists installed skins (optionally filtered by `?plugin_id=`).
|
||||
|
||||
## Distribution
|
||||
|
||||
- **Manual:** `git clone <skin repo> skins/<skin-id>` — that's the whole
|
||||
install. No manifest bumps, no `update_registry.py`; skins are not monorepo
|
||||
plugins.
|
||||
- **Store:** registry entries with `"type": "skin"` install through the same
|
||||
`plugins.json` pipeline; `PluginStoreManager` routes them to `skins/`,
|
||||
validates `skin.json` (including the API major version) instead of
|
||||
`manifest.json`, and never installs dependencies — skins are render-only
|
||||
(stdlib + PIL + the provided context, no third-party packages in v1).
|
||||
|
||||
## Trust model
|
||||
|
||||
A skin is Python executing inside the display service — **exactly the same
|
||||
trust level as a plugin**, even though "skin" sounds cosmetic. Only install
|
||||
skins from sources you'd be willing to install a plugin from.
|
||||
|
||||
## v2 directions (not in v1)
|
||||
|
||||
- A generic `BasePlugin` opt-in (`render_with_skin()`) so non-sports plugins
|
||||
(weather, music) can offer skinnable layouts; `skin_runtime` is already
|
||||
sports-agnostic in anticipation.
|
||||
- Store UI: preview gallery, one-click install from the skin browser.
|
||||
- An update path for git-cloned skins (today: re-clone or store reinstall).
|
||||
- Animation support in skins (today the API is one frame per render call;
|
||||
stateful tricks work but are at-your-own-risk).
|
||||
@@ -0,0 +1,384 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Vegas Mode Density Audit
|
||||
|
||||
Reports how much of the Vegas ticker is actually showing something. Loads the
|
||||
real enabled plugins, pulls each one's content through the real
|
||||
``PluginAdapter``, composes the strip through the real ``ScrollHelper``, then
|
||||
measures the result.
|
||||
|
||||
The headline number is the **dead-frame ratio**: the fraction of viewport
|
||||
positions across a full cycle that are effectively blank. Because the panel
|
||||
only ever shows ``display_width`` columns at a time, a blank stretch wider than
|
||||
the viewport is a stretch where the display looks switched off — so this ratio
|
||||
tracks perceived dead time rather than just counting unlit pixels.
|
||||
|
||||
Runs entirely off-hardware, so it is safe to run alongside a live display.
|
||||
|
||||
Usage:
|
||||
# Audit every enabled plugin at the display size from config.json
|
||||
python scripts/dev/vegas_audit.py
|
||||
|
||||
# Specific plugins, dump each segment as a PNG for eyeballing
|
||||
python scripts/dev/vegas_audit.py -p of-the-day,youtube-stats --dump-dir /tmp/vg
|
||||
|
||||
# Machine-readable, for before/after comparison
|
||||
python scripts/dev/vegas_audit.py --json > after.json
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
# Must precede any src import that may reach for hardware.
|
||||
os.environ.setdefault('EMULATOR', 'true')
|
||||
|
||||
from PIL import Image # noqa: E402
|
||||
|
||||
from src.common.scroll_helper import ScrollHelper # noqa: E402
|
||||
from src.plugin_system.testing.loading import ( # noqa: E402
|
||||
build_full_config,
|
||||
find_plugin_dir,
|
||||
load_manifest,
|
||||
)
|
||||
from src.vegas_mode.config import VegasModeConfig # noqa: E402
|
||||
from src.vegas_mode.geometry import ( # noqa: E402
|
||||
DEFAULT_INK_THRESHOLD,
|
||||
column_has_ink,
|
||||
content_bounds,
|
||||
dead_window_stats,
|
||||
window_coverage_stats,
|
||||
)
|
||||
from src.vegas_mode.plugin_adapter import PluginAdapter # noqa: E402
|
||||
|
||||
# Sampling stride for the dead-window scan. A full cycle can be 30,000px wide;
|
||||
# 4px granularity keeps the scan instant while staying well under the ~10px a
|
||||
# single scroll step ever covers, so no dead stretch is missed.
|
||||
DEAD_SCAN_STEP = 4
|
||||
|
||||
|
||||
def load_main_config(path: Path) -> Dict[str, Any]:
|
||||
with open(path, 'r') as fh:
|
||||
return json.load(fh)
|
||||
|
||||
|
||||
def display_size_from_config(config: Dict[str, Any]) -> tuple:
|
||||
"""Derive the logical ticker size the way DisplayManager does."""
|
||||
hw = config.get('display', {}).get('hardware', {})
|
||||
cols = int(hw.get('cols', 64))
|
||||
chain = int(hw.get('chain_length', 1))
|
||||
rows = int(hw.get('rows', 32))
|
||||
parallel = int(hw.get('parallel', 1))
|
||||
return cols * chain, rows * parallel
|
||||
|
||||
|
||||
def enabled_plugin_ids(config: Dict[str, Any]) -> List[str]:
|
||||
"""Plugin IDs that are enabled in config, excluding non-plugin sections."""
|
||||
ids = []
|
||||
for key, value in config.items():
|
||||
if isinstance(value, dict) and value.get('enabled') is True:
|
||||
ids.append(key)
|
||||
return ids
|
||||
|
||||
|
||||
def instantiate(plugin_id: str, display_manager, cache_manager, plugin_manager):
|
||||
"""Load one plugin offline. Returns the instance or None."""
|
||||
from src.plugin_system.plugin_loader import PluginLoader
|
||||
|
||||
search_dirs = [
|
||||
str(PROJECT_ROOT / 'plugin-repos'),
|
||||
str(PROJECT_ROOT / 'plugins'),
|
||||
]
|
||||
plugin_dir = find_plugin_dir(plugin_id, search_dirs)
|
||||
if not plugin_dir:
|
||||
return None
|
||||
|
||||
try:
|
||||
manifest = load_manifest(Path(plugin_dir))
|
||||
cfg = build_full_config(Path(plugin_dir))
|
||||
instance, _ = PluginLoader().load_plugin(
|
||||
plugin_id=plugin_id,
|
||||
manifest=manifest,
|
||||
plugin_dir=Path(plugin_dir),
|
||||
config=cfg,
|
||||
display_manager=display_manager,
|
||||
cache_manager=cache_manager,
|
||||
plugin_manager=plugin_manager,
|
||||
install_deps=False,
|
||||
)
|
||||
return instance
|
||||
except Exception as exc: # noqa: BLE001 - audit tool must survive any plugin
|
||||
print(f" ! {plugin_id}: load failed ({type(exc).__name__}: {exc})",
|
||||
file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def join_rows(images: List[Image.Image], gap: int) -> Image.Image:
|
||||
"""Concatenate one plugin's rows, matching RenderPipeline._join_plugin_rows."""
|
||||
if len(images) == 1:
|
||||
return images[0]
|
||||
gap = max(0, gap)
|
||||
width = sum(img.width for img in images) + gap * (len(images) - 1)
|
||||
height = max(img.height for img in images)
|
||||
block = Image.new('RGB', (width, height), (0, 0, 0))
|
||||
x = 0
|
||||
for img in images:
|
||||
block.paste(img, (x, 0))
|
||||
x += img.width + gap
|
||||
return block
|
||||
|
||||
|
||||
def measure_segment(images: List[Image.Image], display_width: int,
|
||||
scroll_speed: float, threshold: int) -> Dict[str, Any]:
|
||||
"""Geometry of one plugin's contribution to the ticker."""
|
||||
total_width = sum(img.width for img in images)
|
||||
combined = Image.new('RGB', (max(1, total_width), images[0].height))
|
||||
x = 0
|
||||
for img in images:
|
||||
combined.paste(img, (x, 0))
|
||||
x += img.width
|
||||
|
||||
ink = column_has_ink(combined, threshold)
|
||||
bounds = content_bounds(combined, threshold)
|
||||
ink_cols = int(ink.sum())
|
||||
|
||||
return {
|
||||
'images': len(images),
|
||||
'width_px': total_width,
|
||||
'ink_cols': ink_cols,
|
||||
'ink_pct': round(100.0 * ink_cols / total_width, 1) if total_width else 0.0,
|
||||
'lead_black_px': bounds[0] if bounds else total_width,
|
||||
'trail_black_px': (total_width - 1 - bounds[1]) if bounds else 0,
|
||||
'seconds_on_screen': round(total_width / scroll_speed, 1) if scroll_speed else 0.0,
|
||||
'widths': [img.width for img in images],
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Audit Vegas mode content density')
|
||||
parser.add_argument('--config', default=str(PROJECT_ROOT / 'config' / 'config.json'),
|
||||
help='Path to main config.json')
|
||||
parser.add_argument('-p', '--plugins', default=None,
|
||||
help='Comma-separated plugin IDs (default: all enabled)')
|
||||
parser.add_argument('--width', type=int, default=None,
|
||||
help='Override display width (default: from config hardware)')
|
||||
parser.add_argument('--height', type=int, default=None,
|
||||
help='Override display height (default: from config hardware)')
|
||||
parser.add_argument('--dump-dir', default=None,
|
||||
help='Write each segment and the composed strip as PNGs here')
|
||||
parser.add_argument('--threshold', type=int, default=DEFAULT_INK_THRESHOLD,
|
||||
help=f'Ink threshold (default: {DEFAULT_INK_THRESHOLD})')
|
||||
parser.add_argument('--per-cycle', type=int, default=None,
|
||||
help='Plugins composed per cycle '
|
||||
'(default: buffer_ahead + 1, matching production)')
|
||||
parser.add_argument('--json', action='store_true',
|
||||
help='Emit JSON instead of a text report')
|
||||
args = parser.parse_args()
|
||||
|
||||
config = load_main_config(Path(args.config))
|
||||
vegas = VegasModeConfig.from_config(config)
|
||||
|
||||
cfg_w, cfg_h = display_size_from_config(config)
|
||||
width = args.width or cfg_w
|
||||
height = args.height or cfg_h
|
||||
speed = vegas.scroll_speed
|
||||
|
||||
if args.plugins:
|
||||
plugin_ids = [p.strip() for p in args.plugins.split(',') if p.strip()]
|
||||
else:
|
||||
plugin_ids = vegas.get_ordered_plugins(enabled_plugin_ids(config))
|
||||
|
||||
dump_dir = Path(args.dump_dir) if args.dump_dir else None
|
||||
if dump_dir:
|
||||
dump_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from src.plugin_system.testing import (
|
||||
MockCacheManager, MockPluginManager, VisualTestDisplayManager,
|
||||
)
|
||||
|
||||
display_manager = VisualTestDisplayManager(width=width, height=height)
|
||||
cache_manager = MockCacheManager()
|
||||
plugin_manager = MockPluginManager()
|
||||
# Pass the loaded config, exactly as VegasModeCoordinator does. Omitting it
|
||||
# makes PluginAdapter fall back to VegasModeConfig() defaults, so the audit
|
||||
# would silently report trimming and width-budget behaviour that differs
|
||||
# from the user's config.json — the same drift the lead_gap and grouping
|
||||
# arguments below exist to avoid.
|
||||
adapter = PluginAdapter(display_manager, vegas)
|
||||
|
||||
if not args.json:
|
||||
print(f"Vegas audit — display {width}x{height}, scroll {speed:g}px/s, "
|
||||
f"separator {vegas.separator_width}px")
|
||||
print(f"One display width = {width / speed:.1f}s of screen time\n")
|
||||
|
||||
results: List[Dict[str, Any]] = []
|
||||
segments: List[Image.Image] = []
|
||||
|
||||
for plugin_id in plugin_ids:
|
||||
started = time.time()
|
||||
instance = instantiate(plugin_id, display_manager, cache_manager, plugin_manager)
|
||||
if instance is None:
|
||||
results.append({'plugin': plugin_id, 'status': 'load_failed'})
|
||||
continue
|
||||
|
||||
plugin_manager.plugins[plugin_id] = instance
|
||||
adapter.invalidate_cache(plugin_id)
|
||||
|
||||
try:
|
||||
images = adapter.get_content(instance, plugin_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
results.append({'plugin': plugin_id, 'status': 'fetch_error',
|
||||
'error': f'{type(exc).__name__}: {exc}'})
|
||||
continue
|
||||
|
||||
fetch_ms = round((time.time() - started) * 1000)
|
||||
|
||||
if not images:
|
||||
results.append({'plugin': plugin_id, 'status': 'no_content',
|
||||
'fetch_ms': fetch_ms})
|
||||
if not args.json:
|
||||
print(f" {plugin_id:28s} NO CONTENT ({fetch_ms}ms)")
|
||||
continue
|
||||
|
||||
entry = {'plugin': plugin_id, 'status': 'ok', 'fetch_ms': fetch_ms}
|
||||
entry.update(measure_segment(images, width, speed, args.threshold))
|
||||
results.append(entry)
|
||||
segments.extend(images)
|
||||
|
||||
if dump_dir:
|
||||
for idx, img in enumerate(images):
|
||||
img.save(dump_dir / f"{plugin_id}__{idx:02d}.png")
|
||||
|
||||
if not args.json:
|
||||
print(f" {plugin_id:28s} {entry['width_px']:>6d}px "
|
||||
f"{entry['images']:>2d} img ink {entry['ink_pct']:>5.1f}% "
|
||||
f"lead {entry['lead_black_px']:>4d} tail {entry['trail_black_px']:>4d} "
|
||||
f"{entry['seconds_on_screen']:>6.1f}s ({fetch_ms}ms)")
|
||||
|
||||
summary: Dict[str, Any] = {
|
||||
'display_width': width,
|
||||
'display_height': height,
|
||||
'scroll_speed': speed,
|
||||
'separator_width': vegas.separator_width,
|
||||
'plugins_audited': len(plugin_ids),
|
||||
'plugins_with_content': sum(1 for r in results if r.get('status') == 'ok'),
|
||||
}
|
||||
|
||||
# Production composes only the plugins sitting in the active buffer, so
|
||||
# measuring one giant strip of every plugin would hide the per-cycle costs
|
||||
# (most importantly the leading gap, which is charged once per cycle).
|
||||
# Group the segments the way the running service does.
|
||||
per_cycle = max(1, args.per_cycle or vegas.plugins_per_cycle)
|
||||
|
||||
cycles: List[Dict[str, Any]] = []
|
||||
with_content = [r for r in results if r.get('status') == 'ok']
|
||||
|
||||
if segments:
|
||||
logger = logging.getLogger('vegas_audit')
|
||||
seg_index = 0
|
||||
for start in range(0, len(with_content), per_cycle):
|
||||
group = with_content[start:start + per_cycle]
|
||||
|
||||
# Mirror RenderPipeline: each plugin's rows are joined by
|
||||
# intra_plugin_gap into one block, and separator_width is applied
|
||||
# only between blocks. Measuring a flat list here would report gaps
|
||||
# the service does not emit.
|
||||
blocks: List[Image.Image] = []
|
||||
for entry in group:
|
||||
count = entry['images']
|
||||
rows = segments[seg_index:seg_index + count]
|
||||
seg_index += count
|
||||
if rows:
|
||||
blocks.append(join_rows(rows, vegas.intra_plugin_gap))
|
||||
if not blocks:
|
||||
continue
|
||||
|
||||
# ScrollHelper logs unconditionally, so it needs a real logger.
|
||||
helper = ScrollHelper(width, height, logger)
|
||||
helper.create_scrolling_image(
|
||||
content_items=blocks,
|
||||
item_gap=vegas.separator_width,
|
||||
element_gap=0,
|
||||
# Must match RenderPipeline. Omitting this made the audit
|
||||
# measure a full-display-width leading gap the service no
|
||||
# longer emits, overstating dead space by 512px per cycle.
|
||||
lead_gap=vegas.lead_in_width,
|
||||
)
|
||||
composed = helper.cached_image
|
||||
if composed is None:
|
||||
continue
|
||||
|
||||
dead = dead_window_stats(composed, width, args.threshold, step=DEAD_SCAN_STEP)
|
||||
cover = window_coverage_stats(
|
||||
composed, width, args.threshold, step=DEAD_SCAN_STEP)
|
||||
|
||||
if dump_dir:
|
||||
composed.save(dump_dir / f"_cycle{len(cycles):02d}.png")
|
||||
|
||||
cycles.append({
|
||||
'plugins': [e['plugin'] for e in group],
|
||||
'width_px': composed.width,
|
||||
'seconds': round(composed.width / speed, 1) if speed else 0.0,
|
||||
'dead_pct': round(100 * dead.dead_ratio, 1),
|
||||
'longest_dead_seconds': round(
|
||||
dead.longest_dead_run * DEAD_SCAN_STEP / speed, 1) if speed else 0.0,
|
||||
'mean_ink_pct': round(100 * cover.mean_ink_ratio, 1),
|
||||
'sparse_pct': round(100 * cover.sparse_ratio, 1),
|
||||
'longest_sparse_seconds': round(
|
||||
cover.longest_sparse_run * DEAD_SCAN_STEP / speed, 1) if speed else 0.0,
|
||||
})
|
||||
|
||||
if cycles:
|
||||
total_px = sum(c['width_px'] for c in cycles)
|
||||
# Weight each cycle by its width so a long cycle counts proportionally.
|
||||
summary.update({
|
||||
'cycles': len(cycles),
|
||||
'total_px': total_px,
|
||||
'full_rotation_seconds': round(total_px / speed, 1) if speed else 0.0,
|
||||
'dead_pct': round(
|
||||
sum(c['dead_pct'] * c['width_px'] for c in cycles) / total_px, 1),
|
||||
'mean_ink_pct': round(
|
||||
sum(c['mean_ink_pct'] * c['width_px'] for c in cycles) / total_px, 1),
|
||||
'sparse_pct': round(
|
||||
sum(c['sparse_pct'] * c['width_px'] for c in cycles) / total_px, 1),
|
||||
'worst_dead_seconds': max(c['longest_dead_seconds'] for c in cycles),
|
||||
'worst_sparse_seconds': max(c['longest_sparse_seconds'] for c in cycles),
|
||||
})
|
||||
|
||||
if args.json:
|
||||
print(json.dumps({'summary': summary, 'cycles': cycles, 'plugins': results},
|
||||
indent=2))
|
||||
else:
|
||||
print(f"\n Cycles ({per_cycle} plugins each, as production composes them):")
|
||||
for idx, cyc in enumerate(cycles):
|
||||
print(f" [{idx}] {cyc['width_px']:>6d}px {cyc['seconds']:>6.1f}s "
|
||||
f"ink {cyc['mean_ink_pct']:>5.1f}% blank {cyc['dead_pct']:>5.1f}% "
|
||||
f"worst blank {cyc['longest_dead_seconds']:>5.1f}s "
|
||||
f"| {', '.join(cyc['plugins'])}")
|
||||
|
||||
print(f"\n {'-' * 66}")
|
||||
print(f" full rotation {summary.get('full_rotation_seconds', 0):>7.1f}s "
|
||||
f"over {summary.get('cycles', 0)} cycles")
|
||||
print(f" mean ink coverage {summary.get('mean_ink_pct', 0):>7.1f}% "
|
||||
f"(higher is better; target >25%)")
|
||||
print(f" fully blank {summary.get('dead_pct', 0):>7.1f}% (target <2%)")
|
||||
print(f" reads as empty {summary.get('sparse_pct', 0):>7.1f}% (target <15%)")
|
||||
print(f" worst blank stretch {summary.get('worst_dead_seconds', 0):>7.1f}s "
|
||||
f"(target <1.5s)")
|
||||
print(f" plugins w/ content {summary.get('plugins_with_content', 0):>7d}"
|
||||
f" of {summary['plugins_audited']}")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Headless skin validator — render a skin against bundled fixture games at
|
||||
multiple panel sizes without hardware, a network, or a running service.
|
||||
|
||||
python scripts/validate_skin.py --skin my-skin
|
||||
python scripts/validate_skin.py --skin my-skin --sport baseball \
|
||||
--size 128x32 --size 64x32 --output-dir /tmp/skin_renders
|
||||
|
||||
For each (mode x size) it checks: the manifest loads and its API version
|
||||
matches, the render raises no exception, the canvas isn't blank, and the
|
||||
render finishes inside a time budget (warn — the live renderer runs every
|
||||
display-loop pass, and a Pi is far slower than your dev machine). PNGs are
|
||||
saved (native plus 4x nearest-neighbor previews) so you can eyeball the
|
||||
result. Exit code is non-zero when any check fails.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont # noqa: E402
|
||||
|
||||
FIXTURES_DIR = PROJECT_ROOT / "src" / "skin_system" / "fixtures"
|
||||
MODES = ("live", "recent", "upcoming")
|
||||
SPORTS = ("baseball", "basketball", "football", "hockey")
|
||||
RENDER_BUDGET_S = 0.100
|
||||
|
||||
|
||||
class FixtureHost:
|
||||
"""Stands in for a SportsCore instance: fonts, logger, logo loading,
|
||||
outlined text — everything build_context needs, no network."""
|
||||
|
||||
def __init__(self, sport: str, skin_options: dict) -> None:
|
||||
self.sport = sport
|
||||
self.sport_key = sport
|
||||
self.skin_options = skin_options
|
||||
self.logger = logging.getLogger(f"validate_skin.{sport}")
|
||||
self.fonts = self._load_fonts()
|
||||
self._logo_cache = {}
|
||||
self.display_manager = None # build_context is always given a size
|
||||
|
||||
def _load_fonts(self) -> dict:
|
||||
"""Load the SportsCore font set (TTF, with PIL default fallback)."""
|
||||
fonts = {}
|
||||
try:
|
||||
press = str(PROJECT_ROOT / "assets/fonts/PressStart2P-Regular.ttf")
|
||||
small = str(PROJECT_ROOT / "assets/fonts/4x6-font.ttf")
|
||||
fonts['score'] = ImageFont.truetype(press, 10)
|
||||
fonts['time'] = ImageFont.truetype(press, 8)
|
||||
fonts['team'] = ImageFont.truetype(press, 8)
|
||||
fonts['status'] = ImageFont.truetype(small, 6)
|
||||
fonts['detail'] = ImageFont.truetype(small, 6)
|
||||
fonts['rank'] = ImageFont.truetype(press, 10)
|
||||
except IOError:
|
||||
default = ImageFont.load_default()
|
||||
for key in ('score', 'time', 'team', 'status', 'detail', 'rank'):
|
||||
fonts[key] = default
|
||||
return fonts
|
||||
|
||||
def _load_and_resize_logo(self, team_id: str, team_abbrev: str,
|
||||
logo_path, logo_url) -> "Image.Image | None":
|
||||
"""Load a fixture logo from disk (no downloads), cached per team."""
|
||||
if team_abbrev in self._logo_cache:
|
||||
return self._logo_cache[team_abbrev]
|
||||
path = Path(logo_path)
|
||||
if not path.is_absolute():
|
||||
path = PROJECT_ROOT / path
|
||||
if not path.exists():
|
||||
return None
|
||||
logo = Image.open(path).convert('RGBA')
|
||||
self._logo_cache[team_abbrev] = logo
|
||||
return logo
|
||||
|
||||
def _draw_text_with_outline(self, draw: "ImageDraw.ImageDraw", text: str,
|
||||
position: tuple, font,
|
||||
fill: tuple = (255, 255, 255),
|
||||
outline_color: tuple = (0, 0, 0)) -> None:
|
||||
"""Classic outlined scorebug text, same as SportsCore's helper."""
|
||||
x, y = position
|
||||
for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1),
|
||||
(1, -1), (1, 0), (1, 1)]:
|
||||
draw.text((x + dx, y + dy), text, font=font, fill=outline_color)
|
||||
draw.text((x, y), text, font=font, fill=fill)
|
||||
|
||||
|
||||
def load_fixture(sport: str, mode: str) -> dict:
|
||||
with open(FIXTURES_DIR / f"{sport}_{mode}.json", encoding="utf-8") as f:
|
||||
game = json.load(f)
|
||||
# Real view models carry start_time_utc as a UTC datetime, not a string.
|
||||
if isinstance(game.get("start_time_utc"), str):
|
||||
from datetime import datetime
|
||||
game["start_time_utc"] = datetime.fromisoformat(game["start_time_utc"])
|
||||
return game
|
||||
|
||||
|
||||
def parse_size(value: str) -> "tuple[int, int]":
|
||||
try:
|
||||
w_text, h_text = value.lower().split("x")
|
||||
w, h = int(w_text), int(h_text)
|
||||
except ValueError as exc:
|
||||
raise argparse.ArgumentTypeError(f"size must look like 128x32, got {value!r}") from exc
|
||||
if w <= 0 or h <= 0:
|
||||
raise argparse.ArgumentTypeError(f"size dimensions must be positive, got {value!r}")
|
||||
return w, h
|
||||
|
||||
|
||||
def parse_options(value: str) -> dict:
|
||||
try:
|
||||
options = json.loads(value)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise argparse.ArgumentTypeError(f"options must be valid JSON: {exc.msg}") from exc
|
||||
if not isinstance(options, dict):
|
||||
raise argparse.ArgumentTypeError("options must be a JSON object")
|
||||
return options
|
||||
|
||||
|
||||
def display_path(path: Path) -> str:
|
||||
"""Repo-relative when inside the repo, absolute otherwise (--output-dir
|
||||
may point anywhere, e.g. /tmp/skin_renders)."""
|
||||
try:
|
||||
return str(path.relative_to(PROJECT_ROOT))
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--skin", required=True, help="skin id (directory name under skins/)")
|
||||
parser.add_argument("--sport", choices=SPORTS,
|
||||
help="fixture sport (default: first sport the skin targets, else baseball)")
|
||||
parser.add_argument("--size", action="append", type=parse_size, dest="sizes",
|
||||
metavar="WxH", help="panel size to render at (repeatable; default 128x32 and 64x32)")
|
||||
parser.add_argument("--output-dir", type=Path,
|
||||
default=PROJECT_ROOT / "skin_renders",
|
||||
help="where rendered PNGs are written")
|
||||
parser.add_argument("--options", type=parse_options, default={},
|
||||
help="skin_options JSON to pass the skin")
|
||||
args = parser.parse_args()
|
||||
sizes = args.sizes or [(128, 32), (64, 32)]
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
|
||||
from src.skin_system import skin_runtime
|
||||
from src.skin_system.skin_base import SKIN_API_VERSION
|
||||
|
||||
skins = skin_runtime.discover_skins()
|
||||
manifest = skins.get(args.skin)
|
||||
if manifest is None:
|
||||
print(f"FAIL: skin '{args.skin}' not found under {skin_runtime.get_skins_directory()}")
|
||||
if skins:
|
||||
print(f" installed skins: {', '.join(sorted(skins))}")
|
||||
return 1
|
||||
|
||||
sport = args.sport
|
||||
if sport is None:
|
||||
declared = skin_runtime.skin_targets(manifest)[0]
|
||||
sport = next((s for s in declared if s in SPORTS), "baseball")
|
||||
|
||||
skin = skin_runtime.load_skin(args.skin, sport=sport, sport_key=sport,
|
||||
options=args.options)
|
||||
if skin is None:
|
||||
print(f"FAIL: skin '{args.skin}' did not load "
|
||||
f"(see log above; host API is {SKIN_API_VERSION})")
|
||||
return 1
|
||||
|
||||
host = FixtureHost(sport, args.options)
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
failures = 0
|
||||
rendered = 0
|
||||
|
||||
for mode in MODES:
|
||||
game = load_fixture(sport, mode)
|
||||
render = getattr(skin, f"render_{mode}")
|
||||
for width, height in sizes:
|
||||
label = f"{mode}@{width}x{height}"
|
||||
try:
|
||||
# Warm-up render absorbs one-time font/image loads, second
|
||||
# render is the one timed against the budget.
|
||||
ctx = skin_runtime.build_context(host, game, size=(width, height))
|
||||
handled = render(ctx, dict(game))
|
||||
if handled:
|
||||
ctx = skin_runtime.build_context(host, game, size=(width, height))
|
||||
started = time.monotonic()
|
||||
handled = render(ctx, dict(game))
|
||||
elapsed = time.monotonic() - started
|
||||
else:
|
||||
elapsed = 0.0
|
||||
except Exception as e:
|
||||
print(f"FAIL {label}: render raised {type(e).__name__}: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
failures += 1
|
||||
continue
|
||||
|
||||
if not handled:
|
||||
print(f"skip {label}: render_{mode} returned False (built-in renderer would be used)")
|
||||
continue
|
||||
|
||||
if ctx.canvas.size != (width, height):
|
||||
print(f"FAIL {label}: canvas was replaced/resized to {ctx.canvas.size} — draw onto ctx.canvas, never reassign it")
|
||||
failures += 1
|
||||
continue
|
||||
if ctx.canvas.convert("L").getbbox() is None:
|
||||
print(f"FAIL {label}: canvas is blank — render returned True but drew nothing")
|
||||
failures += 1
|
||||
continue
|
||||
if elapsed > RENDER_BUDGET_S:
|
||||
print(f"WARN {label}: render took {elapsed * 1000:.0f}ms "
|
||||
f"(budget {RENDER_BUDGET_S * 1000:.0f}ms; a Pi is much slower than this machine)")
|
||||
|
||||
out = args.output_dir / f"{args.skin}_{sport}_{mode}_{width}x{height}.png"
|
||||
ctx.canvas.save(out)
|
||||
preview = ctx.canvas.resize((width * 4, height * 4), Image.NEAREST)
|
||||
preview.save(out.with_name(out.stem + "_x4.png"))
|
||||
print(f"ok {label}: {elapsed * 1000:.0f}ms -> {display_path(out)}")
|
||||
rendered += 1
|
||||
|
||||
# Vegas card, once per mode at the first size (optional API)
|
||||
try:
|
||||
width, height = sizes[0]
|
||||
ctx = skin_runtime.build_context(host, game, size=(width, height))
|
||||
card = skin.render_vegas_card(ctx, dict(game))
|
||||
if card is not None:
|
||||
out = args.output_dir / f"{args.skin}_{sport}_{mode}_vegas.png"
|
||||
card.save(out)
|
||||
print(f"ok {mode} vegas card -> {display_path(out)}")
|
||||
except Exception as e:
|
||||
print(f"FAIL {mode} vegas card: {type(e).__name__}: {e}")
|
||||
failures += 1
|
||||
|
||||
if rendered == 0 and failures == 0:
|
||||
print(f"FAIL: skin '{args.skin}' rendered nothing — no render_<mode> returned True")
|
||||
return 1
|
||||
print(f"\n{'FAILED' if failures else 'PASSED'}: {rendered} renders, {failures} failures "
|
||||
f"(PNGs in {args.output_dir})")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,23 @@
|
||||
# skins/
|
||||
|
||||
User-installable **visual skins** for the sports scoreboards. Each
|
||||
subdirectory is one skin:
|
||||
|
||||
```text
|
||||
skins/<skin-id>/
|
||||
skin.json # manifest
|
||||
skin.py # renderer (a ScoreboardSkin subclass)
|
||||
preview.png # optional
|
||||
```
|
||||
|
||||
- Install a skin: `git clone <skin repo> skins/<skin-id>` (or via the Plugin
|
||||
Store for registry entries with `"type": "skin"`).
|
||||
- Select it: set `"skin": "<skin-id>"` in the plugin's section of
|
||||
`config/config.json`, or use the web UI's Visual Skin dropdown.
|
||||
- Build one: start from `example-classic-baseball/` and read
|
||||
[docs/CREATING_SKINS.md](../docs/CREATING_SKINS.md). Validate with
|
||||
`python scripts/validate_skin.py --skin <skin-id>`.
|
||||
|
||||
Skins survive plugin reinstalls/updates (that's why they live here and not in
|
||||
the plugin's directory). A skin is Python at the same trust level as a
|
||||
plugin — review before installing.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"id": "example-classic-baseball",
|
||||
"name": "Example: Classic Baseball",
|
||||
"version": "1.0.0",
|
||||
"author": "LEDMatrix",
|
||||
"description": "Reference skin: a restyled baseball scorebug demonstrating the skin API. Copy this directory to start your own skin.",
|
||||
"skin_api_version": "1.0.0",
|
||||
"targets": {
|
||||
"sports": [
|
||||
"baseball"
|
||||
],
|
||||
"sport_keys": [
|
||||
"mlb",
|
||||
"milb"
|
||||
]
|
||||
},
|
||||
"entry_point": "skin.py",
|
||||
"class_name": "ClassicBaseballSkin",
|
||||
"modes": [
|
||||
"live",
|
||||
"recent",
|
||||
"upcoming"
|
||||
],
|
||||
"preview": "preview.png"
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
Example: Classic Baseball — the reference skin.
|
||||
|
||||
Shows the whole skin API surface on purpose: adaptive regions
|
||||
(scoreboard_regions), fitted text (ctx.layout.fit_text + ctx.draw_fit),
|
||||
logos (ctx.load_logo + ctx.draw_image), raw PIL (ctx.draw for the bases
|
||||
diamond), and per-user options (ctx.options). Everything is derived from
|
||||
ctx and the game dict — a skin holds no state, does no I/O, and never
|
||||
touches the display.
|
||||
|
||||
Copy this directory to skins/<your-skin-id>/, rename the class and the
|
||||
manifest fields, and run:
|
||||
|
||||
python scripts/validate_skin.py --skin <your-skin-id>
|
||||
"""
|
||||
|
||||
from src.adaptive_layout import LADDER_GRID, scoreboard_regions
|
||||
from src.skin_system.skin_base import ScoreboardSkin, SkinContext
|
||||
|
||||
DEFAULT_ACCENT = (255, 200, 0)
|
||||
|
||||
|
||||
class ClassicBaseballSkin(ScoreboardSkin):
|
||||
"""Reference baseball skin: classic scorebug with bases/outs/count."""
|
||||
|
||||
def __init__(self, manifest: dict, options: dict):
|
||||
super().__init__(manifest, options)
|
||||
# Validate user options once at load time (fail fast, fall back
|
||||
# gracefully) rather than surprising every render.
|
||||
accent = self.options.get("accent_color", DEFAULT_ACCENT)
|
||||
if (isinstance(accent, (list, tuple)) and len(accent) == 3
|
||||
and all(isinstance(c, int) and 0 <= c <= 255 for c in accent)):
|
||||
self._accent_color = tuple(accent)
|
||||
else:
|
||||
import logging
|
||||
logging.getLogger(__name__).error(
|
||||
"accent_color must be three 0-255 integers, got %r; using default", accent)
|
||||
self._accent_color = DEFAULT_ACCENT
|
||||
|
||||
# -- shared pieces ----------------------------------------------------
|
||||
|
||||
def _accent(self, ctx: SkinContext) -> tuple:
|
||||
"""Users can recolor the skin from config via skin_options."""
|
||||
return self._accent_color
|
||||
|
||||
def _draw_card(self, ctx: SkinContext, game: dict, status: str,
|
||||
center_lines: list, detail: str) -> None:
|
||||
"""The common card: logos left/right, status on top, the given
|
||||
center content, detail along the bottom."""
|
||||
regions = scoreboard_regions(ctx.layout.bounds, ctx=ctx.layout)
|
||||
|
||||
ctx.draw_image(ctx.load_logo("away"), regions.away_slot,
|
||||
cache_key=f"logo:{game.get('away_abbr')}")
|
||||
ctx.draw_image(ctx.load_logo("home"), regions.home_slot,
|
||||
cache_key=f"logo:{game.get('home_abbr')}")
|
||||
|
||||
if status:
|
||||
fit = ctx.layout.fit_text(status, regions.status_band, LADDER_GRID)
|
||||
ctx.draw_fit(fit, regions.status_band, color=self._accent(ctx))
|
||||
|
||||
if center_lines:
|
||||
rows = regions.score_area.split_v(*[1] * len(center_lines))
|
||||
for line, row in zip(center_lines, rows):
|
||||
if line:
|
||||
fit = ctx.layout.fit_text(line, row, LADDER_GRID)
|
||||
ctx.draw_fit(fit, row)
|
||||
|
||||
if detail:
|
||||
fit = ctx.layout.fit_text(detail, regions.detail_band, LADDER_GRID)
|
||||
ctx.draw_fit(fit, regions.detail_band, color=(160, 160, 160))
|
||||
|
||||
def _draw_bases_and_outs(self, ctx: SkinContext, game: dict) -> None:
|
||||
"""Raw-PIL escape hatch: a bases diamond + out dots in the bottom
|
||||
band, sized from the layout scale so it works on any panel."""
|
||||
size = ctx.layout.px(3, minimum=2) # half-diagonal of one base
|
||||
gap = ctx.layout.px(1)
|
||||
cx = ctx.width // 2
|
||||
cy = ctx.height - (size * 2) - 1
|
||||
|
||||
bases = game.get("bases_occupied") or [False, False, False]
|
||||
# (dx, dy) per base: first (right), second (top), third (left)
|
||||
offsets = [(size + gap, 0), (0, -(size + gap)), (-(size + gap), 0)]
|
||||
for occupied, (dx, dy) in zip(bases, offsets):
|
||||
x, y = cx + dx, cy + dy
|
||||
diamond = [(x, y - size), (x + size, y), (x, y + size), (x - size, y)]
|
||||
if occupied:
|
||||
ctx.draw.polygon(diamond, fill=self._accent(ctx))
|
||||
else:
|
||||
ctx.draw.polygon(diamond, outline=(110, 110, 110))
|
||||
|
||||
outs = min(int(game.get("outs") or 0), 3)
|
||||
r = max(1, size - 1)
|
||||
for i in range(3):
|
||||
x = cx + (i - 1) * (2 * r + 2 * gap)
|
||||
y = ctx.height - r - 1
|
||||
dot = [x - r, y - r, x + r, y + r]
|
||||
if i < outs:
|
||||
ctx.draw.ellipse(dot, fill=(255, 255, 255))
|
||||
else:
|
||||
ctx.draw.ellipse(dot, outline=(110, 110, 110))
|
||||
|
||||
# -- the three modes --------------------------------------------------
|
||||
|
||||
def render_live(self, ctx: SkinContext, game: dict) -> bool:
|
||||
half = "▲" if game.get("inning_half") == "top" else "▼"
|
||||
inning = game.get("inning") or ""
|
||||
status = f"{half}{inning}" if inning else game.get("status_text", "")
|
||||
score = f"{game.get('away_score', '0')}-{game.get('home_score', '0')}"
|
||||
count = f"{game.get('balls', 0)}-{game.get('strikes', 0)}"
|
||||
|
||||
self._draw_card(ctx, game, status, [score], "")
|
||||
self._draw_bases_and_outs(ctx, game)
|
||||
|
||||
# Ball-strike count in the top-left corner, over the away logo.
|
||||
fit = ctx.layout.fit_text(count, (ctx.width // 4, ctx.layout.px(8, minimum=6)), LADDER_GRID)
|
||||
ctx.draw_fit(fit, ctx.layout.bounds.top_band(fit.height + 1).left_col(fit.width + 2),
|
||||
color=(200, 200, 200))
|
||||
return True
|
||||
|
||||
def render_recent(self, ctx: SkinContext, game: dict) -> bool:
|
||||
score = f"{game.get('away_score', '0')}-{game.get('home_score', '0')}"
|
||||
self._draw_card(ctx, game, game.get("status_text", "Final"),
|
||||
[score], game.get("series_summary", ""))
|
||||
return True
|
||||
|
||||
def render_upcoming(self, ctx: SkinContext, game: dict) -> bool:
|
||||
matchup = f"{game.get('away_abbr', '')}@{game.get('home_abbr', '')}"
|
||||
self._draw_card(ctx, game, game.get("game_date", ""),
|
||||
[matchup, game.get("game_time", "")],
|
||||
f"{game.get('away_record', '')} {game.get('home_record', '')}".strip())
|
||||
return True
|
||||
+110
-3
@@ -29,6 +29,10 @@ except ImportError:
|
||||
|
||||
|
||||
class SportsCore(ABC):
|
||||
# Which ScoreboardSkin render method this class's display path maps to.
|
||||
# SportsLive inherits the default; SportsUpcoming/SportsRecent override.
|
||||
SKIN_MODE = "live"
|
||||
|
||||
def __init__(self, config: Dict[str, Any], display_manager: DisplayManager, cache_manager: CacheManager, logger: logging.Logger, sport_key: str):
|
||||
self.logger = logger
|
||||
self.config = config
|
||||
@@ -99,6 +103,17 @@ class SportsCore(ABC):
|
||||
self.last_update = 0
|
||||
self.current_game = None
|
||||
self.fonts = self._load_fonts()
|
||||
|
||||
# Optional visual skin (see docs/SKIN_SYSTEM.md). "skin" is either a
|
||||
# skin id applied to all modes, or a per-mode mapping like
|
||||
# {"live": "retro", "recent": "built-in"}. Loaded lazily on first
|
||||
# render so a broken skin can never block startup.
|
||||
self._skin_config = self.mode_config.get("skin")
|
||||
self.skin_options = self.mode_config.get("skin_options", {}) or {}
|
||||
self._skin = None
|
||||
self._skin_load_attempted = False
|
||||
self._skin_failures = 0
|
||||
self._skin_slow_renders = 0
|
||||
|
||||
# Initialize dynamic team resolver and resolve favorite teams
|
||||
self.dynamic_resolver = DynamicTeamResolver()
|
||||
@@ -205,6 +220,95 @@ class SportsCore(ABC):
|
||||
self.logger.error(f"Error in base _draw_scorebug_layout: {e}", exc_info=True)
|
||||
|
||||
|
||||
def _resolve_skin_id(self) -> Optional[str]:
|
||||
"""The skin id configured for this instance's mode, or None for the
|
||||
built-in renderer. Accepts a plain id (all modes) or a per-mode
|
||||
mapping ({"live": "retro-baseball", "recent": "built-in"})."""
|
||||
skin_id = self._skin_config
|
||||
if isinstance(skin_id, dict):
|
||||
skin_id = skin_id.get(self.SKIN_MODE)
|
||||
if not skin_id or not isinstance(skin_id, str) or skin_id == "built-in":
|
||||
return None
|
||||
return skin_id
|
||||
|
||||
def _get_skin(self):
|
||||
"""Lazily load the configured skin once. Returns None (built-in
|
||||
renderer) when no skin is configured or loading failed."""
|
||||
if not self._skin_load_attempted:
|
||||
self._skin_load_attempted = True
|
||||
skin_id = self._resolve_skin_id()
|
||||
if skin_id:
|
||||
try:
|
||||
from src.skin_system import skin_runtime
|
||||
self._skin = skin_runtime.load_skin(
|
||||
skin_id, sport=self.sport, sport_key=self.sport_key,
|
||||
options=self.skin_options)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to load skin '{skin_id}': {e}", exc_info=True)
|
||||
self._skin = None
|
||||
return self._skin
|
||||
|
||||
def _render_game(self, game: Dict, force_clear: bool = False) -> None:
|
||||
"""Render one game: try the configured skin first, fall back to the
|
||||
built-in _draw_scorebug_layout. A skin that raises 3 times in a row
|
||||
is disabled for the rest of the session."""
|
||||
skin = self._get_skin()
|
||||
if skin is not None and self._skin_failures < 3:
|
||||
try:
|
||||
from src.skin_system import skin_runtime
|
||||
ctx = skin_runtime.build_context(self, game)
|
||||
render = getattr(skin, f"render_{self.SKIN_MODE}")
|
||||
started = time.monotonic()
|
||||
handled = render(ctx, dict(game))
|
||||
elapsed = time.monotonic() - started
|
||||
if elapsed > 0.15 and self._skin_slow_renders < 5:
|
||||
self._skin_slow_renders += 1
|
||||
self.logger.warning(
|
||||
f"Skin '{self._resolve_skin_id()}' took {elapsed * 1000:.0f}ms to "
|
||||
f"render {self.SKIN_MODE} — slow renders stall the whole display loop")
|
||||
if handled:
|
||||
self._skin_failures = 0
|
||||
self.display_manager.image.paste(ctx.canvas, (0, 0))
|
||||
self.display_manager.update_display()
|
||||
return
|
||||
except Exception:
|
||||
self._skin_failures += 1
|
||||
outcome = ("disabling skin for this session" if self._skin_failures >= 3
|
||||
else "falling back to built-in renderer")
|
||||
self.logger.error(
|
||||
f"Skin '{self._resolve_skin_id()}' failed rendering {self.SKIN_MODE} "
|
||||
f"({self._skin_failures}/3); {outcome}", exc_info=True)
|
||||
self._draw_scorebug_layout(game, force_clear)
|
||||
|
||||
def render_skin_card(self, game: Dict, size: tuple) -> Optional[Image.Image]:
|
||||
"""Render one game as a standalone card via the configured skin —
|
||||
for vegas mode and previews. Tries render_vegas_card at the given
|
||||
size, then the mode renderer on a card-sized canvas. Returns None
|
||||
when no skin is active or the skin declined, so callers can use
|
||||
their default rendering."""
|
||||
skin = self._get_skin()
|
||||
if skin is None or self._skin_failures >= 3:
|
||||
return None
|
||||
try:
|
||||
from src.skin_system import skin_runtime
|
||||
ctx = skin_runtime.build_context(self, game, size=size)
|
||||
card = skin.render_vegas_card(ctx, dict(game))
|
||||
if card is not None:
|
||||
return card
|
||||
ctx = skin_runtime.build_context(self, game, size=size)
|
||||
render = getattr(skin, f"render_{self.SKIN_MODE}")
|
||||
if render(ctx, dict(game)):
|
||||
return ctx.canvas
|
||||
except Exception:
|
||||
# Card failures count toward the same 3-strike session disable
|
||||
# as display failures — a skin broken for vegas shouldn't get
|
||||
# to throw on every scroll tick forever.
|
||||
self._skin_failures += 1
|
||||
self.logger.error(
|
||||
f"Skin '{self._resolve_skin_id()}' card render failed "
|
||||
f"({self._skin_failures}/3)", exc_info=True)
|
||||
return None
|
||||
|
||||
def display(self, force_clear: bool = False) -> bool:
|
||||
"""Common display method for all NCAA FB managers""" # Updated docstring
|
||||
if not self.is_enabled: # Check if module is enabled
|
||||
@@ -229,7 +333,7 @@ class SportsCore(ABC):
|
||||
return False
|
||||
|
||||
try:
|
||||
self._draw_scorebug_layout(self.current_game, force_clear)
|
||||
self._render_game(self.current_game, force_clear)
|
||||
# display_manager.update_display() should be called within subclass draw methods
|
||||
# or after calling display() in the main loop. Let's keep it out of the base display.
|
||||
return True
|
||||
@@ -646,6 +750,8 @@ class SportsCore(ABC):
|
||||
pass
|
||||
|
||||
class SportsUpcoming(SportsCore):
|
||||
SKIN_MODE = "upcoming"
|
||||
|
||||
def __init__(self, config: Dict[str, Any], display_manager: DisplayManager, cache_manager: CacheManager, logger: logging.Logger, sport_key: str):
|
||||
super().__init__(config, display_manager, cache_manager, logger, sport_key)
|
||||
self.upcoming_games = [] # Store all fetched upcoming games initially
|
||||
@@ -973,7 +1079,7 @@ class SportsUpcoming(SportsCore):
|
||||
self.logger.debug(f"Switched to game index {self.current_game_index}")
|
||||
|
||||
if self.current_game:
|
||||
self._draw_scorebug_layout(self.current_game, force_clear)
|
||||
self._render_game(self.current_game, force_clear)
|
||||
return True
|
||||
# update_display() is called within _draw_scorebug_layout for upcoming
|
||||
return False
|
||||
@@ -984,6 +1090,7 @@ class SportsUpcoming(SportsCore):
|
||||
|
||||
|
||||
class SportsRecent(SportsCore):
|
||||
SKIN_MODE = "recent"
|
||||
|
||||
def __init__(self, config: Dict[str, Any], display_manager: DisplayManager, cache_manager: CacheManager, logger: logging.Logger, sport_key: str):
|
||||
super().__init__(config, display_manager, cache_manager, logger, sport_key)
|
||||
@@ -1274,7 +1381,7 @@ class SportsRecent(SportsCore):
|
||||
self.logger.debug(f"Switched to game index {self.current_game_index}")
|
||||
|
||||
if self.current_game:
|
||||
self._draw_scorebug_layout(self.current_game, force_clear)
|
||||
self._render_game(self.current_game, force_clear)
|
||||
return True
|
||||
# update_display() is called within _draw_scorebug_layout for recent
|
||||
return False
|
||||
|
||||
@@ -110,20 +110,30 @@ class ScrollHelper:
|
||||
self.is_scrolling = False
|
||||
self.scroll_complete = False
|
||||
|
||||
def create_scrolling_image(self, content_items: list,
|
||||
def create_scrolling_image(self, content_items: list,
|
||||
item_gap: int = 32,
|
||||
element_gap: int = 16) -> Image.Image:
|
||||
element_gap: int = 16,
|
||||
lead_gap: Optional[int] = None) -> Image.Image:
|
||||
"""
|
||||
Create a wide image containing all content items for scrolling.
|
||||
|
||||
|
||||
Args:
|
||||
content_items: List of PIL Images to include in scroll
|
||||
item_gap: Gap between different items
|
||||
element_gap: Gap between elements within an item
|
||||
|
||||
lead_gap: Blank columns before the first item. Defaults to a full
|
||||
display width, which makes a standalone ticker scroll in from
|
||||
off-screen. Callers that loop many plugins back-to-back (Vegas
|
||||
mode) pass a smaller value, since a full display width of black
|
||||
reads as the panel being switched off at the start of every
|
||||
cycle.
|
||||
|
||||
Returns:
|
||||
PIL Image containing all content arranged horizontally
|
||||
"""
|
||||
if lead_gap is None:
|
||||
lead_gap = self.display_width
|
||||
lead_gap = max(0, int(lead_gap))
|
||||
if not content_items:
|
||||
# Create empty image if no content
|
||||
# Still set total_scroll_width to 0 to indicate no scrollable content
|
||||
@@ -144,13 +154,13 @@ class ScrollHelper:
|
||||
total_width += element_gap * len(content_items)
|
||||
|
||||
# Add initial gap before first item
|
||||
total_width += self.display_width
|
||||
|
||||
total_width += lead_gap
|
||||
|
||||
# Create the full scrolling image
|
||||
full_image = Image.new('RGB', (total_width, self.display_height), (0, 0, 0))
|
||||
|
||||
|
||||
# Position items
|
||||
current_x = self.display_width # Start with initial gap
|
||||
current_x = lead_gap # Start with initial gap
|
||||
|
||||
for i, img in enumerate(content_items):
|
||||
# Paste the item image
|
||||
|
||||
@@ -1137,6 +1137,29 @@ class DisplayController:
|
||||
remaining = self.on_demand_expires_at - time.time()
|
||||
return max(0.0, remaining)
|
||||
|
||||
def _publish_current_mode_state(self) -> None:
|
||||
"""Publish the currently active display mode/plugin to cache for the web UI."""
|
||||
try:
|
||||
state = {
|
||||
'mode': self.current_display_mode,
|
||||
'plugin_id': self.mode_to_plugin_id.get(self.current_display_mode),
|
||||
'mode_index': self.current_mode_index,
|
||||
'total_modes': len(self.available_modes),
|
||||
'on_demand_active': self.on_demand_active,
|
||||
'is_display_active': self.is_display_active,
|
||||
'last_updated': time.time(),
|
||||
}
|
||||
self.cache_manager.set('display_current_state', state)
|
||||
self._last_published_mode = self.current_display_mode
|
||||
except (OSError, RuntimeError, ValueError, TypeError) as err:
|
||||
logger.error("Failed to publish current display state: %s", err, exc_info=True)
|
||||
|
||||
def _publish_current_mode_state_if_changed(self) -> None:
|
||||
"""Publish current mode state only when it actually changed, to avoid
|
||||
writing to the shared cache on every render tick."""
|
||||
if self.current_display_mode != getattr(self, '_last_published_mode', None):
|
||||
self._publish_current_mode_state()
|
||||
|
||||
def _publish_on_demand_state(self) -> None:
|
||||
"""Publish current on-demand state to cache for external consumers."""
|
||||
try:
|
||||
@@ -1656,6 +1679,7 @@ class DisplayController:
|
||||
logger.info("Starting display with cached data (fast startup mode)")
|
||||
self.current_display_mode = self.available_modes[self.current_mode_index] if self.available_modes else 'none'
|
||||
logger.info(f"Initial mode set to: {self.current_display_mode} (index: {self.current_mode_index}, total modes: {len(self.available_modes)})")
|
||||
self._publish_current_mode_state()
|
||||
|
||||
while True:
|
||||
# Apply plugin enable/disable edits saved via the web UI. The
|
||||
@@ -1716,9 +1740,11 @@ class DisplayController:
|
||||
logger.debug(f"Error clearing display when inactive: {e}")
|
||||
|
||||
logger.info(f"Display not active (is_display_active={self.is_display_active}), sleeping...")
|
||||
self._publish_current_mode_state()
|
||||
self._sleep_with_plugin_updates(60)
|
||||
continue
|
||||
|
||||
self._publish_current_mode_state_if_changed()
|
||||
logger.debug("Display active, processing mode: %s", self.current_display_mode)
|
||||
|
||||
# Plugins update on their own schedules - no forced sync updates needed
|
||||
|
||||
+26
-8
@@ -139,23 +139,41 @@ def setup_logging(
|
||||
sys.stderr.write(f"Warning: Could not set up file logging to {log_file}: {e}\n")
|
||||
|
||||
|
||||
def get_logger(name: str, plugin_id: Optional[str] = None) -> logging.Logger:
|
||||
class PluginLoggerAdapter(logging.LoggerAdapter):
|
||||
"""LoggerAdapter that stamps every record with its plugin_id.
|
||||
|
||||
A plain `logging.Logger` attribute (the old approach) is never copied
|
||||
onto individual `LogRecord`s, so `ContextualFormatter`/`StructuredFormatter`
|
||||
only ever saw `plugin_id` on calls that explicitly passed
|
||||
`extra={'plugin_id': ...}` (i.e. `log_with_context`). This adapter injects
|
||||
it into `extra` on every call, so `self.logger.info(...)` in plugin code
|
||||
is tagged automatically.
|
||||
"""
|
||||
|
||||
def process(self, msg, kwargs):
|
||||
extra = dict(kwargs.get('extra') or {})
|
||||
extra.setdefault('plugin_id', self.extra.get('plugin_id'))
|
||||
kwargs['extra'] = extra
|
||||
return msg, kwargs
|
||||
|
||||
|
||||
def get_logger(name: str, plugin_id: Optional[str] = None):
|
||||
"""
|
||||
Get a logger with consistent configuration.
|
||||
|
||||
|
||||
Args:
|
||||
name: Logger name (typically __name__)
|
||||
plugin_id: Optional plugin ID for automatic context
|
||||
|
||||
|
||||
Returns:
|
||||
Configured logger instance
|
||||
Configured logger instance (or a PluginLoggerAdapter when plugin_id
|
||||
is given, which supports the same .debug/.info/.warning/.error API)
|
||||
"""
|
||||
logger = logging.getLogger(name)
|
||||
|
||||
# Add plugin_id as attribute for formatters
|
||||
|
||||
if plugin_id:
|
||||
logger.plugin_id = plugin_id
|
||||
|
||||
return PluginLoggerAdapter(logger, {'plugin_id': plugin_id})
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
|
||||
@@ -86,7 +86,9 @@ class BasePlugin(ABC):
|
||||
self.display_manager: Any = display_manager
|
||||
self.cache_manager: Any = cache_manager
|
||||
self.plugin_manager: Any = plugin_manager
|
||||
self.logger: logging.Logger = get_logger(f"plugin.{plugin_id}", plugin_id=plugin_id)
|
||||
# get_logger returns a PluginLoggerAdapter here (plugin_id given), which
|
||||
# stamps every record with plugin_id so it survives into formatted output.
|
||||
self.logger = get_logger(f"plugin.{plugin_id}", plugin_id=plugin_id)
|
||||
self.enabled: bool = config.get("enabled", True)
|
||||
|
||||
self.logger.info("Initialized plugin: %s", plugin_id)
|
||||
|
||||
@@ -284,6 +284,19 @@ class SchemaManager:
|
||||
"type": "boolean",
|
||||
"default": False,
|
||||
"description": "Enable live priority takeover when plugin has live content"
|
||||
},
|
||||
# Skin selection (docs/SKIN_SYSTEM.md). Deliberately NOT an
|
||||
# enum here: validation must keep passing when a configured
|
||||
# skin gets uninstalled (rendering falls back to built-in).
|
||||
# The install-dependent enum is injected only at serve time
|
||||
# (inject_skin_selector) for the web UI dropdown.
|
||||
"skin": {
|
||||
"type": ["string", "object", "null"],
|
||||
"description": "Visual skin id, or a per-mode mapping like {\"live\": \"my-skin\"}"
|
||||
},
|
||||
"skin_options": {
|
||||
"type": "object",
|
||||
"description": "Options passed through to the selected skin"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,6 +367,53 @@ class SchemaManager:
|
||||
self.logger.error(error_msg)
|
||||
return False, [error_msg]
|
||||
|
||||
def inject_skin_selector(self, schema: Dict[str, Any], plugin_id: str,
|
||||
current_value: Any = None) -> Dict[str, Any]:
|
||||
"""Return a copy of a plugin's schema with a "skin" dropdown added
|
||||
when installed skins target this plugin (docs/SKIN_SYSTEM.md).
|
||||
|
||||
Serve-time only — validation never sees this enum, so a config
|
||||
referencing an uninstalled skin stays valid (rendering falls back
|
||||
to the built-in layout). The currently-configured value is always
|
||||
included in the enum for the same reason: the dropdown must be able
|
||||
to display a selection whose skin was removed.
|
||||
"""
|
||||
# A per-mode mapping ({"live": ..., "recent": ...}) can't be edited
|
||||
# through a string dropdown — injecting one would let the form save
|
||||
# a string over the mapping. Leave the schema alone; per-mode users
|
||||
# edit via the raw JSON config editor.
|
||||
if isinstance(current_value, dict):
|
||||
return schema
|
||||
|
||||
try:
|
||||
from src.skin_system import skin_runtime
|
||||
matching = skin_runtime.skins_for_plugin(plugin_id)
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Skin discovery failed for {plugin_id}: {e}")
|
||||
return schema
|
||||
|
||||
choices = sorted(matching.keys())
|
||||
if isinstance(current_value, str) and current_value and \
|
||||
current_value != "built-in" and current_value not in choices:
|
||||
choices.append(current_value)
|
||||
if not choices:
|
||||
return schema
|
||||
|
||||
enhanced = copy.deepcopy(schema)
|
||||
enhanced.setdefault("properties", {})
|
||||
if "skin" not in enhanced["properties"]:
|
||||
names = {sid: (matching.get(sid, {}).get("name") or sid) for sid in choices}
|
||||
enhanced["properties"]["skin"] = {
|
||||
"type": "string",
|
||||
"title": "Visual Skin",
|
||||
"description": "Replace this scoreboard's look with an installed skin "
|
||||
"(data, scheduling, and vegas mode are unaffected)",
|
||||
"enum": ["built-in", *choices],
|
||||
"enumNames": ["Built-in", *(names[sid] for sid in choices)],
|
||||
"default": "built-in"
|
||||
}
|
||||
return enhanced
|
||||
|
||||
def _format_validation_error(self, error: ValidationError, plugin_id: Optional[str] = None) -> str:
|
||||
"""
|
||||
Format a validation error into a readable message.
|
||||
|
||||
@@ -1214,6 +1214,11 @@ class PluginStoreManager:
|
||||
self.logger.error(f"Plugin not found in registry: {plugin_id}")
|
||||
return False
|
||||
|
||||
# Visual skins share the registry but install to skins/, not to a
|
||||
# plugin directory (docs/SKIN_SYSTEM.md)
|
||||
if (plugin_info.get('type') or 'plugin') == 'skin':
|
||||
return self._install_skin_from_info(plugin_id, plugin_info, branch)
|
||||
|
||||
repo_url = plugin_info.get('repo')
|
||||
if not repo_url:
|
||||
self.logger.error(f"Plugin {plugin_id} missing repository URL")
|
||||
@@ -2254,19 +2259,171 @@ class PluginStoreManager:
|
||||
|
||||
return None
|
||||
|
||||
_SKIN_ID_PATTERN = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$')
|
||||
|
||||
def _resolve_skin_target(self, skin_id: str) -> Optional[Path]:
|
||||
"""Validate an externally-supplied skin id and resolve it to a path
|
||||
strictly inside the skins directory. Returns None (after logging)
|
||||
for ids that are malformed or would escape the directory — registry
|
||||
entries and manifests are external input and must not be able to
|
||||
write or delete outside skins/."""
|
||||
from src.skin_system import skin_runtime
|
||||
|
||||
if not isinstance(skin_id, str) or not self._SKIN_ID_PATTERN.match(skin_id) \
|
||||
or '..' in skin_id:
|
||||
self.logger.error(f"Rejecting unsafe skin id: {skin_id!r}")
|
||||
return None
|
||||
skins_dir = skin_runtime.get_skins_directory().resolve()
|
||||
target = (skins_dir / skin_id).resolve()
|
||||
if target.parent != skins_dir:
|
||||
self.logger.error(f"Skin id {skin_id!r} escapes the skins directory; rejecting")
|
||||
return None
|
||||
return target
|
||||
|
||||
def _install_skin_from_info(self, skin_id: str, skin_info: Dict,
|
||||
branch: Optional[str] = None) -> bool:
|
||||
"""Install a registry entry of type "skin" into skins/<id>/.
|
||||
|
||||
Reuses the plugin download machinery (git / monorepo zip / archive)
|
||||
but validates skin.json instead of manifest.json and never installs
|
||||
dependencies — skins are render-only (stdlib + PIL + the provided
|
||||
SkinContext), which is also what keeps them safe to iterate on.
|
||||
|
||||
Downloads into a staging directory and validates there; the
|
||||
existing installation is only replaced after the new one passes,
|
||||
so a failed download or bad manifest can't destroy a working skin.
|
||||
"""
|
||||
from src.skin_system import skin_runtime
|
||||
from src.skin_system.skin_base import SKIN_API_VERSION
|
||||
|
||||
repo_url = skin_info.get('repo')
|
||||
if not repo_url:
|
||||
self.logger.error(f"Skin {skin_id} missing repository URL")
|
||||
return False
|
||||
|
||||
target = self._resolve_skin_target(skin_id)
|
||||
if target is None:
|
||||
return False
|
||||
skins_dir = target.parent
|
||||
skins_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Leading "_" keeps staging invisible to skin discovery
|
||||
staging = skins_dir / f"_staging-{skin_id}"
|
||||
if staging.exists() and not self._safe_remove_directory(staging):
|
||||
return False
|
||||
|
||||
subpath = skin_info.get('plugin_path')
|
||||
branch_candidates = self._distinct_sequence([
|
||||
branch,
|
||||
skin_info.get('branch'),
|
||||
skin_info.get('default_branch'),
|
||||
skin_info.get('last_commit_branch'),
|
||||
'main',
|
||||
'master'
|
||||
])
|
||||
|
||||
try:
|
||||
branch_used = None
|
||||
if subpath:
|
||||
for candidate in branch_candidates:
|
||||
download_url = f"{repo_url}/archive/refs/heads/{candidate}.zip"
|
||||
if self._install_from_monorepo(download_url, subpath, staging):
|
||||
branch_used = candidate
|
||||
break
|
||||
else:
|
||||
branch_used = self._install_via_git(repo_url, staging, branch_candidates)
|
||||
if branch_used is None and not staging.exists():
|
||||
for candidate in branch_candidates:
|
||||
download_url = f"{repo_url}/archive/refs/heads/{candidate}.zip"
|
||||
if self._install_via_download(download_url, staging):
|
||||
branch_used = candidate
|
||||
break
|
||||
|
||||
if branch_used is None and not staging.exists():
|
||||
self.logger.error(f"Failed to install skin {skin_id} via git or archive download")
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(staging / 'skin.json', 'r', encoding='utf-8') as f:
|
||||
manifest = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
self.logger.error(f"Skin {skin_id} has no valid skin.json: {e}")
|
||||
return False
|
||||
|
||||
missing = [k for k in ('id', 'name', 'version', 'skin_api_version', 'class_name')
|
||||
if not manifest.get(k)]
|
||||
if missing:
|
||||
self.logger.error(f"Skin {skin_id} manifest missing fields: {missing}")
|
||||
return False
|
||||
|
||||
# Unlike plugins, a mismatched id is rejected rather than
|
||||
# renamed: the manifest id is external input, and the registry
|
||||
# id is what the user asked to install.
|
||||
if manifest['id'] != skin_id:
|
||||
self.logger.error(
|
||||
f"Skin manifest id {manifest['id']!r} doesn't match registry id "
|
||||
f"{skin_id!r}; not installing")
|
||||
return False
|
||||
|
||||
def _api_major(v):
|
||||
try:
|
||||
return int(str(v).split('.')[0])
|
||||
except (ValueError, IndexError):
|
||||
return None
|
||||
|
||||
if _api_major(manifest['skin_api_version']) != _api_major(SKIN_API_VERSION):
|
||||
self.logger.error(
|
||||
f"Skin {skin_id} targets skin API {manifest['skin_api_version']} but this "
|
||||
f"LEDMatrix provides {SKIN_API_VERSION}; not installing")
|
||||
return False
|
||||
|
||||
# Validated — swap into place
|
||||
if target.exists() and not self._safe_remove_directory(target):
|
||||
self.logger.error(f"Could not replace existing skin directory: {target}")
|
||||
return False
|
||||
shutil.move(str(staging), str(target))
|
||||
skin_runtime.discover_skins(force_refresh=True)
|
||||
self.logger.info(f"Successfully installed skin: {skin_id} (branch: {branch_used})")
|
||||
return True
|
||||
finally:
|
||||
if staging.exists():
|
||||
self._safe_remove_directory(staging)
|
||||
|
||||
def uninstall_skin(self, skin_id: str) -> bool:
|
||||
"""Remove an installed skin. Plugin configs referencing it keep
|
||||
validating; rendering falls back to the built-in layout."""
|
||||
from src.skin_system import skin_runtime
|
||||
|
||||
target = self._resolve_skin_target(skin_id)
|
||||
if target is None:
|
||||
return False
|
||||
if not target.exists():
|
||||
self.logger.info(f"Skin {skin_id} not found (already uninstalled)")
|
||||
return True
|
||||
if self._safe_remove_directory(target):
|
||||
skin_runtime.discover_skins(force_refresh=True)
|
||||
self.logger.info(f"Successfully uninstalled skin: {skin_id}")
|
||||
return True
|
||||
return False
|
||||
|
||||
def uninstall_plugin(self, plugin_id: str) -> bool:
|
||||
"""
|
||||
Uninstall a plugin by removing its directory.
|
||||
|
||||
|
||||
Args:
|
||||
plugin_id: Plugin identifier
|
||||
|
||||
|
||||
Returns:
|
||||
True if uninstalled successfully (or already not installed)
|
||||
"""
|
||||
plugin_path = self._find_plugin_path(plugin_id)
|
||||
|
||||
|
||||
if plugin_path is None or not plugin_path.exists():
|
||||
# A skin id passed to the plugin uninstall path (the store UI
|
||||
# uses one uninstall flow) removes the skin instead
|
||||
skin_target = self._resolve_skin_target(plugin_id) \
|
||||
if self._SKIN_ID_PATTERN.match(str(plugin_id)) else None
|
||||
if skin_target is not None and skin_target.exists():
|
||||
return self.uninstall_skin(plugin_id)
|
||||
self.logger.info(f"Plugin {plugin_id} not found (already uninstalled)")
|
||||
return True # Already uninstalled, consider this success
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ PIL Image canvas and draws text using the actual project fonts.
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
@@ -62,6 +63,9 @@ class VisualTestDisplayManager:
|
||||
# Matrix proxy (plugins access display_manager.matrix.width/height)
|
||||
self.matrix = _MatrixProxy(width, height)
|
||||
|
||||
# Set while inside capture_mode(); mirrors DisplayManager's flag.
|
||||
self._capture_mode_active = False
|
||||
|
||||
# Scrolling state (interface compat, no-op)
|
||||
self._scrolling_state = {
|
||||
'is_scrolling': False,
|
||||
@@ -174,6 +178,21 @@ class VisualTestDisplayManager:
|
||||
"""No-op for hardware; marks that display was updated."""
|
||||
self.update_called = True
|
||||
|
||||
@contextmanager
|
||||
def capture_mode(self):
|
||||
"""
|
||||
Interface parity with DisplayManager.capture_mode().
|
||||
|
||||
There is no hardware to suppress here, but Vegas mode's PluginAdapter
|
||||
wraps every off-screen content fetch in this context, so the harness
|
||||
must provide it for that code path to be exercisable in tests.
|
||||
"""
|
||||
self._capture_mode_active = True
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._capture_mode_active = False
|
||||
|
||||
def draw_text(self, text: str, x: Optional[int] = None, y: Optional[int] = None,
|
||||
color: Tuple[int, int, int] = (255, 255, 255), small_font: bool = False,
|
||||
font: Optional[Any] = None, centered: bool = False) -> None:
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
Skin system: user-installable visual overlays for sports scoreboards.
|
||||
|
||||
A skin replaces only the rendering of a scoreboard (live / recent /
|
||||
upcoming) while the host plugin keeps doing data fetching, scheduling,
|
||||
caching, live priority, and vegas mode. See docs/SKIN_SYSTEM.md.
|
||||
"""
|
||||
|
||||
from src.skin_system.skin_base import (
|
||||
SKIN_API_VERSION,
|
||||
VIEW_MODEL_VERSION,
|
||||
ScoreboardSkin,
|
||||
SkinContext,
|
||||
)
|
||||
from src.skin_system.skin_runtime import (
|
||||
build_context,
|
||||
discover_skins,
|
||||
get_skins_directory,
|
||||
load_skin,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"SKIN_API_VERSION",
|
||||
"VIEW_MODEL_VERSION",
|
||||
"ScoreboardSkin",
|
||||
"SkinContext",
|
||||
"build_context",
|
||||
"discover_skins",
|
||||
"get_skins_directory",
|
||||
"load_skin",
|
||||
]
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Bot 7th",
|
||||
"is_live": true,
|
||||
"is_final": false,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "LAD",
|
||||
"home_id": "19",
|
||||
"home_score": "5",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "SF",
|
||||
"away_id": "26",
|
||||
"away_score": "3",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"status": "STATUS_IN_PROGRESS",
|
||||
"status_state": "in",
|
||||
"inning": 7,
|
||||
"inning_half": "bottom",
|
||||
"balls": 3,
|
||||
"strikes": 2,
|
||||
"outs": 2,
|
||||
"bases_occupied": [
|
||||
true,
|
||||
true,
|
||||
true
|
||||
],
|
||||
"start_time": "2026-07-16T23:05:00Z",
|
||||
"series_summary": "LAD leads 2-1"
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Final",
|
||||
"is_live": false,
|
||||
"is_final": true,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "LAD",
|
||||
"home_id": "19",
|
||||
"home_score": "5",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "SF",
|
||||
"away_id": "26",
|
||||
"away_score": "3",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"status": "STATUS_FINAL",
|
||||
"status_state": "post",
|
||||
"inning": 9,
|
||||
"inning_half": "top",
|
||||
"balls": 0,
|
||||
"strikes": 0,
|
||||
"outs": 3,
|
||||
"bases_occupied": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
],
|
||||
"start_time": "2026-07-16T23:05:00Z",
|
||||
"series_summary": "Series tied 2-2"
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "7:05 PM",
|
||||
"is_live": false,
|
||||
"is_final": false,
|
||||
"is_upcoming": true,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "LAD",
|
||||
"home_id": "19",
|
||||
"home_score": "0",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "SF",
|
||||
"away_id": "26",
|
||||
"away_score": "0",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"status": "STATUS_SCHEDULED",
|
||||
"status_state": "pre",
|
||||
"inning": 0,
|
||||
"inning_half": "top",
|
||||
"balls": 0,
|
||||
"strikes": 0,
|
||||
"outs": 0,
|
||||
"bases_occupied": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
],
|
||||
"start_time": "2026-07-16T23:05:00Z",
|
||||
"series_summary": ""
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Q4 2:34",
|
||||
"is_live": true,
|
||||
"is_final": false,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "OKC",
|
||||
"home_id": "19",
|
||||
"home_score": "5",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "",
|
||||
"away_abbr": "MIN",
|
||||
"away_id": "26",
|
||||
"away_score": "3",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "",
|
||||
"is_within_window": true,
|
||||
"period": 4,
|
||||
"period_text": "Q4",
|
||||
"clock": "2:34"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Final",
|
||||
"is_live": false,
|
||||
"is_final": true,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "OKC",
|
||||
"home_id": "19",
|
||||
"home_score": "5",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "",
|
||||
"away_abbr": "MIN",
|
||||
"away_id": "26",
|
||||
"away_score": "3",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "",
|
||||
"is_within_window": true,
|
||||
"period": 4,
|
||||
"period_text": "Final",
|
||||
"clock": "0:00"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "7:05 PM",
|
||||
"is_live": false,
|
||||
"is_final": false,
|
||||
"is_upcoming": true,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "OKC",
|
||||
"home_id": "19",
|
||||
"home_score": "0",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "",
|
||||
"away_abbr": "MIN",
|
||||
"away_id": "26",
|
||||
"away_score": "0",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "",
|
||||
"is_within_window": true,
|
||||
"period": 0,
|
||||
"period_text": "",
|
||||
"clock": "0:00"
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Q3 8:12",
|
||||
"is_live": true,
|
||||
"is_final": false,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "KC",
|
||||
"home_id": "19",
|
||||
"home_score": "21",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "BUF",
|
||||
"away_id": "26",
|
||||
"away_score": "17",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"period": 3,
|
||||
"period_text": "Q3",
|
||||
"clock": "8:12",
|
||||
"home_timeouts": 2,
|
||||
"away_timeouts": 3,
|
||||
"down_distance_text": "3rd & 4",
|
||||
"down_distance_text_long": "3rd & 4 at KC 22",
|
||||
"is_redzone": true,
|
||||
"possession": "12",
|
||||
"possession_indicator": "away",
|
||||
"scoring_event": null
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Final",
|
||||
"is_live": false,
|
||||
"is_final": true,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "KC",
|
||||
"home_id": "19",
|
||||
"home_score": "21",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "BUF",
|
||||
"away_id": "26",
|
||||
"away_score": "17",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"period": 4,
|
||||
"period_text": "Final",
|
||||
"clock": "0:00",
|
||||
"home_timeouts": 0,
|
||||
"away_timeouts": 0,
|
||||
"down_distance_text": "",
|
||||
"down_distance_text_long": "",
|
||||
"is_redzone": false,
|
||||
"possession": null,
|
||||
"possession_indicator": null,
|
||||
"scoring_event": null
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "7:05 PM",
|
||||
"is_live": false,
|
||||
"is_final": false,
|
||||
"is_upcoming": true,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "KC",
|
||||
"home_id": "19",
|
||||
"home_score": "0",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "BUF",
|
||||
"away_id": "26",
|
||||
"away_score": "0",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"period": 0,
|
||||
"period_text": "",
|
||||
"clock": "0:00",
|
||||
"home_timeouts": 3,
|
||||
"away_timeouts": 3,
|
||||
"down_distance_text": "",
|
||||
"down_distance_text_long": "",
|
||||
"is_redzone": false,
|
||||
"possession": null,
|
||||
"possession_indicator": null,
|
||||
"scoring_event": null
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "P3 14:55",
|
||||
"is_live": true,
|
||||
"is_final": false,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "COL",
|
||||
"home_id": "19",
|
||||
"home_score": "2",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "VGK",
|
||||
"away_id": "26",
|
||||
"away_score": "2",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"period": 3,
|
||||
"period_text": "P3",
|
||||
"clock": "14:55",
|
||||
"power_play": true,
|
||||
"penalties": [],
|
||||
"home_shots": 27,
|
||||
"away_shots": 31
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "Final/OT",
|
||||
"is_live": false,
|
||||
"is_final": true,
|
||||
"is_upcoming": false,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "COL",
|
||||
"home_id": "19",
|
||||
"home_score": "3",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "VGK",
|
||||
"away_id": "26",
|
||||
"away_score": "2",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"period": 5,
|
||||
"period_text": "Final/OT",
|
||||
"clock": "0:00",
|
||||
"power_play": false,
|
||||
"penalties": [],
|
||||
"home_shots": 35,
|
||||
"away_shots": 33
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"id": "401570001",
|
||||
"game_time": "7:05PM",
|
||||
"game_date": "Jul 16th",
|
||||
"start_time_utc": "2026-07-16T23:05:00+00:00",
|
||||
"status_text": "7:05 PM",
|
||||
"is_live": false,
|
||||
"is_final": false,
|
||||
"is_upcoming": true,
|
||||
"is_halftime": false,
|
||||
"is_period_break": false,
|
||||
"home_abbr": "COL",
|
||||
"home_id": "19",
|
||||
"home_score": "0",
|
||||
"home_logo_path": "src/skin_system/fixtures/placeholder_home.png",
|
||||
"home_logo_url": null,
|
||||
"home_record": "58-33",
|
||||
"away_abbr": "VGK",
|
||||
"away_id": "26",
|
||||
"away_score": "0",
|
||||
"away_logo_path": "src/skin_system/fixtures/placeholder_away.png",
|
||||
"away_logo_url": null,
|
||||
"away_record": "49-42",
|
||||
"is_within_window": true,
|
||||
"period": 0,
|
||||
"period_text": "",
|
||||
"clock": "0:00",
|
||||
"power_play": false,
|
||||
"penalties": [],
|
||||
"home_shots": 0,
|
||||
"away_shots": 0
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 444 B |
Binary file not shown.
|
After Width: | Height: | Size: 446 B |
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
Skin API: the classes a skin author works with.
|
||||
|
||||
A skin is a directory under skins/<skin-id>/ containing a skin.json
|
||||
manifest and a Python module exposing a ScoreboardSkin subclass. The
|
||||
host (a sports scoreboard's base classes) builds a SkinContext per
|
||||
render and calls render_live / render_recent / render_upcoming with the
|
||||
game view model. The skin draws onto ctx.canvas and returns True; the
|
||||
host composites the canvas onto the display. A skin never talks to the
|
||||
display, the network, or the plugin directly.
|
||||
|
||||
Skin API Version: 1.0.0
|
||||
View Model Version: 1.0
|
||||
"""
|
||||
|
||||
from abc import ABC
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Dict, Optional, Tuple, Union
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
try:
|
||||
import freetype
|
||||
except ImportError: # pragma: no cover - freetype ships with the project deps
|
||||
freetype = None
|
||||
|
||||
from src.adaptive_layout import FitResult, LayoutContext, Region
|
||||
|
||||
# Major must match a skin manifest's skin_api_version major or the skin
|
||||
# is refused at load time (renames/removals bump major; additions minor).
|
||||
SKIN_API_VERSION = "1.0.0"
|
||||
|
||||
# Version of the guaranteed `game` dict keys (see docs/CREATING_SKINS.md).
|
||||
VIEW_MODEL_VERSION = "1.0"
|
||||
|
||||
|
||||
def _draw_bdf_text_on(draw: ImageDraw.ImageDraw, text: str, x: int, y: int,
|
||||
color: Tuple[int, int, int], face: Any,
|
||||
clip_w: int, clip_h: int) -> None:
|
||||
"""Render a freetype BDF face glyph-by-glyph onto an arbitrary canvas.
|
||||
|
||||
DisplayManager._draw_bdf_text only draws onto the panel image; skins
|
||||
draw onto their own canvas, so the fitted-font path (fit_text can
|
||||
return freetype faces) needs this standalone equivalent.
|
||||
"""
|
||||
try:
|
||||
ascender_px = face.size.ascender >> 6
|
||||
except Exception:
|
||||
ascender_px = 0
|
||||
baseline_y = y + ascender_px
|
||||
for char in text:
|
||||
face.load_char(char)
|
||||
bitmap = face.glyph.bitmap
|
||||
glyph_left = face.glyph.bitmap_left
|
||||
glyph_top = face.glyph.bitmap_top
|
||||
for i in range(bitmap.rows):
|
||||
for j in range(bitmap.width):
|
||||
byte_index = i * bitmap.pitch + (j // 8)
|
||||
if byte_index < len(bitmap.buffer) and \
|
||||
bitmap.buffer[byte_index] & (1 << (7 - (j % 8))):
|
||||
px = x + glyph_left + j
|
||||
py = baseline_y - glyph_top + i
|
||||
if 0 <= px < clip_w and 0 <= py < clip_h:
|
||||
draw.point((px, py), fill=color)
|
||||
x += face.glyph.advance.x >> 6
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkinContext:
|
||||
"""Everything a skin may touch during one render call.
|
||||
|
||||
The canvas is a fresh RGB image sized to the current display (or
|
||||
vegas card). Draw onto it via the helpers below or raw ``draw``;
|
||||
never call display/update methods — the host composites the canvas.
|
||||
"""
|
||||
|
||||
canvas: Image.Image
|
||||
draw: ImageDraw.ImageDraw
|
||||
layout: LayoutContext
|
||||
width: int
|
||||
height: int
|
||||
fonts: Dict[str, Any]
|
||||
options: Dict[str, Any]
|
||||
logger: Any
|
||||
sport: Optional[str] = None
|
||||
view_model_version: str = VIEW_MODEL_VERSION
|
||||
# load_logo("home") / load_logo("away") -> RGBA PIL image or None.
|
||||
# Bound to the current game; hits the host's logo cache (never loads
|
||||
# from disk twice), downloads missing logos like the built-in layout.
|
||||
load_logo: Callable[[str], Optional[Image.Image]] = field(default=lambda side: None)
|
||||
# draw_text_outlined(text, (x, y), font, fill=..., outline_color=...)
|
||||
# — the classic scorebug outlined text, drawn onto this canvas.
|
||||
# TTF fonts only (ctx.fonts values are TTF); for ladder-fitted fonts
|
||||
# use draw_fit / draw_text, which handle BDF faces too.
|
||||
draw_text_outlined: Callable[..., None] = field(default=lambda *a, **k: None)
|
||||
|
||||
def draw_text(self, text: str, x: int, y: int,
|
||||
color: Tuple[int, int, int] = (255, 255, 255),
|
||||
font: Any = None) -> None:
|
||||
"""Draw text at a top-left position, handling both PIL fonts and
|
||||
the freetype BDF faces that layout.fit_text can return."""
|
||||
if font is None:
|
||||
font = self.fonts.get('time')
|
||||
if freetype is not None and isinstance(font, freetype.Face):
|
||||
_draw_bdf_text_on(self.draw, text, int(x), int(y), color, font,
|
||||
self.width, self.height)
|
||||
else:
|
||||
self.draw.text((int(x), int(y)), text, font=font, fill=color)
|
||||
|
||||
def draw_fit(self, fit: FitResult, box: Union[Region, Tuple[int, int]],
|
||||
color: Tuple[int, int, int] = (255, 255, 255),
|
||||
align: str = "center", valign: str = "center") -> None:
|
||||
"""Draw a layout.fit_text() result aligned within a Region — the
|
||||
canvas-local equivalent of adaptive_layout.draw_fitted_text."""
|
||||
region = box if isinstance(box, Region) else Region(0, 0, box[0], box[1])
|
||||
x, y = region.align_xy(fit.width, fit.height, align, valign)
|
||||
self.draw_text(fit.text, x, y - fit.y_offset, color=color, font=fit.font)
|
||||
|
||||
def draw_image(self, img: Optional[Image.Image],
|
||||
box: Union[Region, Tuple[int, int]], *,
|
||||
mode: str = "contain", align: str = "center",
|
||||
valign: str = "center", cache_key: Any = None) -> None:
|
||||
"""Fit an image (a logo, art) into a Region and paste it, honoring
|
||||
alpha. Silently no-ops on None so `ctx.draw_image(ctx.load_logo(
|
||||
'home'), ...)` stays safe when a logo is missing."""
|
||||
if img is None:
|
||||
return
|
||||
region = box if isinstance(box, Region) else Region(0, 0, box[0], box[1])
|
||||
fitted = self.layout.fit_image(img, region, mode=mode,
|
||||
cache_key=cache_key)
|
||||
result = fitted.image # fit_image returns an ImageFitResult (always RGBA)
|
||||
if result is None:
|
||||
return
|
||||
x, y = region.align_xy(result.width, result.height, align, valign)
|
||||
self.canvas.paste(result, (int(x), int(y)), result)
|
||||
|
||||
|
||||
class ScoreboardSkin(ABC):
|
||||
"""Base class for scoreboard skins.
|
||||
|
||||
Override only the modes you want to restyle; any mode you leave
|
||||
unimplemented (or return False from) falls back to the plugin's
|
||||
built-in renderer, so a live-only skin still gets recent/upcoming
|
||||
screens for free.
|
||||
|
||||
Skins should be stateless: three host instances (live, recent,
|
||||
upcoming) each hold their own skin instance, and a render must be
|
||||
derivable from (ctx, game) alone.
|
||||
"""
|
||||
|
||||
SKIN_API_VERSION = SKIN_API_VERSION
|
||||
|
||||
def __init__(self, manifest: Dict[str, Any], options: Dict[str, Any]):
|
||||
self.manifest = manifest
|
||||
self.options = options or {}
|
||||
|
||||
def render_live(self, ctx: SkinContext, game: Dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
def render_recent(self, ctx: SkinContext, game: Dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
def render_upcoming(self, ctx: SkinContext, game: Dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
def render_vegas_card(self, ctx: SkinContext,
|
||||
game: Dict[str, Any]) -> Optional[Image.Image]:
|
||||
"""Render one vegas scroll card at ctx.width x ctx.height. Return
|
||||
the finished image, or None to let the host use its default vegas
|
||||
rendering (which captures the regular display output)."""
|
||||
return None
|
||||
@@ -0,0 +1,352 @@
|
||||
"""
|
||||
Skin runtime: discovery, validation, loading, and context building.
|
||||
|
||||
Deliberately generic — this module knows nothing about sports beyond
|
||||
passing a `sport` label through; the sports flavor lives in skin_base
|
||||
(ScoreboardSkin) and in the hosts that call build_context.
|
||||
|
||||
Every failure path here logs and returns None: a broken or missing skin
|
||||
must never take down the plugin that references it — the host falls
|
||||
back to its built-in renderer.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from src.adaptive_layout import LayoutContext
|
||||
from src.logging_config import get_logger
|
||||
from src.skin_system.skin_base import (
|
||||
SKIN_API_VERSION,
|
||||
ScoreboardSkin,
|
||||
SkinContext,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
_REQUIRED_MANIFEST_FIELDS = ("id", "name", "version", "skin_api_version", "class_name")
|
||||
_DEFAULT_ENTRY_POINT = "skin.py"
|
||||
|
||||
_lock = threading.RLock()
|
||||
# skins_dir -> (fingerprint, {skin_id: manifest+path})
|
||||
_discovery_cache: Dict[str, Tuple[Tuple, Dict[str, Dict[str, Any]]]] = {}
|
||||
|
||||
_shared_layout_font_manager: Optional[Any] = None
|
||||
|
||||
|
||||
def _get_font_manager() -> Any:
|
||||
"""Shared FontManager for skin LayoutContexts. SportsCore hosts don't
|
||||
carry a plugin_manager, so skins share one module-level FontManager —
|
||||
the same shape as base_plugin._fallback_font_manager, constructed
|
||||
directly so rendering never has to import the whole plugin system."""
|
||||
global _shared_layout_font_manager
|
||||
if _shared_layout_font_manager is None:
|
||||
from src.font_manager import FontManager
|
||||
_shared_layout_font_manager = FontManager({})
|
||||
return _shared_layout_font_manager
|
||||
|
||||
|
||||
def get_skins_directory() -> Path:
|
||||
"""Central skins directory: <project_root>/skins. Lives outside the
|
||||
plugin directories on purpose — plugin reinstall/update deletes the
|
||||
whole plugin directory, and a skin must survive that."""
|
||||
return Path(__file__).resolve().parents[2] / "skins"
|
||||
|
||||
|
||||
def _major(version: str) -> Optional[int]:
|
||||
try:
|
||||
return int(str(version).split(".")[0])
|
||||
except (ValueError, AttributeError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def _read_manifest(skin_dir: Path) -> Optional[Dict[str, Any]]:
|
||||
manifest_path = skin_dir / "skin.json"
|
||||
if not manifest_path.is_file():
|
||||
return None
|
||||
try:
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
manifest = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
logger.error("Skin manifest %s is unreadable: %s", manifest_path, e)
|
||||
return None
|
||||
missing = [k for k in _REQUIRED_MANIFEST_FIELDS if not manifest.get(k)]
|
||||
if missing:
|
||||
logger.error("Skin manifest %s missing required fields: %s",
|
||||
manifest_path, ", ".join(missing))
|
||||
return None
|
||||
if manifest["id"] != skin_dir.name:
|
||||
logger.warning("Skin manifest id %r does not match directory name %r",
|
||||
manifest["id"], skin_dir.name)
|
||||
manifest["_skin_dir"] = str(skin_dir)
|
||||
return manifest
|
||||
|
||||
|
||||
def _discovery_fingerprint(skins_dir: Path) -> Optional[Tuple]:
|
||||
"""Cache key for a skins directory: its mtime plus every skin.json's
|
||||
(path, mtime). The directory mtime alone misses in-place manifest edits
|
||||
(a skin updated without adding/removing entries)."""
|
||||
try:
|
||||
parts = [skins_dir.stat().st_mtime]
|
||||
for manifest_path in sorted(skins_dir.glob("*/skin.json")):
|
||||
parts.append((str(manifest_path), manifest_path.stat().st_mtime))
|
||||
return tuple(parts)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def discover_skins(skins_dir: Optional[Path] = None,
|
||||
force_refresh: bool = False) -> Dict[str, Dict[str, Any]]:
|
||||
"""Return {skin_id: manifest} for every valid skin package installed.
|
||||
|
||||
Cached per directory and invalidated when the directory or any
|
||||
skin.json changes; pass force_refresh to bypass.
|
||||
"""
|
||||
skins_dir = Path(skins_dir) if skins_dir else get_skins_directory()
|
||||
cache_key = str(skins_dir)
|
||||
fingerprint = _discovery_fingerprint(skins_dir)
|
||||
if fingerprint is None:
|
||||
return {}
|
||||
|
||||
with _lock:
|
||||
cached = _discovery_cache.get(cache_key)
|
||||
if cached and not force_refresh and cached[0] == fingerprint:
|
||||
return dict(cached[1])
|
||||
|
||||
skins: Dict[str, Dict[str, Any]] = {}
|
||||
for entry in sorted(skins_dir.iterdir()):
|
||||
if not entry.is_dir() or entry.name.startswith((".", "_")):
|
||||
continue
|
||||
manifest = _read_manifest(entry)
|
||||
if manifest:
|
||||
skins[manifest["id"]] = manifest
|
||||
_discovery_cache[cache_key] = (fingerprint, skins)
|
||||
return dict(skins)
|
||||
|
||||
|
||||
def skin_targets(manifest: Dict[str, Any]) -> Tuple[list, list]:
|
||||
"""(sports, sport_keys) a skin declares it supports."""
|
||||
targets = manifest.get("targets") or {}
|
||||
return (list(targets.get("sports") or []),
|
||||
list(targets.get("sport_keys") or []))
|
||||
|
||||
|
||||
def skin_matches_target(manifest: Dict[str, Any], sport: Optional[str],
|
||||
sport_key: Optional[str]) -> bool:
|
||||
"""True when the skin declares support for this sport family or exact
|
||||
sport key. A skin with no targets at all matches everything."""
|
||||
sports, sport_keys = skin_targets(manifest)
|
||||
if not sports and not sport_keys:
|
||||
return True
|
||||
if sport and sport in sports:
|
||||
return True
|
||||
if sport_key and sport_key in sport_keys:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def skins_for_plugin(plugin_id: str,
|
||||
skins: Optional[Dict[str, Dict[str, Any]]] = None) -> Dict[str, Dict[str, Any]]:
|
||||
"""Installed skins that plausibly apply to a plugin, for UI dropdowns.
|
||||
|
||||
A skin matches when the plugin id is listed in targets.plugins, or any
|
||||
declared sport / sport_key appears as a token of the plugin id (so a
|
||||
skin targeting sports=["baseball"] matches "baseball-scoreboard", and
|
||||
sport_keys=["milb"] matches "milb-scoreboard")."""
|
||||
if skins is None:
|
||||
skins = discover_skins()
|
||||
tokens = set(str(plugin_id).lower().replace("-", "_").split("_"))
|
||||
matched = {}
|
||||
for skin_id, manifest in skins.items():
|
||||
targets = manifest.get("targets") or {}
|
||||
if plugin_id in (targets.get("plugins") or []):
|
||||
matched[skin_id] = manifest
|
||||
continue
|
||||
sports, sport_keys = skin_targets(manifest)
|
||||
if any(str(t).lower() in tokens for t in sports + sport_keys):
|
||||
matched[skin_id] = manifest
|
||||
return matched
|
||||
|
||||
|
||||
def _load_skin_module(skin_id: str, skin_dir: Path, entry_point: str) -> Optional[Any]:
|
||||
"""Import the skin's entry module under a namespaced sys.modules key,
|
||||
namespacing its sibling .py files the same way — the collision-
|
||||
avoidance scheme plugins use (plugin_loader._namespace_plugin_modules),
|
||||
so two skins can both ship a helpers.py.
|
||||
|
||||
The entry module is cached: the live/recent/upcoming hosts all load
|
||||
the same skin, and only the first load executes any code. (A skin
|
||||
whose *code* changed on disk needs a service restart to take effect —
|
||||
Python modules can't be safely hot-swapped.)
|
||||
"""
|
||||
entry_path = skin_dir / entry_point
|
||||
if not entry_path.is_file():
|
||||
logger.error("Skin '%s' entry point not found: %s", skin_id, entry_path)
|
||||
return None
|
||||
|
||||
module_name = f"_skin_{skin_id}_{Path(entry_point).stem}"
|
||||
with _lock:
|
||||
cached_entry = sys.modules.get(module_name)
|
||||
if cached_entry is not None:
|
||||
return cached_entry
|
||||
|
||||
# Import siblings under their namespaced alias, and *bind* the bare
|
||||
# name (cached or fresh) so `import helpers` inside the entry module
|
||||
# resolves to this skin's copy. The bare bindings are transient —
|
||||
# restored below so another skin's identically-named sibling can't
|
||||
# be shadowed by ours.
|
||||
replaced_bare: Dict[str, Any] = {}
|
||||
try:
|
||||
for sibling in skin_dir.glob("*.py"):
|
||||
if sibling.name == entry_point:
|
||||
continue
|
||||
alias = f"_skin_{skin_id}_{sibling.stem}"
|
||||
module = sys.modules.get(alias)
|
||||
if module is None:
|
||||
spec = importlib.util.spec_from_file_location(alias, sibling)
|
||||
if not spec or not spec.loader:
|
||||
continue
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[alias] = module
|
||||
replaced_bare.setdefault(sibling.stem, sys.modules.get(sibling.stem))
|
||||
sys.modules[sibling.stem] = module
|
||||
try:
|
||||
spec.loader.exec_module(module)
|
||||
except Exception as e:
|
||||
logger.error("Skin '%s' sibling module %s failed to import: %s",
|
||||
skin_id, sibling.name, e, exc_info=True)
|
||||
sys.modules.pop(alias, None)
|
||||
return None
|
||||
else:
|
||||
replaced_bare.setdefault(sibling.stem, sys.modules.get(sibling.stem))
|
||||
sys.modules[sibling.stem] = module
|
||||
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(module_name, entry_path)
|
||||
if not spec or not spec.loader:
|
||||
logger.error("Skin '%s': could not create import spec for %s",
|
||||
skin_id, entry_path)
|
||||
return None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[module_name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
except Exception as e:
|
||||
sys.modules.pop(module_name, None)
|
||||
logger.error("Skin '%s' failed to import: %s", skin_id, e, exc_info=True)
|
||||
return None
|
||||
finally:
|
||||
for bare_name, previous in replaced_bare.items():
|
||||
if previous is None:
|
||||
sys.modules.pop(bare_name, None)
|
||||
else:
|
||||
sys.modules[bare_name] = previous
|
||||
|
||||
|
||||
def load_skin(skin_id: str, sport: Optional[str] = None,
|
||||
sport_key: Optional[str] = None,
|
||||
options: Optional[Dict[str, Any]] = None,
|
||||
skins_dir: Optional[Path] = None) -> Optional[ScoreboardSkin]:
|
||||
"""Load and instantiate a skin. Returns None (after logging why) on
|
||||
any failure — callers treat None as 'use the built-in renderer'."""
|
||||
skins = discover_skins(skins_dir)
|
||||
manifest = skins.get(skin_id)
|
||||
if manifest is None:
|
||||
logger.warning("Skin '%s' is configured but not installed under %s; "
|
||||
"using built-in renderer",
|
||||
skin_id, skins_dir or get_skins_directory())
|
||||
return None
|
||||
|
||||
manifest_major = _major(manifest.get("skin_api_version"))
|
||||
api_major = _major(SKIN_API_VERSION)
|
||||
if manifest_major != api_major:
|
||||
logger.error("Skin '%s' targets skin API %s but this LEDMatrix "
|
||||
"provides %s — the skin needs an update; using "
|
||||
"built-in renderer",
|
||||
skin_id, manifest.get("skin_api_version"), SKIN_API_VERSION)
|
||||
return None
|
||||
|
||||
if not skin_matches_target(manifest, sport, sport_key):
|
||||
# Soft: the user explicitly configured it, so warn but load anyway
|
||||
# (a baseball skin may render an acceptable generic scoreboard).
|
||||
logger.warning("Skin '%s' does not declare support for sport=%r / "
|
||||
"sport_key=%r; loading anyway", skin_id, sport, sport_key)
|
||||
|
||||
skin_dir = Path(manifest["_skin_dir"])
|
||||
module = _load_skin_module(skin_id, skin_dir,
|
||||
manifest.get("entry_point", _DEFAULT_ENTRY_POINT))
|
||||
if module is None:
|
||||
return None
|
||||
|
||||
class_name = manifest["class_name"]
|
||||
skin_class = getattr(module, class_name, None)
|
||||
if skin_class is None or not isinstance(skin_class, type) or \
|
||||
not issubclass(skin_class, ScoreboardSkin):
|
||||
logger.error("Skin '%s': %s is missing or not a ScoreboardSkin subclass",
|
||||
skin_id, class_name)
|
||||
return None
|
||||
|
||||
try:
|
||||
return skin_class(manifest, options or {})
|
||||
except Exception as e:
|
||||
logger.error("Skin '%s' failed to instantiate: %s", skin_id, e, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def build_context(host: Any, game: Dict[str, Any],
|
||||
size: Optional[Tuple[int, int]] = None) -> SkinContext:
|
||||
"""Build a SkinContext for one render call.
|
||||
|
||||
`host` is a SportsCore-style object: display_manager, fonts, logger,
|
||||
sport, skin_options, _load_and_resize_logo, _draw_text_with_outline.
|
||||
`size` overrides the canvas size (vegas cards); default is the
|
||||
current display size read live from the display manager.
|
||||
"""
|
||||
if size is not None:
|
||||
width, height = int(size[0]), int(size[1])
|
||||
else:
|
||||
dm = host.display_manager
|
||||
width = getattr(dm, "width", None) or dm.matrix.width
|
||||
height = getattr(dm, "height", None) or dm.matrix.height
|
||||
|
||||
canvas = Image.new("RGB", (width, height), (0, 0, 0))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
layout = LayoutContext(width, height, _get_font_manager())
|
||||
|
||||
def load_logo(side: str) -> Optional[Image.Image]:
|
||||
if side not in ("home", "away"):
|
||||
return None
|
||||
try:
|
||||
logo_path = game.get(f"{side}_logo_path")
|
||||
if logo_path is not None and not isinstance(logo_path, Path):
|
||||
logo_path = Path(logo_path)
|
||||
return host._load_and_resize_logo(
|
||||
game.get(f"{side}_id"), game.get(f"{side}_abbr"),
|
||||
logo_path, game.get(f"{side}_logo_url"))
|
||||
except Exception as e:
|
||||
host.logger.warning("Skin logo load failed for %s: %s", side, e)
|
||||
return None
|
||||
|
||||
def draw_text_outlined(text, position, font, fill=(255, 255, 255),
|
||||
outline_color=(0, 0, 0)):
|
||||
host._draw_text_with_outline(draw, text, position, font,
|
||||
fill=fill, outline_color=outline_color)
|
||||
|
||||
return SkinContext(
|
||||
canvas=canvas,
|
||||
draw=draw,
|
||||
layout=layout,
|
||||
width=width,
|
||||
height=height,
|
||||
fonts=dict(host.fonts),
|
||||
options=dict(getattr(host, "skin_options", {}) or {}),
|
||||
logger=host.logger,
|
||||
sport=getattr(host, "sport", None),
|
||||
load_logo=load_logo,
|
||||
draw_text_outlined=draw_text_outlined,
|
||||
)
|
||||
@@ -21,6 +21,41 @@ class VegasModeConfig:
|
||||
scroll_speed: float = 50.0 # Pixels per second
|
||||
separator_width: int = 32 # Gap between plugins (pixels)
|
||||
|
||||
# Gap between rows contributed by the *same* plugin. separator_width marks
|
||||
# the handoff from one plugin to the next; applying it between every image
|
||||
# forced a 32px chasm between each row of a per-row ticker (the F1
|
||||
# scoreboard renders its own rows 4px apart), which both looked wrong and
|
||||
# silently inflated the width that plugin occupied.
|
||||
intra_plugin_gap: int = 8
|
||||
|
||||
# Content density
|
||||
#
|
||||
# Plugins that render onto a full-display canvas contribute that whole
|
||||
# canvas to the ticker, blank margins included. On a wide panel that is the
|
||||
# dominant source of dead air: a plugin drawing 35px of text on a 512px
|
||||
# canvas otherwise buys 9.5s of black at 50px/s. Trimming reclaims it.
|
||||
auto_trim: bool = True
|
||||
trim_threshold: int = 10 # Per-channel value a pixel must exceed to be "ink"
|
||||
content_padding: int = 8 # Blank columns kept either side of trimmed content
|
||||
min_plugin_width: int = 8 # Segments narrower than this after trim are dropped
|
||||
|
||||
# Columns of blank lead-in before the first item of a cycle. ScrollHelper
|
||||
# defaults this to a full display width, which reads as the display being
|
||||
# switched off at the start of every cycle.
|
||||
lead_in_width: int = 0
|
||||
|
||||
# How many plugins are composed into one scroll cycle. Kept separate from
|
||||
# buffer_ahead (which is only a prefetch low-water mark) because the two
|
||||
# were previously the same number: a buffer_ahead of 2 meant just 3 plugins
|
||||
# per cycle, so a 20-plugin install took seven cycles to come around.
|
||||
plugins_per_cycle: int = 6
|
||||
|
||||
# Cap on one plugin's share of a cycle, as a multiple of display width.
|
||||
# A single ticker returning 7,000px would otherwise hold the panel for over
|
||||
# two minutes. Overflow is deferred to later cycles rather than discarded.
|
||||
# 0 disables the cap.
|
||||
max_plugin_width_ratio: float = 3.0
|
||||
|
||||
# Plugin management
|
||||
plugin_order: List[str] = field(default_factory=list)
|
||||
excluded_plugins: Set[str] = field(default_factory=set)
|
||||
@@ -55,6 +90,15 @@ class VegasModeConfig:
|
||||
enabled=vegas_config.get('enabled', False),
|
||||
scroll_speed=float(vegas_config.get('scroll_speed', 50.0)),
|
||||
separator_width=int(vegas_config.get('separator_width', 32)),
|
||||
intra_plugin_gap=int(vegas_config.get('intra_plugin_gap', 8)),
|
||||
auto_trim=vegas_config.get('auto_trim', True),
|
||||
trim_threshold=int(vegas_config.get('trim_threshold', 10)),
|
||||
content_padding=int(vegas_config.get('content_padding', 8)),
|
||||
min_plugin_width=int(vegas_config.get('min_plugin_width', 8)),
|
||||
lead_in_width=int(vegas_config.get('lead_in_width', 0)),
|
||||
plugins_per_cycle=int(vegas_config.get('plugins_per_cycle', 6)),
|
||||
max_plugin_width_ratio=float(
|
||||
vegas_config.get('max_plugin_width_ratio', 3.0)),
|
||||
plugin_order=list(vegas_config.get('plugin_order', [])),
|
||||
excluded_plugins=set(vegas_config.get('excluded_plugins', [])),
|
||||
target_fps=int(vegas_config.get('target_fps', 125)),
|
||||
@@ -72,6 +116,14 @@ class VegasModeConfig:
|
||||
'enabled': self.enabled,
|
||||
'scroll_speed': self.scroll_speed,
|
||||
'separator_width': self.separator_width,
|
||||
'intra_plugin_gap': self.intra_plugin_gap,
|
||||
'auto_trim': self.auto_trim,
|
||||
'trim_threshold': self.trim_threshold,
|
||||
'content_padding': self.content_padding,
|
||||
'min_plugin_width': self.min_plugin_width,
|
||||
'lead_in_width': self.lead_in_width,
|
||||
'plugins_per_cycle': self.plugins_per_cycle,
|
||||
'max_plugin_width_ratio': self.max_plugin_width_ratio,
|
||||
'plugin_order': self.plugin_order,
|
||||
'excluded_plugins': list(self.excluded_plugins),
|
||||
'target_fps': self.target_fps,
|
||||
@@ -157,6 +209,49 @@ class VegasModeConfig:
|
||||
if self.buffer_ahead > 5:
|
||||
errors.append(f"buffer_ahead must be <= 5, got {self.buffer_ahead}")
|
||||
|
||||
if self.intra_plugin_gap < 0:
|
||||
errors.append(
|
||||
f"intra_plugin_gap must be >= 0, got {self.intra_plugin_gap}")
|
||||
if self.intra_plugin_gap > 128:
|
||||
errors.append(
|
||||
f"intra_plugin_gap must be <= 128, got {self.intra_plugin_gap}")
|
||||
|
||||
if not 0 <= self.trim_threshold <= 254:
|
||||
errors.append(
|
||||
f"trim_threshold must be between 0 and 254, got {self.trim_threshold}")
|
||||
|
||||
if self.content_padding < 0:
|
||||
errors.append(
|
||||
f"content_padding must be >= 0, got {self.content_padding}")
|
||||
if self.content_padding > 128:
|
||||
errors.append(
|
||||
f"content_padding must be <= 128, got {self.content_padding}")
|
||||
|
||||
if self.min_plugin_width < 0:
|
||||
errors.append(
|
||||
f"min_plugin_width must be >= 0, got {self.min_plugin_width}")
|
||||
# Bounded because every segment narrower than this is dropped — an
|
||||
# unbounded value would discard every plugin and leave a blank ticker.
|
||||
if self.min_plugin_width > 512:
|
||||
errors.append(
|
||||
f"min_plugin_width must be <= 512, got {self.min_plugin_width}")
|
||||
|
||||
if self.lead_in_width < 0:
|
||||
errors.append(
|
||||
f"lead_in_width must be >= 0, got {self.lead_in_width}")
|
||||
|
||||
if self.plugins_per_cycle < 1:
|
||||
errors.append(
|
||||
f"plugins_per_cycle must be >= 1, got {self.plugins_per_cycle}")
|
||||
if self.plugins_per_cycle > 50:
|
||||
errors.append(
|
||||
f"plugins_per_cycle must be <= 50, got {self.plugins_per_cycle}")
|
||||
|
||||
if self.max_plugin_width_ratio < 0:
|
||||
errors.append(
|
||||
"max_plugin_width_ratio must be >= 0 "
|
||||
f"(0 disables the cap), got {self.max_plugin_width_ratio}")
|
||||
|
||||
return errors
|
||||
|
||||
def update(self, new_config: Dict[str, Any]) -> None:
|
||||
@@ -174,6 +269,23 @@ class VegasModeConfig:
|
||||
self.scroll_speed = float(vegas_config['scroll_speed'])
|
||||
if 'separator_width' in vegas_config:
|
||||
self.separator_width = int(vegas_config['separator_width'])
|
||||
if 'intra_plugin_gap' in vegas_config:
|
||||
self.intra_plugin_gap = int(vegas_config['intra_plugin_gap'])
|
||||
if 'auto_trim' in vegas_config:
|
||||
self.auto_trim = vegas_config['auto_trim']
|
||||
if 'trim_threshold' in vegas_config:
|
||||
self.trim_threshold = int(vegas_config['trim_threshold'])
|
||||
if 'content_padding' in vegas_config:
|
||||
self.content_padding = int(vegas_config['content_padding'])
|
||||
if 'min_plugin_width' in vegas_config:
|
||||
self.min_plugin_width = int(vegas_config['min_plugin_width'])
|
||||
if 'lead_in_width' in vegas_config:
|
||||
self.lead_in_width = int(vegas_config['lead_in_width'])
|
||||
if 'plugins_per_cycle' in vegas_config:
|
||||
self.plugins_per_cycle = int(vegas_config['plugins_per_cycle'])
|
||||
if 'max_plugin_width_ratio' in vegas_config:
|
||||
self.max_plugin_width_ratio = float(
|
||||
vegas_config['max_plugin_width_ratio'])
|
||||
if 'plugin_order' in vegas_config:
|
||||
self.plugin_order = list(vegas_config['plugin_order'])
|
||||
if 'excluded_plugins' in vegas_config:
|
||||
|
||||
@@ -64,7 +64,7 @@ class VegasModeCoordinator:
|
||||
self.plugin_manager = plugin_manager
|
||||
|
||||
# Initialize components
|
||||
self.plugin_adapter = PluginAdapter(display_manager)
|
||||
self.plugin_adapter = PluginAdapter(display_manager, self.vegas_config)
|
||||
self.stream_manager = StreamManager(
|
||||
self.vegas_config,
|
||||
plugin_manager,
|
||||
@@ -505,6 +505,10 @@ class VegasModeCoordinator:
|
||||
# Update components
|
||||
self.render_pipeline.update_config(new_vegas_config)
|
||||
self.stream_manager.config = new_vegas_config
|
||||
self.plugin_adapter.config = new_vegas_config
|
||||
# Cached segments were trimmed under the old settings, so drop them
|
||||
# or a changed trim/padding value would not visibly take effect.
|
||||
self.plugin_adapter.invalidate_cache()
|
||||
|
||||
# Force refresh of stream manager to pick up plugin_order/buffer changes
|
||||
self.stream_manager._last_refresh = 0
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
"""
|
||||
Geometry primitives for Vegas Mode.
|
||||
|
||||
Pure, side-effect-free measurements over PIL images. Two consumers:
|
||||
|
||||
- ``PluginAdapter`` trims the blank margins plugins bake into their content
|
||||
before it enters the ticker (see ``trim_to_content``).
|
||||
- ``scripts/dev/vegas_audit.py`` reports how much of the composed ticker is
|
||||
dead space (see ``dead_window_stats``).
|
||||
|
||||
Keeping both on the same primitives means the number the audit reports is the
|
||||
number the trimmer acted on.
|
||||
|
||||
All column scans go through numpy: a Python-level per-column loop over a
|
||||
17,000px-wide ticker image takes seconds, which is far too slow for the render
|
||||
path.
|
||||
"""
|
||||
|
||||
from typing import NamedTuple, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
# A pixel counts as "ink" when any channel exceeds this. Chosen to ignore the
|
||||
# 1-2/255 noise that JPEG-sourced logos and alpha compositing leave behind in
|
||||
# nominally black areas, while still treating any deliberately drawn dark grey
|
||||
# as real content.
|
||||
DEFAULT_INK_THRESHOLD = 10
|
||||
|
||||
# A window counts as "dead" when this fraction of its columns carry no ink.
|
||||
DEFAULT_DEAD_WINDOW_RATIO = 0.95
|
||||
|
||||
|
||||
def column_has_ink(img: Image.Image, threshold: int = DEFAULT_INK_THRESHOLD) -> np.ndarray:
|
||||
"""
|
||||
Return a boolean array, one entry per image column, True where the column
|
||||
contains at least one pixel brighter than ``threshold`` in any channel.
|
||||
|
||||
Args:
|
||||
img: Image to scan (converted to RGB internally)
|
||||
threshold: Per-channel value a pixel must exceed to count as ink
|
||||
|
||||
Returns:
|
||||
Bool array of shape (width,)
|
||||
"""
|
||||
arr = np.asarray(img if img.mode == 'RGB' else img.convert('RGB'))
|
||||
if arr.ndim != 3:
|
||||
# Degenerate/empty image — treat every column as blank.
|
||||
return np.zeros(img.width, dtype=bool)
|
||||
# Collapse rows and channels: a column is ink if any pixel in it is bright.
|
||||
return arr.max(axis=(0, 2)) > threshold
|
||||
|
||||
|
||||
def content_bounds(
|
||||
img: Image.Image, threshold: int = DEFAULT_INK_THRESHOLD
|
||||
) -> Optional[Tuple[int, int]]:
|
||||
"""
|
||||
Find the first and last columns containing ink.
|
||||
|
||||
Args:
|
||||
img: Image to measure
|
||||
threshold: Ink threshold
|
||||
|
||||
Returns:
|
||||
(first_col, last_col) inclusive, or None if the image is entirely blank
|
||||
"""
|
||||
ink = column_has_ink(img, threshold)
|
||||
if not ink.any():
|
||||
return None
|
||||
first = int(ink.argmax())
|
||||
last = len(ink) - 1 - int(ink[::-1].argmax())
|
||||
return first, last
|
||||
|
||||
|
||||
class TrimResult(NamedTuple):
|
||||
"""Outcome of a ``trim_to_content`` call."""
|
||||
|
||||
image: Optional[Image.Image] # None when the source was entirely blank
|
||||
original_width: int
|
||||
trimmed_left: int
|
||||
trimmed_right: int
|
||||
|
||||
@property
|
||||
def is_blank(self) -> bool:
|
||||
"""True when the source image carried no ink at all."""
|
||||
return self.image is None
|
||||
|
||||
@property
|
||||
def width(self) -> int:
|
||||
"""Width after trimming (0 for a blank source)."""
|
||||
return 0 if self.image is None else self.image.width
|
||||
|
||||
@property
|
||||
def removed(self) -> int:
|
||||
"""Total columns removed."""
|
||||
return self.trimmed_left + self.trimmed_right
|
||||
|
||||
|
||||
def trim_to_content(
|
||||
img: Image.Image,
|
||||
threshold: int = DEFAULT_INK_THRESHOLD,
|
||||
padding: int = 0,
|
||||
) -> TrimResult:
|
||||
"""
|
||||
Crop blank columns off the left and right edges of an image.
|
||||
|
||||
Only the outer edges are considered. Blank columns *between* two pieces of
|
||||
content are deliberately preserved — those are the plugin's own layout
|
||||
(e.g. a logo on the left and a score on the right), and closing them up
|
||||
would corrupt the design rather than reclaim dead space.
|
||||
|
||||
A plugin drawing on a non-black background is unaffected: every column of a
|
||||
filled background carries ink, so there is nothing to trim.
|
||||
|
||||
Args:
|
||||
img: Image to trim
|
||||
threshold: Ink threshold
|
||||
padding: Columns of the original blank margin to keep on each side, as
|
||||
breathing room. Capped at what the margin actually contains, so
|
||||
this never widens the image beyond its original bounds.
|
||||
|
||||
Returns:
|
||||
TrimResult. When the image is entirely blank, ``image`` is None and the
|
||||
caller decides whether to skip the plugin.
|
||||
"""
|
||||
bounds = content_bounds(img, threshold)
|
||||
if bounds is None:
|
||||
return TrimResult(None, img.width, 0, 0)
|
||||
|
||||
first, last = bounds
|
||||
pad = max(0, padding)
|
||||
left = max(0, first - pad)
|
||||
right = min(img.width, last + 1 + pad)
|
||||
|
||||
if left == 0 and right == img.width:
|
||||
return TrimResult(img, img.width, 0, 0)
|
||||
|
||||
cropped = img.crop((left, 0, right, img.height))
|
||||
return TrimResult(cropped, img.width, left, img.width - right)
|
||||
|
||||
|
||||
def find_blank_cut(
|
||||
img: Image.Image,
|
||||
target: int,
|
||||
search_radius: int,
|
||||
threshold: int = DEFAULT_INK_THRESHOLD,
|
||||
) -> int:
|
||||
"""
|
||||
Find a column near ``target`` that carries no ink, so an image can be cut
|
||||
there without slicing through a glyph or logo.
|
||||
|
||||
Used when a single oversized segment has to be narrowed to fit a width
|
||||
budget. Cutting at an arbitrary column would leave half a character
|
||||
hanging at the panel edge; snapping to the nearest gap hides the cut.
|
||||
|
||||
Args:
|
||||
img: Image to cut
|
||||
target: Preferred cut column
|
||||
search_radius: How far either side of ``target`` to look
|
||||
threshold: Ink threshold
|
||||
|
||||
Returns:
|
||||
A blank column within the search window, or ``target`` clamped to the
|
||||
image bounds when the window contains no blank column at all.
|
||||
"""
|
||||
width = img.width
|
||||
target = max(0, min(target, width))
|
||||
if search_radius <= 0 or width == 0:
|
||||
return target
|
||||
|
||||
ink = column_has_ink(img, threshold)
|
||||
lo = max(0, target - search_radius)
|
||||
hi = min(width - 1, target + search_radius)
|
||||
|
||||
# Walk outwards from target so the nearest gap wins.
|
||||
for offset in range(0, search_radius + 1):
|
||||
right = target + offset
|
||||
if right <= hi and not ink[right]:
|
||||
return right
|
||||
left = target - offset
|
||||
if left >= lo and not ink[left]:
|
||||
return left
|
||||
|
||||
return target
|
||||
|
||||
|
||||
class DeadWindowStats(NamedTuple):
|
||||
"""How much of a composed ticker reads as blank to a viewer."""
|
||||
|
||||
total_windows: int
|
||||
dead_windows: int
|
||||
longest_dead_run: int # consecutive dead windows (i.e. scroll steps)
|
||||
|
||||
@property
|
||||
def dead_ratio(self) -> float:
|
||||
"""Fraction of viewport positions that are effectively blank."""
|
||||
if self.total_windows <= 0:
|
||||
return 0.0
|
||||
return self.dead_windows / self.total_windows
|
||||
|
||||
|
||||
def dead_window_stats(
|
||||
img: Image.Image,
|
||||
viewport_width: int,
|
||||
threshold: int = DEFAULT_INK_THRESHOLD,
|
||||
dead_ratio: float = DEFAULT_DEAD_WINDOW_RATIO,
|
||||
step: int = 1,
|
||||
) -> DeadWindowStats:
|
||||
"""
|
||||
Slide a viewport across a composed ticker image and count how many
|
||||
positions are effectively blank.
|
||||
|
||||
This models what the viewer actually experiences: the ticker is only ever
|
||||
seen ``viewport_width`` columns at a time, so a stretch of blank wider than
|
||||
the viewport becomes a period where the panel looks switched off. Measuring
|
||||
per-window rather than per-column is what makes the result correspond to
|
||||
perceived dead time.
|
||||
|
||||
Args:
|
||||
img: Composed ticker image
|
||||
viewport_width: Display width in pixels
|
||||
threshold: Ink threshold
|
||||
dead_ratio: Fraction of blank columns for a window to count as dead
|
||||
step: Column stride between sampled windows. 1 is exact; larger values
|
||||
trade precision for speed on very wide images.
|
||||
|
||||
Returns:
|
||||
DeadWindowStats. ``longest_dead_run`` is in units of ``step`` columns,
|
||||
so multiply by ``step`` for pixels.
|
||||
"""
|
||||
if viewport_width <= 0 or img.width <= 0:
|
||||
return DeadWindowStats(0, 0, 0)
|
||||
|
||||
ink = column_has_ink(img, threshold)
|
||||
step = max(1, step)
|
||||
|
||||
# Prefix sum of ink counts lets each window be evaluated in constant time,
|
||||
# instead of re-summing viewport_width columns per position.
|
||||
prefix = np.concatenate(([0], np.cumsum(ink)))
|
||||
|
||||
# Only whole windows are sampled; a partial tail window would report
|
||||
# artificially dead because it has fewer columns to draw ink from.
|
||||
last_start = img.width - viewport_width
|
||||
if last_start < 0:
|
||||
# Image narrower than the viewport — evaluate it as a single window.
|
||||
blank_cols = len(ink) - int(prefix[-1])
|
||||
is_dead = blank_cols >= dead_ratio * len(ink)
|
||||
return DeadWindowStats(1, 1 if is_dead else 0, 1 if is_dead else 0)
|
||||
|
||||
starts = np.arange(0, last_start + 1, step)
|
||||
ink_counts = prefix[starts + viewport_width] - prefix[starts]
|
||||
blank_counts = viewport_width - ink_counts
|
||||
dead = blank_counts >= dead_ratio * viewport_width
|
||||
|
||||
longest = _longest_true_run(dead)
|
||||
return DeadWindowStats(len(starts), int(dead.sum()), longest)
|
||||
|
||||
|
||||
class CoverageStats(NamedTuple):
|
||||
"""How well-filled the viewport stays as the ticker scrolls past."""
|
||||
|
||||
total_windows: int
|
||||
mean_ink_ratio: float # average fraction of the viewport carrying ink
|
||||
min_ink_ratio: float # worst viewport position in the cycle
|
||||
sparse_windows: int # positions below the "looks empty" threshold
|
||||
longest_sparse_run: int # consecutive sparse positions, in steps
|
||||
|
||||
@property
|
||||
def sparse_ratio(self) -> float:
|
||||
"""Fraction of viewport positions that read as near-empty."""
|
||||
if self.total_windows <= 0:
|
||||
return 0.0
|
||||
return self.sparse_windows / self.total_windows
|
||||
|
||||
|
||||
def window_coverage_stats(
|
||||
img: Image.Image,
|
||||
viewport_width: int,
|
||||
threshold: int = DEFAULT_INK_THRESHOLD,
|
||||
sparse_ink_ratio: float = 0.10,
|
||||
step: int = 1,
|
||||
) -> CoverageStats:
|
||||
"""
|
||||
Measure how full the viewport stays across a whole scroll cycle.
|
||||
|
||||
``dead_window_stats`` only catches viewport positions that are *entirely*
|
||||
blank. That misses the more common complaint: a position holding one narrow
|
||||
sliver of content at the very edge, with the other 90% black. Such a
|
||||
position is not "dead" by that definition but still looks switched off.
|
||||
This function grades every position by how much ink it carries, so
|
||||
"there is always something to see" becomes measurable.
|
||||
|
||||
Args:
|
||||
img: Composed ticker image
|
||||
viewport_width: Display width in pixels
|
||||
threshold: Ink threshold
|
||||
sparse_ink_ratio: A position with less than this fraction of inked
|
||||
columns counts as reading near-empty
|
||||
step: Column stride between sampled positions
|
||||
|
||||
Returns:
|
||||
CoverageStats
|
||||
"""
|
||||
if viewport_width <= 0 or img.width <= 0:
|
||||
return CoverageStats(0, 0.0, 0.0, 0, 0)
|
||||
|
||||
ink = column_has_ink(img, threshold)
|
||||
step = max(1, step)
|
||||
prefix = np.concatenate(([0], np.cumsum(ink)))
|
||||
|
||||
last_start = img.width - viewport_width
|
||||
if last_start < 0:
|
||||
ratio = float(prefix[-1]) / viewport_width
|
||||
sparse = ratio < sparse_ink_ratio
|
||||
return CoverageStats(1, ratio, ratio, 1 if sparse else 0, 1 if sparse else 0)
|
||||
|
||||
starts = np.arange(0, last_start + 1, step)
|
||||
ratios = (prefix[starts + viewport_width] - prefix[starts]) / viewport_width
|
||||
sparse_flags = ratios < sparse_ink_ratio
|
||||
|
||||
return CoverageStats(
|
||||
total_windows=len(starts),
|
||||
mean_ink_ratio=float(ratios.mean()),
|
||||
min_ink_ratio=float(ratios.min()),
|
||||
sparse_windows=int(sparse_flags.sum()),
|
||||
longest_sparse_run=_longest_true_run(sparse_flags),
|
||||
)
|
||||
|
||||
|
||||
def _longest_true_run(flags: np.ndarray) -> int:
|
||||
"""Length of the longest consecutive run of True in a boolean array."""
|
||||
if flags.size == 0 or not flags.any():
|
||||
return 0
|
||||
# Reset a running counter at every False by subtracting the cumulative max
|
||||
# of the counter's value at the preceding False positions.
|
||||
idx = np.arange(len(flags))
|
||||
not_flag = ~flags
|
||||
# For each position, the index of the most recent False at or before it.
|
||||
last_false = np.maximum.accumulate(np.where(not_flag, idx, -1))
|
||||
run_lengths = idx - last_false
|
||||
return int(run_lengths[flags].max())
|
||||
@@ -11,6 +11,8 @@ import time
|
||||
from typing import Optional, List, Any, Tuple, Union, TYPE_CHECKING
|
||||
from PIL import Image
|
||||
|
||||
from src.vegas_mode.geometry import find_blank_cut, trim_to_content
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.plugin_system.base_plugin import BasePlugin
|
||||
|
||||
@@ -26,14 +28,21 @@ class PluginAdapter:
|
||||
2. Fallback: Capture display_manager.image after calling plugin.display()
|
||||
"""
|
||||
|
||||
def __init__(self, display_manager: Any):
|
||||
def __init__(self, display_manager: Any, config: Optional[Any] = None):
|
||||
"""
|
||||
Initialize the plugin adapter.
|
||||
|
||||
Args:
|
||||
display_manager: DisplayManager instance for fallback capture
|
||||
config: VegasModeConfig controlling trim behaviour. When omitted,
|
||||
trimming runs with the dataclass defaults, so existing callers
|
||||
and tests keep working unchanged.
|
||||
"""
|
||||
self.display_manager = display_manager
|
||||
if config is None:
|
||||
from src.vegas_mode.config import VegasModeConfig
|
||||
config = VegasModeConfig()
|
||||
self.config = config
|
||||
# Handle both property and method access patterns
|
||||
self.display_width = (
|
||||
display_manager.width() if callable(display_manager.width)
|
||||
@@ -49,6 +58,11 @@ class PluginAdapter:
|
||||
self._cache_lock = threading.Lock()
|
||||
self._cache_ttl = 5.0 # Cache for 5 seconds
|
||||
|
||||
# Per-plugin rotation offset, so a plugin whose content exceeds its
|
||||
# width budget shows a different slice on each cycle rather than
|
||||
# always the same opening items.
|
||||
self._item_offsets: dict = {}
|
||||
|
||||
logger.info(
|
||||
"PluginAdapter initialized: display=%dx%d",
|
||||
self.display_width, self.display_height
|
||||
@@ -93,8 +107,7 @@ class PluginAdapter:
|
||||
"[%s] Native content SUCCESS: %d images, %dpx total",
|
||||
plugin_id, len(content), total_width
|
||||
)
|
||||
self._cache_content(plugin_id, content)
|
||||
return content
|
||||
return self._finalize(content, plugin_id, 'native')
|
||||
logger.info("[%s] Native content returned None", plugin_id)
|
||||
|
||||
# Try to get scroll_helper's cached image (for scrolling plugins like stocks/odds)
|
||||
@@ -107,8 +120,7 @@ class PluginAdapter:
|
||||
"[%s] ScrollHelper content SUCCESS: %d images, %dpx total",
|
||||
plugin_id, len(content), total_width
|
||||
)
|
||||
self._cache_content(plugin_id, content)
|
||||
return content
|
||||
return self._finalize(content, plugin_id, 'scroll_helper')
|
||||
if has_scroll_helper:
|
||||
logger.info("[%s] ScrollHelper content returned None", plugin_id)
|
||||
|
||||
@@ -121,8 +133,7 @@ class PluginAdapter:
|
||||
"[%s] Fallback capture SUCCESS: %d images, %dpx total",
|
||||
plugin_id, len(content), total_width
|
||||
)
|
||||
self._cache_content(plugin_id, content)
|
||||
return content
|
||||
return self._finalize(content, plugin_id, 'fallback')
|
||||
|
||||
logger.warning(
|
||||
"[%s] NO CONTENT from any method (native=%s, scroll_helper=%s, fallback=tried)",
|
||||
@@ -130,6 +141,181 @@ class PluginAdapter:
|
||||
)
|
||||
return None
|
||||
|
||||
def _finalize(
|
||||
self, images: List[Image.Image], plugin_id: str, source: str
|
||||
) -> Optional[List[Image.Image]]:
|
||||
"""
|
||||
Trim dead space off a segment, then cache it.
|
||||
|
||||
Every content path funnels through here so trimming is applied
|
||||
uniformly. Previously only the scroll_helper path had its margins
|
||||
stripped, which left plugins that render onto a full-display canvas
|
||||
contributing their entire blank canvas to the ticker.
|
||||
|
||||
Each image is trimmed independently because compose_scroll_content()
|
||||
treats every image as its own item and inserts separator_width between
|
||||
them — so a per-image trim is what makes that separator the real gap.
|
||||
|
||||
Args:
|
||||
images: Raw content from one of the fetch paths
|
||||
plugin_id: Plugin identifier for logging
|
||||
source: Which path produced the content, for logging
|
||||
|
||||
Returns:
|
||||
Trimmed image list, or None if nothing worth showing remains
|
||||
"""
|
||||
if not self.config.auto_trim:
|
||||
self._cache_content(plugin_id, images)
|
||||
return images
|
||||
|
||||
original_width = sum(img.width for img in images)
|
||||
kept: List[Image.Image] = []
|
||||
dropped_blank = 0
|
||||
|
||||
for img in images:
|
||||
result = trim_to_content(
|
||||
img,
|
||||
threshold=self.config.trim_threshold,
|
||||
padding=self.config.content_padding,
|
||||
)
|
||||
if result.is_blank:
|
||||
dropped_blank += 1
|
||||
continue
|
||||
kept.append(result.image)
|
||||
|
||||
if not kept:
|
||||
logger.info(
|
||||
"[%s] All %d image(s) from %s were blank — contributing nothing",
|
||||
plugin_id, len(images), source
|
||||
)
|
||||
return None
|
||||
|
||||
trimmed_width = sum(img.width for img in kept)
|
||||
|
||||
if trimmed_width < self.config.min_plugin_width:
|
||||
logger.info(
|
||||
"[%s] Trimmed content %dpx is below min_plugin_width %dpx — skipping",
|
||||
plugin_id, trimmed_width, self.config.min_plugin_width
|
||||
)
|
||||
return None
|
||||
|
||||
if trimmed_width != original_width or dropped_blank:
|
||||
logger.info(
|
||||
"[%s] Trimmed %s content: %dpx -> %dpx (%.0f%% reclaimed), "
|
||||
"%d image(s) kept, %d blank dropped",
|
||||
plugin_id, source, original_width, trimmed_width,
|
||||
100.0 * (original_width - trimmed_width) / original_width
|
||||
if original_width else 0.0,
|
||||
len(kept), dropped_blank
|
||||
)
|
||||
|
||||
kept = self._apply_width_budget(kept, plugin_id)
|
||||
|
||||
self._cache_content(plugin_id, kept)
|
||||
return kept
|
||||
|
||||
def _width_budget(self) -> int:
|
||||
"""Maximum columns one plugin may occupy in a cycle. 0 means unlimited."""
|
||||
ratio = self.config.max_plugin_width_ratio
|
||||
if ratio <= 0:
|
||||
return 0
|
||||
return int(self.display_width * ratio)
|
||||
|
||||
def _apply_width_budget(
|
||||
self, images: List[Image.Image], plugin_id: str
|
||||
) -> List[Image.Image]:
|
||||
"""
|
||||
Hold one plugin to its share of a cycle.
|
||||
|
||||
A ticker returning 7,000px would otherwise own the panel for over two
|
||||
minutes, which defeats the point of a rotation. Overflow is deferred
|
||||
rather than discarded: the starting offset advances each time this
|
||||
plugin is fetched, so later items appear on subsequent cycles instead
|
||||
of never being seen.
|
||||
|
||||
Args:
|
||||
images: Trimmed images for this plugin
|
||||
plugin_id: Plugin identifier, used to track its rotation offset
|
||||
|
||||
Returns:
|
||||
Images that fit the budget, starting from the plugin's current
|
||||
rotation offset.
|
||||
"""
|
||||
budget = self._width_budget()
|
||||
|
||||
# Count the gaps the compositor will insert between these rows, not
|
||||
# just the pixels of the rows themselves — otherwise a plugin with many
|
||||
# rows quietly occupies far more of the panel than its budget allows.
|
||||
gap = max(0, self.config.intra_plugin_gap)
|
||||
total = sum(img.width for img in images) + gap * (len(images) - 1)
|
||||
|
||||
if not budget or total <= budget:
|
||||
# Fits, so reset rotation — the whole segment is being shown.
|
||||
self._item_offsets.pop(plugin_id, None)
|
||||
return images
|
||||
|
||||
if len(images) == 1:
|
||||
return [self._crop_to_budget(images[0], budget, plugin_id)]
|
||||
|
||||
start = self._item_offsets.get(plugin_id, 0) % len(images)
|
||||
selected: List[Image.Image] = []
|
||||
used = 0
|
||||
consumed = 0
|
||||
|
||||
# Walk forward from the rotation offset, taking whole items only, so a
|
||||
# cut never lands in the middle of one.
|
||||
for step in range(len(images)):
|
||||
img = images[(start + step) % len(images)]
|
||||
cost = img.width + (gap if selected else 0)
|
||||
if selected and used + cost > budget:
|
||||
break
|
||||
selected.append(img)
|
||||
used += cost
|
||||
consumed += 1
|
||||
|
||||
self._item_offsets[plugin_id] = (start + consumed) % len(images)
|
||||
|
||||
logger.info(
|
||||
"[%s] Width budget %dpx: showing %d of %d row(s) (%dpx incl. gaps) "
|
||||
"from offset %d; remainder deferred to a later cycle",
|
||||
plugin_id, budget, len(selected), len(images), used, start
|
||||
)
|
||||
return selected
|
||||
|
||||
def _crop_to_budget(
|
||||
self, img: Image.Image, budget: int, plugin_id: str
|
||||
) -> Image.Image:
|
||||
"""
|
||||
Narrow a single oversized image to the budget, advancing a window
|
||||
through it across cycles.
|
||||
|
||||
The cut is snapped to the nearest blank column so it does not slice
|
||||
through a glyph or logo and leave half a character at the panel edge.
|
||||
"""
|
||||
offset = self._item_offsets.get(plugin_id, 0)
|
||||
if offset >= img.width:
|
||||
offset = 0
|
||||
|
||||
# Snap both edges to blank columns. The search radius is generous
|
||||
# enough to clear a wide glyph but small enough not to distort the
|
||||
# requested budget much.
|
||||
snap = max(8, self.display_width // 16)
|
||||
start = find_blank_cut(img, offset, snap, self.config.trim_threshold)
|
||||
end = find_blank_cut(
|
||||
img, min(start + budget, img.width), snap, self.config.trim_threshold)
|
||||
if end <= start:
|
||||
end = min(start + budget, img.width)
|
||||
|
||||
# Next cycle resumes where this one stopped; wrap when the strip ends.
|
||||
self._item_offsets[plugin_id] = 0 if end >= img.width else end
|
||||
|
||||
logger.info(
|
||||
"[%s] Width budget %dpx: cropped single %dpx image to [%d:%d] "
|
||||
"(%dpx), window advances next cycle",
|
||||
plugin_id, budget, img.width, start, end, end - start
|
||||
)
|
||||
return img.crop((start, 0, end, img.height))
|
||||
|
||||
def _get_native_content(
|
||||
self, plugin: 'BasePlugin', plugin_id: str
|
||||
) -> Optional[List[Image.Image]]:
|
||||
|
||||
@@ -66,10 +66,6 @@ class RenderPipeline:
|
||||
else display_manager.height
|
||||
)
|
||||
|
||||
# Reusable blank frame for cycle-end pushes (allocated lazily,
|
||||
# re-blacked before each reuse)
|
||||
self._blank_frame = None
|
||||
|
||||
# ScrollHelper for optimized scrolling
|
||||
self.scroll_helper = ScrollHelper(
|
||||
self.display_width,
|
||||
@@ -141,23 +137,37 @@ class RenderPipeline:
|
||||
True if composition successful
|
||||
"""
|
||||
try:
|
||||
# Get all buffered content
|
||||
images = self.stream_manager.get_all_content_for_composition()
|
||||
# Content grouped by plugin, so a separator can be placed at the
|
||||
# plugin boundaries only.
|
||||
grouped = self.stream_manager.get_grouped_content_for_composition()
|
||||
|
||||
if not images:
|
||||
if not grouped:
|
||||
logger.warning("No content available for composition")
|
||||
return False
|
||||
|
||||
# Add separator gaps between images
|
||||
content_with_gaps = []
|
||||
for i, img in enumerate(images):
|
||||
content_with_gaps.append(img)
|
||||
# Collapse each plugin's rows into a single block, joined by
|
||||
# intra_plugin_gap. ScrollHelper applies one uniform gap between the
|
||||
# items it is given, so handing it one item per plugin is what makes
|
||||
# separator_width mean "between plugins" instead of "between every
|
||||
# row". Without this, a per-row ticker such as the F1 scoreboard got
|
||||
# the full separator between each of its ~116 rows.
|
||||
blocks = []
|
||||
total_rows = 0
|
||||
for plugin_id, images in grouped:
|
||||
total_rows += len(images)
|
||||
blocks.append(self._join_plugin_rows(images))
|
||||
|
||||
# Create scrolling image via ScrollHelper
|
||||
# Create scrolling image via ScrollHelper.
|
||||
#
|
||||
# lead_gap is explicit because ScrollHelper otherwise prepends a
|
||||
# full display width of black — appropriate for a standalone ticker
|
||||
# scrolling in from off-screen, but in Vegas mode it is charged
|
||||
# once per cycle and reads as the panel switching off.
|
||||
self.scroll_helper.create_scrolling_image(
|
||||
content_items=content_with_gaps,
|
||||
content_items=blocks,
|
||||
item_gap=self.config.separator_width,
|
||||
element_gap=0
|
||||
element_gap=0,
|
||||
lead_gap=self.config.lead_in_width
|
||||
)
|
||||
|
||||
# Verify scroll image was created successfully
|
||||
@@ -177,11 +187,14 @@ class RenderPipeline:
|
||||
self._cycle_complete = False
|
||||
|
||||
logger.info(
|
||||
"Composed scroll image: %dx%d, %d plugins, %d items",
|
||||
"Composed scroll image: %dx%d, %d plugin block(s), %d rows, "
|
||||
"separator=%dpx between plugins / %dpx within",
|
||||
self.scroll_helper.cached_image.width if self.scroll_helper.cached_image else 0,
|
||||
self.display_height,
|
||||
len(self._segments_in_scroll),
|
||||
len(images)
|
||||
len(blocks),
|
||||
total_rows,
|
||||
self.config.separator_width,
|
||||
self.config.intra_plugin_gap,
|
||||
)
|
||||
|
||||
return True
|
||||
@@ -191,6 +204,32 @@ class RenderPipeline:
|
||||
logger.exception("Error composing scroll content")
|
||||
return False
|
||||
|
||||
def _join_plugin_rows(self, images: List[Image.Image]) -> Image.Image:
|
||||
"""
|
||||
Concatenate one plugin's images into a single block.
|
||||
|
||||
Args:
|
||||
images: That plugin's content, in order
|
||||
|
||||
Returns:
|
||||
A single image with the rows laid out left to right, separated by
|
||||
``intra_plugin_gap``. Returned unchanged when there is only one row,
|
||||
which is the common case and avoids a pointless copy.
|
||||
"""
|
||||
if len(images) == 1:
|
||||
return images[0]
|
||||
|
||||
gap = max(0, self.config.intra_plugin_gap)
|
||||
width = sum(img.width for img in images) + gap * (len(images) - 1)
|
||||
height = max(img.height for img in images)
|
||||
|
||||
block = Image.new('RGB', (width, height), (0, 0, 0))
|
||||
x = 0
|
||||
for img in images:
|
||||
block.paste(img, (x, 0))
|
||||
x += img.width + gap
|
||||
return block
|
||||
|
||||
def render_frame(self) -> bool:
|
||||
"""
|
||||
Render a single frame to the display.
|
||||
@@ -236,24 +275,17 @@ class RenderPipeline:
|
||||
"Scroll cycle complete after %.1fs",
|
||||
time.time() - self._cycle_start_time
|
||||
)
|
||||
# Push blank immediately so the hardware never shows any
|
||||
# post-wrap content while the coordinator recomposes the
|
||||
# next cycle (~100 ms). The blank is allocated once and
|
||||
# reused across cycle wraps (fresh paste each time in case
|
||||
# a consumer drew on the previous one).
|
||||
try:
|
||||
if self._blank_frame is None or self._blank_frame.size != (
|
||||
self.display_width, self.display_height):
|
||||
self._blank_frame = Image.new(
|
||||
'RGB', (self.display_width, self.display_height))
|
||||
else:
|
||||
self._blank_frame.paste(
|
||||
(0, 0, 0),
|
||||
(0, 0, self.display_width, self.display_height))
|
||||
self.display_manager.image = self._blank_frame
|
||||
self.display_manager.update_display()
|
||||
except Exception:
|
||||
logger.exception("Failed to write blank frame to display at cycle end")
|
||||
# Deliberately leave the last rendered frame on the panel.
|
||||
#
|
||||
# This used to push a blank frame so no post-wrap content
|
||||
# could be seen while the next cycle was composed. But
|
||||
# recomposing is synchronous and fetches plugin content:
|
||||
# measured 84ms at best and 4.8s at worst on a 512px panel,
|
||||
# and every millisecond of it was black. Holding the last
|
||||
# frame instead turns that into a brief freeze, which reads
|
||||
# as far less broken than the display switching off. The
|
||||
# frame is already past the end of the content, so there is
|
||||
# no second-pass content to leak.
|
||||
return True # Cycle done; coordinator starts new cycle next frame
|
||||
|
||||
# Get visible portion
|
||||
@@ -415,11 +447,12 @@ class RenderPipeline:
|
||||
result = self.compose_scroll_content()
|
||||
|
||||
if result and self.sync_manager:
|
||||
# When sync is active, start the leader at display_width instead of 0.
|
||||
# This skips the initial black gap so the leader immediately shows content.
|
||||
# The follower starts at position 0 (the gap) which looks like a clean
|
||||
# blank transition rather than near-end content wrapping around.
|
||||
self.scroll_helper.scroll_position = float(self.display_width)
|
||||
# When sync is active, start the leader past the lead-in gap so it
|
||||
# immediately shows content, leaving the follower on the blank gap
|
||||
# for a clean transition rather than near-end content wrapping
|
||||
# around. This tracks lead_in_width rather than assuming a full
|
||||
# display width of gap, which is no longer the default.
|
||||
self.scroll_helper.scroll_position = float(self.config.lead_in_width)
|
||||
|
||||
if result and self.sync_manager:
|
||||
# Signal follower that a new cycle started (triggers its own rebuild)
|
||||
|
||||
@@ -14,7 +14,7 @@ Supports three display modes:
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from typing import Optional, List, Dict, Any, Deque, TYPE_CHECKING
|
||||
from typing import Optional, List, Dict, Any, Deque, Tuple, TYPE_CHECKING
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from PIL import Image
|
||||
@@ -116,8 +116,11 @@ class StreamManager:
|
||||
logger.warning("No plugins available for Vegas scroll")
|
||||
return False
|
||||
|
||||
# Prefetch initial content
|
||||
self._prefetch_content(count=min(self.config.buffer_ahead + 1, len(self._ordered_plugins)))
|
||||
# Fill the buffer to a whole cycle's worth of plugins. This used to be
|
||||
# buffer_ahead + 1, which conflated prefetch depth with cycle size and
|
||||
# meant a 20-plugin install only showed 3 plugins before recomposing.
|
||||
self._prefetch_content(
|
||||
count=min(self.config.plugins_per_cycle, len(self._ordered_plugins)))
|
||||
|
||||
logger.info(
|
||||
"StreamManager initialized with %d plugins, %d segments buffered",
|
||||
@@ -385,7 +388,7 @@ class StreamManager:
|
||||
return
|
||||
|
||||
for _ in range(count):
|
||||
if len(self._active_buffer) >= self.config.buffer_ahead + 1:
|
||||
if len(self._active_buffer) >= self.config.plugins_per_cycle:
|
||||
break
|
||||
|
||||
# Ensure index is valid (guard against empty list)
|
||||
@@ -521,28 +524,61 @@ class StreamManager:
|
||||
logger.debug("Refreshed content for %s in staging buffer", plugin_id)
|
||||
|
||||
def _ensure_buffer_filled(self) -> None:
|
||||
"""Ensure buffer has enough content prefetched."""
|
||||
if len(self._active_buffer) < self.config.buffer_ahead:
|
||||
needed = self.config.buffer_ahead - len(self._active_buffer)
|
||||
self._prefetch_content(count=needed)
|
||||
"""
|
||||
Top the buffer back up after segments have been served.
|
||||
|
||||
buffer_ahead is the low-water mark only; plugins_per_cycle is the
|
||||
ceiling and is enforced inside _prefetch_content.
|
||||
"""
|
||||
low_water = min(self.config.buffer_ahead, self.config.plugins_per_cycle)
|
||||
if len(self._active_buffer) < low_water:
|
||||
self._prefetch_content(count=low_water - len(self._active_buffer))
|
||||
|
||||
def get_all_content_for_composition(self) -> List[Image.Image]:
|
||||
"""
|
||||
Get all buffered content as a flat list of images.
|
||||
|
||||
Used when composing the full scroll image.
|
||||
Skips STATIC segments as they don't have images to compose.
|
||||
|
||||
Prefer get_grouped_content_for_composition(): flattening loses the
|
||||
plugin boundaries, which is what tells the compositor where a
|
||||
separator belongs and where it does not.
|
||||
|
||||
Returns:
|
||||
List of all images in buffer order
|
||||
"""
|
||||
all_images = []
|
||||
for _plugin_id, images in self.get_grouped_content_for_composition():
|
||||
all_images.extend(images)
|
||||
return all_images
|
||||
|
||||
def get_grouped_content_for_composition(self) -> List[Tuple[str, List[Image.Image]]]:
|
||||
"""
|
||||
Get buffered content grouped by the plugin that produced it.
|
||||
|
||||
The grouping matters: separator_width is meant to mark the handoff from
|
||||
one plugin to the next, not to sit between every row a single plugin
|
||||
contributes. A per-row ticker like the F1 scoreboard returns over a
|
||||
hundred images that it renders 4px apart internally, so flattening them
|
||||
into one list and applying a uniform gap forced 32px between each of
|
||||
its rows — both inconsistent with how the plugin looks standalone, and
|
||||
a large hidden addition to the width it occupies.
|
||||
|
||||
Skips STATIC segments, which trigger a pause rather than contributing
|
||||
scroll content, and segments left with no images.
|
||||
|
||||
Returns:
|
||||
List of (plugin_id, images) in buffer order
|
||||
"""
|
||||
grouped: List[Tuple[str, List[Image.Image]]] = []
|
||||
with self._buffer_lock:
|
||||
for segment in self._active_buffer:
|
||||
# Skip STATIC segments - they trigger pauses, not scroll content
|
||||
if segment.display_mode != VegasDisplayMode.STATIC:
|
||||
all_images.extend(segment.images)
|
||||
return all_images
|
||||
if segment.display_mode == VegasDisplayMode.STATIC:
|
||||
continue
|
||||
if not segment.images:
|
||||
continue
|
||||
grouped.append((segment.plugin_id, list(segment.images)))
|
||||
return grouped
|
||||
|
||||
def advance_cycle(self) -> None:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
"""Tests for the skin system: discovery, version gating, fallback
|
||||
semantics, module isolation, and the view-model contract."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageFont
|
||||
|
||||
# src.base_classes.sports transitively imports the hardware matrix driver;
|
||||
# stub it so the fallback-semantics tests can import SportsCore off-device.
|
||||
sys.modules.setdefault("rgbmatrix", MagicMock())
|
||||
|
||||
from src.skin_system import skin_runtime
|
||||
from src.skin_system.skin_base import (
|
||||
SKIN_API_VERSION,
|
||||
ScoreboardSkin,
|
||||
SkinContext,
|
||||
)
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURES_DIR = PROJECT_ROOT / "src" / "skin_system" / "fixtures"
|
||||
|
||||
# The v1.0 guaranteed view-model keys (docs/CREATING_SKINS.md). Renaming
|
||||
# or removing any of these is a breaking change to every published skin:
|
||||
# it requires a VIEW_MODEL_VERSION major bump and a compat shim.
|
||||
GUARANTEED_KEYS = [
|
||||
"id", "game_time", "game_date", "start_time_utc", "status_text",
|
||||
"is_live", "is_final", "is_upcoming", "is_halftime",
|
||||
"home_abbr", "home_id", "home_score", "home_logo_path", "home_record",
|
||||
"away_abbr", "away_id", "away_score", "away_logo_path", "away_record",
|
||||
]
|
||||
|
||||
|
||||
def write_skin(skins_dir: Path, skin_id: str, *, api_version: str = SKIN_API_VERSION,
|
||||
body: str = None, extra_files: dict = None,
|
||||
class_name: str = "TestSkin") -> Path:
|
||||
skin_dir = skins_dir / skin_id
|
||||
skin_dir.mkdir(parents=True)
|
||||
manifest = {
|
||||
"id": skin_id, "name": skin_id, "version": "1.0.0",
|
||||
"skin_api_version": api_version, "class_name": class_name,
|
||||
"targets": {"sports": ["baseball"]},
|
||||
}
|
||||
(skin_dir / "skin.json").write_text(json.dumps(manifest))
|
||||
if body is None:
|
||||
body = (
|
||||
"from src.skin_system.skin_base import ScoreboardSkin\n"
|
||||
f"class {class_name}(ScoreboardSkin):\n"
|
||||
" def render_live(self, ctx, game):\n"
|
||||
" ctx.draw.rectangle([0, 0, 4, 4], fill=(255, 0, 0))\n"
|
||||
" return True\n"
|
||||
)
|
||||
(skin_dir / "skin.py").write_text(body)
|
||||
for name, content in (extra_files or {}).items():
|
||||
(skin_dir / name).write_text(content)
|
||||
return skin_dir
|
||||
|
||||
|
||||
class TestDiscovery:
|
||||
def test_discovers_valid_skin(self, tmp_path):
|
||||
write_skin(tmp_path, "my-skin")
|
||||
skins = skin_runtime.discover_skins(tmp_path, force_refresh=True)
|
||||
assert "my-skin" in skins
|
||||
assert skins["my-skin"]["_skin_dir"].endswith("my-skin")
|
||||
|
||||
def test_skips_manifest_missing_required_fields(self, tmp_path):
|
||||
skin_dir = tmp_path / "broken"
|
||||
skin_dir.mkdir()
|
||||
(skin_dir / "skin.json").write_text(json.dumps({"id": "broken"}))
|
||||
assert skin_runtime.discover_skins(tmp_path, force_refresh=True) == {}
|
||||
|
||||
def test_skips_unreadable_manifest_and_non_skin_dirs(self, tmp_path):
|
||||
(tmp_path / "not-a-skin").mkdir()
|
||||
bad = tmp_path / "bad-json"
|
||||
bad.mkdir()
|
||||
(bad / "skin.json").write_text("{nope")
|
||||
write_skin(tmp_path, "good-skin")
|
||||
skins = skin_runtime.discover_skins(tmp_path, force_refresh=True)
|
||||
assert list(skins) == ["good-skin"]
|
||||
|
||||
def test_missing_directory_is_empty(self, tmp_path):
|
||||
assert skin_runtime.discover_skins(tmp_path / "nope") == {}
|
||||
|
||||
def test_example_skin_in_repo_is_discoverable(self):
|
||||
skins = skin_runtime.discover_skins(force_refresh=True)
|
||||
assert "example-classic-baseball" in skins
|
||||
|
||||
|
||||
class TestLoadSkin:
|
||||
def test_loads_and_instantiates(self, tmp_path):
|
||||
write_skin(tmp_path, "my-skin")
|
||||
skin = skin_runtime.load_skin("my-skin", sport="baseball",
|
||||
skins_dir=tmp_path)
|
||||
assert isinstance(skin, ScoreboardSkin)
|
||||
|
||||
def test_unknown_skin_returns_none(self, tmp_path):
|
||||
assert skin_runtime.load_skin("ghost", skins_dir=tmp_path) is None
|
||||
|
||||
def test_api_major_mismatch_is_refused(self, tmp_path):
|
||||
write_skin(tmp_path, "old-skin", api_version="99.0.0")
|
||||
assert skin_runtime.load_skin("old-skin", skins_dir=tmp_path) is None
|
||||
|
||||
def test_target_mismatch_still_loads(self, tmp_path):
|
||||
write_skin(tmp_path, "my-skin") # targets baseball
|
||||
skin = skin_runtime.load_skin("my-skin", sport="hockey",
|
||||
skins_dir=tmp_path)
|
||||
assert skin is not None # soft warning, not a hard block
|
||||
|
||||
def test_import_error_returns_none(self, tmp_path):
|
||||
write_skin(tmp_path, "crashy", body="raise RuntimeError('boom')\n")
|
||||
assert skin_runtime.load_skin("crashy", skins_dir=tmp_path) is None
|
||||
|
||||
def test_wrong_class_returns_none(self, tmp_path):
|
||||
write_skin(tmp_path, "classless", body="x = 1\n")
|
||||
assert skin_runtime.load_skin("classless", skins_dir=tmp_path) is None
|
||||
|
||||
def test_options_are_passed_through(self, tmp_path):
|
||||
write_skin(tmp_path, "my-skin")
|
||||
skin = skin_runtime.load_skin("my-skin", skins_dir=tmp_path,
|
||||
options={"accent": [1, 2, 3]})
|
||||
assert skin.options == {"accent": [1, 2, 3]}
|
||||
|
||||
def test_sibling_modules_are_isolated_between_skins(self, tmp_path):
|
||||
helper = "VALUE = {!r}\n"
|
||||
body = (
|
||||
"import helpers\n"
|
||||
"from src.skin_system.skin_base import ScoreboardSkin\n"
|
||||
"class TestSkin(ScoreboardSkin):\n"
|
||||
" def render_live(self, ctx, game):\n"
|
||||
" ctx.logger.info(helpers.VALUE)\n"
|
||||
" self.helper_value = helpers.VALUE\n"
|
||||
" return False\n"
|
||||
)
|
||||
write_skin(tmp_path, "skin-a", body=body,
|
||||
extra_files={"helpers.py": helper.format("A")})
|
||||
write_skin(tmp_path, "skin-b", body=body,
|
||||
extra_files={"helpers.py": helper.format("B")})
|
||||
skin_a = skin_runtime.load_skin("skin-a", skins_dir=tmp_path)
|
||||
skin_b = skin_runtime.load_skin("skin-b", skins_dir=tmp_path)
|
||||
ctx = _make_context()
|
||||
skin_a.render_live(ctx, {})
|
||||
skin_b.render_live(ctx, {})
|
||||
assert skin_a.helper_value == "A"
|
||||
assert skin_b.helper_value == "B"
|
||||
|
||||
def test_same_skin_loads_repeatedly_with_siblings(self, tmp_path):
|
||||
"""The live/recent/upcoming hosts each load the same skin — the
|
||||
2nd and 3rd loads must still resolve sibling modules (regression:
|
||||
cached siblings used to be skipped without rebinding)."""
|
||||
body = (
|
||||
"import reload_helpers\n"
|
||||
"from src.skin_system.skin_base import ScoreboardSkin\n"
|
||||
"class TestSkin(ScoreboardSkin):\n"
|
||||
" def render_live(self, ctx, game):\n"
|
||||
" self.helper_value = reload_helpers.VALUE\n"
|
||||
" return False\n"
|
||||
)
|
||||
write_skin(tmp_path, "reload-skin", body=body,
|
||||
extra_files={"reload_helpers.py": "VALUE = 'R'\n"})
|
||||
ctx = _make_context()
|
||||
for _ in range(3):
|
||||
skin = skin_runtime.load_skin("reload-skin", skins_dir=tmp_path)
|
||||
assert skin is not None
|
||||
skin.render_live(ctx, {})
|
||||
assert skin.helper_value == "R"
|
||||
|
||||
|
||||
def _make_host(fonts=None):
|
||||
host = MagicMock()
|
||||
host.sport = "baseball"
|
||||
host.sport_key = "mlb"
|
||||
host.skin_options = {"accent": True}
|
||||
host.fonts = fonts or {"time": ImageFont.load_default()}
|
||||
host.logger = logging.getLogger("test_skin_system")
|
||||
host.display_manager.width = 128
|
||||
host.display_manager.height = 32
|
||||
return host
|
||||
|
||||
|
||||
def _make_context(width=128, height=32):
|
||||
host = _make_host()
|
||||
return skin_runtime.build_context(host, {}, size=(width, height))
|
||||
|
||||
|
||||
class TestBuildContext:
|
||||
def test_context_shape(self):
|
||||
host = _make_host()
|
||||
game = {"home_abbr": "LAD", "away_abbr": "SF"}
|
||||
ctx = skin_runtime.build_context(host, game)
|
||||
assert (ctx.width, ctx.height) == (128, 32)
|
||||
assert ctx.canvas.size == (128, 32)
|
||||
assert ctx.sport == "baseball"
|
||||
assert ctx.options == {"accent": True}
|
||||
assert ctx.layout.bounds.w == 128
|
||||
|
||||
def test_explicit_size_overrides_display(self):
|
||||
ctx = skin_runtime.build_context(_make_host(), {}, size=(64, 64))
|
||||
assert ctx.canvas.size == (64, 64)
|
||||
|
||||
def test_load_logo_binds_game_and_survives_failure(self):
|
||||
host = _make_host()
|
||||
host._load_and_resize_logo.side_effect = RuntimeError("disk gone")
|
||||
ctx = skin_runtime.build_context(
|
||||
host, {"home_id": "1", "home_abbr": "LAD",
|
||||
"home_logo_path": "x.png", "home_logo_url": None})
|
||||
assert ctx.load_logo("home") is None # exception swallowed
|
||||
assert ctx.load_logo("elsewhere") is None # bad side rejected
|
||||
|
||||
def test_draw_helpers_draw_on_canvas(self):
|
||||
ctx = _make_context()
|
||||
ctx.draw_text("HI", 2, 2, font=ImageFont.load_default())
|
||||
fit = ctx.layout.fit_text("42", ctx.layout.bounds)
|
||||
ctx.draw_fit(fit, ctx.layout.bounds)
|
||||
logo = Image.new("RGBA", (16, 16), (255, 0, 0, 255))
|
||||
ctx.draw_image(logo, ctx.layout.bounds.left_col(20))
|
||||
ctx.draw_image(None, ctx.layout.bounds) # None must no-op
|
||||
assert ctx.canvas.convert("L").getbbox() is not None
|
||||
|
||||
|
||||
class _FallbackProbe:
|
||||
"""Bare-bones SportsCore stand-in that exercises the real _render_game."""
|
||||
|
||||
def __init__(self, skin):
|
||||
from src.base_classes.sports import SportsCore
|
||||
self._cls = SportsCore
|
||||
self.SKIN_MODE = "live"
|
||||
self.logger = logging.getLogger("test_skin_system")
|
||||
self.sport = "baseball"
|
||||
self.sport_key = "mlb"
|
||||
self.skin_options = {}
|
||||
self.fonts = {"time": ImageFont.load_default()}
|
||||
self._skin = skin
|
||||
self._skin_load_attempted = True
|
||||
self._skin_failures = 0
|
||||
self._skin_slow_renders = 0
|
||||
self._skin_config = "test-skin"
|
||||
self.display_manager = MagicMock()
|
||||
self.display_manager.width = 128
|
||||
self.display_manager.height = 32
|
||||
self.display_manager.image = Image.new("RGB", (128, 32))
|
||||
self.builtin_calls = 0
|
||||
|
||||
def _resolve_skin_id(self):
|
||||
return "test-skin"
|
||||
|
||||
def _draw_scorebug_layout(self, game, force_clear=False):
|
||||
self.builtin_calls += 1
|
||||
|
||||
def _render_game(self, game, force_clear=False):
|
||||
from src.base_classes.sports import SportsCore
|
||||
SportsCore._render_game(self, game, force_clear)
|
||||
|
||||
def _get_skin(self):
|
||||
return self._skin
|
||||
|
||||
|
||||
class TestRenderGameFallback:
|
||||
def test_skin_handles_render(self):
|
||||
class GoodSkin(ScoreboardSkin):
|
||||
def render_live(self, ctx, game):
|
||||
ctx.draw.rectangle([0, 0, 10, 10], fill=(0, 255, 0))
|
||||
return True
|
||||
|
||||
probe = _FallbackProbe(GoodSkin({}, {}))
|
||||
probe._render_game({"status_text": "Q1"})
|
||||
assert probe.builtin_calls == 0
|
||||
probe.display_manager.update_display.assert_called_once()
|
||||
assert probe.display_manager.image.convert("L").getbbox() is not None
|
||||
|
||||
def test_skin_declining_falls_back(self):
|
||||
probe = _FallbackProbe(ScoreboardSkin({}, {})) # all renders -> False
|
||||
probe._render_game({"status_text": "Q1"})
|
||||
assert probe.builtin_calls == 1
|
||||
|
||||
def test_no_skin_falls_back(self):
|
||||
probe = _FallbackProbe(None)
|
||||
probe._render_game({"status_text": "Q1"})
|
||||
assert probe.builtin_calls == 1
|
||||
|
||||
def test_three_strikes_disables_skin(self):
|
||||
class BrokenSkin(ScoreboardSkin):
|
||||
calls = 0
|
||||
|
||||
def render_live(self, ctx, game):
|
||||
BrokenSkin.calls += 1
|
||||
raise ValueError("kaboom")
|
||||
|
||||
probe = _FallbackProbe(BrokenSkin({}, {}))
|
||||
for i in range(5):
|
||||
probe._render_game({"status_text": "Q1"})
|
||||
# every render fell back to the built-in layout...
|
||||
assert probe.builtin_calls == 5
|
||||
# ...and the skin stopped being called after the 3rd failure
|
||||
assert BrokenSkin.calls == 3
|
||||
assert probe._skin_failures == 3
|
||||
|
||||
def test_skin_cannot_mutate_callers_game_dict(self):
|
||||
class MutatingSkin(ScoreboardSkin):
|
||||
def render_live(self, ctx, game):
|
||||
game.clear()
|
||||
game["hacked"] = True
|
||||
return True
|
||||
|
||||
probe = _FallbackProbe(MutatingSkin({}, {}))
|
||||
game = {"status_text": "Q1", "home_score": "3"}
|
||||
probe._render_game(game)
|
||||
assert game == {"status_text": "Q1", "home_score": "3"}
|
||||
|
||||
|
||||
class TestSkinModeResolution:
|
||||
def _core(self, skin_config, mode="live"):
|
||||
from src.base_classes.sports import SportsCore
|
||||
probe = _FallbackProbe(None)
|
||||
probe.SKIN_MODE = mode
|
||||
probe._skin_config = skin_config
|
||||
return SportsCore._resolve_skin_id(probe)
|
||||
|
||||
def test_plain_id_applies_to_all_modes(self):
|
||||
assert self._core("retro", "live") == "retro"
|
||||
assert self._core("retro", "recent") == "retro"
|
||||
|
||||
def test_per_mode_mapping(self):
|
||||
cfg = {"live": "retro", "recent": "built-in"}
|
||||
assert self._core(cfg, "live") == "retro"
|
||||
assert self._core(cfg, "recent") is None
|
||||
assert self._core(cfg, "upcoming") is None
|
||||
|
||||
def test_builtin_and_empty_mean_none(self):
|
||||
assert self._core("built-in") is None
|
||||
assert self._core("") is None
|
||||
assert self._core(None) is None
|
||||
|
||||
|
||||
class TestViewModelContract:
|
||||
@pytest.mark.parametrize("sport", ["baseball", "basketball", "football", "hockey"])
|
||||
@pytest.mark.parametrize("mode", ["live", "recent", "upcoming"])
|
||||
def test_fixtures_carry_all_guaranteed_keys(self, sport, mode):
|
||||
with open(FIXTURES_DIR / f"{sport}_{mode}.json") as f:
|
||||
game = json.load(f)
|
||||
missing = [k for k in GUARANTEED_KEYS if k not in game]
|
||||
assert not missing, f"{sport}_{mode} fixture missing {missing}"
|
||||
|
||||
def test_extractor_produces_guaranteed_keys(self):
|
||||
"""The real extractor's output must be a superset of the documented
|
||||
contract — this is the test that catches accidental renames."""
|
||||
import pytz
|
||||
from src.base_classes.sports import SportsCore
|
||||
|
||||
event = {
|
||||
"id": "401570001",
|
||||
"date": "2026-07-16T23:05:00Z",
|
||||
"competitions": [{
|
||||
"status": {"type": {"name": "STATUS_IN_PROGRESS", "state": "in",
|
||||
"shortDetail": "Bot 7th"}},
|
||||
"competitors": [
|
||||
{"homeAway": "home", "id": "19",
|
||||
"team": {"abbreviation": "LAD"}, "score": "5",
|
||||
"records": [{"summary": "58-33"}]},
|
||||
{"homeAway": "away", "id": "26",
|
||||
"team": {"abbreviation": "SF"}, "score": "3",
|
||||
"records": [{"summary": "49-42"}]},
|
||||
],
|
||||
}],
|
||||
}
|
||||
probe = MagicMock()
|
||||
probe.logger = logging.getLogger("test_skin_system")
|
||||
probe.favorite_teams = []
|
||||
probe.config = {}
|
||||
probe.logo_dir = Path("assets/logos")
|
||||
probe._get_timezone.return_value = pytz.utc
|
||||
probe.display_manager.format_date_with_ordinal.return_value = "Jul 16th"
|
||||
|
||||
details, _, _, _, _ = SportsCore._extract_game_details_common(probe, event)
|
||||
assert details is not None
|
||||
missing = [k for k in GUARANTEED_KEYS if k not in details]
|
||||
assert not missing, (
|
||||
f"_extract_game_details_common no longer emits {missing}. "
|
||||
"These keys are part of the frozen skin view-model contract "
|
||||
"(VIEW_MODEL_VERSION) — renaming or removing them breaks every "
|
||||
"published skin. Add a compat shim or bump the major version.")
|
||||
|
||||
|
||||
class TestPluginMatching:
|
||||
def test_matches_by_sport_token_and_sport_key(self, tmp_path):
|
||||
write_skin(tmp_path, "bb-skin") # targets sports=["baseball"]
|
||||
skins = skin_runtime.discover_skins(tmp_path, force_refresh=True)
|
||||
assert "bb-skin" in skin_runtime.skins_for_plugin("baseball-scoreboard", skins)
|
||||
assert "bb-skin" not in skin_runtime.skins_for_plugin("football-scoreboard", skins)
|
||||
|
||||
def test_matches_by_explicit_plugin_list(self, tmp_path):
|
||||
skin_dir = write_skin(tmp_path, "exact-skin")
|
||||
manifest = json.loads((skin_dir / "skin.json").read_text())
|
||||
manifest["targets"] = {"plugins": ["my-custom-plugin"]}
|
||||
(skin_dir / "skin.json").write_text(json.dumps(manifest))
|
||||
skins = skin_runtime.discover_skins(tmp_path, force_refresh=True)
|
||||
assert "exact-skin" in skin_runtime.skins_for_plugin("my-custom-plugin", skins)
|
||||
assert "exact-skin" not in skin_runtime.skins_for_plugin("baseball-scoreboard", skins)
|
||||
|
||||
|
||||
class TestSchemaInjection:
|
||||
def _manager(self):
|
||||
from src.plugin_system.schema_manager import SchemaManager
|
||||
return SchemaManager()
|
||||
|
||||
def test_injects_enum_with_installed_and_configured_skins(self):
|
||||
sm = self._manager()
|
||||
schema = {"type": "object", "properties": {}}
|
||||
out = sm.inject_skin_selector(schema, "baseball-scoreboard",
|
||||
current_value="gone-skin")
|
||||
enum = out["properties"]["skin"]["enum"]
|
||||
assert enum[0] == "built-in"
|
||||
assert "example-classic-baseball" in enum
|
||||
# an uninstalled-but-configured skin must stay selectable so the
|
||||
# saved config never becomes invalid in the UI
|
||||
assert "gone-skin" in enum
|
||||
assert "skin" not in schema["properties"] # source schema untouched
|
||||
|
||||
def test_no_matching_skins_leaves_schema_alone(self):
|
||||
sm = self._manager()
|
||||
schema = {"type": "object", "properties": {}}
|
||||
out = sm.inject_skin_selector(schema, "totally-unrelated-plugin")
|
||||
assert "skin" not in out.get("properties", {})
|
||||
|
||||
def test_validation_accepts_skin_keys_without_enum(self):
|
||||
sm = self._manager()
|
||||
schema = {"type": "object", "properties": {"foo": {"type": "string"}}}
|
||||
ok, errors = sm.validate_config_against_schema(
|
||||
{"skin": "any-id-even-uninstalled", "skin_options": {"x": 1}},
|
||||
schema, "baseball-scoreboard")
|
||||
assert ok, errors
|
||||
ok, errors = sm.validate_config_against_schema(
|
||||
{"skin": {"live": "a", "recent": "built-in"}}, schema, "p")
|
||||
assert ok, errors
|
||||
|
||||
|
||||
class TestExampleSkin:
|
||||
@pytest.mark.parametrize("mode", ["live", "recent", "upcoming"])
|
||||
@pytest.mark.parametrize("size", [(128, 32), (64, 32), (128, 64)])
|
||||
def test_renders_all_modes_and_sizes(self, mode, size):
|
||||
skin = skin_runtime.load_skin("example-classic-baseball", sport="baseball")
|
||||
assert skin is not None
|
||||
host = _make_host()
|
||||
host._load_and_resize_logo.return_value = Image.new("RGBA", (32, 32), (200, 0, 0, 255))
|
||||
with open(FIXTURES_DIR / f"baseball_{mode}.json") as f:
|
||||
game = json.load(f)
|
||||
ctx = skin_runtime.build_context(host, game, size=size)
|
||||
assert getattr(skin, f"render_{mode}")(ctx, game) is True
|
||||
assert ctx.canvas.convert("L").getbbox() is not None
|
||||
@@ -0,0 +1,603 @@
|
||||
"""
|
||||
Tests for the Vegas mode density work: dead-space trimming in PluginAdapter
|
||||
and the configurable lead-in gap in ScrollHelper.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from src.common.scroll_helper import ScrollHelper
|
||||
from src.vegas_mode.config import VegasModeConfig
|
||||
from src.vegas_mode.geometry import column_has_ink
|
||||
from src.vegas_mode.plugin_adapter import PluginAdapter
|
||||
|
||||
DISPLAY_W = 512
|
||||
DISPLAY_H = 64
|
||||
|
||||
|
||||
class FakeDisplayManager:
|
||||
"""Minimal stand-in; the native content path never touches the canvas."""
|
||||
|
||||
width = DISPLAY_W
|
||||
height = DISPLAY_H
|
||||
|
||||
def __init__(self):
|
||||
self.image = Image.new('RGB', (DISPLAY_W, DISPLAY_H))
|
||||
|
||||
|
||||
class NativePlugin:
|
||||
"""Plugin that returns pre-rendered Vegas content."""
|
||||
|
||||
def __init__(self, images):
|
||||
self._images = images
|
||||
|
||||
def get_vegas_content(self):
|
||||
return self._images
|
||||
|
||||
|
||||
def canvas(content_spans, width=DISPLAY_W, height=DISPLAY_H):
|
||||
"""Full-display canvas with white content in the given [x0, x1) spans."""
|
||||
img = Image.new('RGB', (width, height), (0, 0, 0))
|
||||
for x0, x1 in content_spans:
|
||||
img.paste(Image.new('RGB', (x1 - x0, height), (255, 255, 255)), (x0, 0))
|
||||
return img
|
||||
|
||||
|
||||
def adapter_with(**overrides):
|
||||
cfg = VegasModeConfig(**overrides)
|
||||
return PluginAdapter(FakeDisplayManager(), cfg)
|
||||
|
||||
|
||||
class TestAdapterTrimming:
|
||||
def test_of_the_day_case_is_reclaimed(self):
|
||||
# Measured on devpi: "No Data" occupying 35px of a 512px canvas bought
|
||||
# 9.5s of black at 50px/s.
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([canvas([(4, 39)])])
|
||||
images = adapter.get_content(plugin, 'of-the-day')
|
||||
assert len(images) == 1
|
||||
assert images[0].width == 35
|
||||
|
||||
def test_youtube_stats_case_is_reclaimed(self):
|
||||
# Centred 142px of content on a 512px canvas: 185px black each side.
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([canvas([(185, 327)])])
|
||||
images = adapter.get_content(plugin, 'youtube-stats')
|
||||
assert images[0].width == 142
|
||||
|
||||
def test_padding_is_applied_within_available_margin(self):
|
||||
adapter = adapter_with(content_padding=8)
|
||||
plugin = NativePlugin([canvas([(185, 327)])])
|
||||
images = adapter.get_content(plugin, 'youtube-stats')
|
||||
assert images[0].width == 142 + 16
|
||||
|
||||
def test_interior_layout_gap_survives(self):
|
||||
# A logo far left and a score far right is deliberate layout; closing
|
||||
# the gap would corrupt the design rather than reclaim dead space.
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([canvas([(10, 40), (400, 460)])])
|
||||
images = adapter.get_content(plugin, 'scoreboard')
|
||||
assert images[0].width == 450 # 10..459
|
||||
assert int(column_has_ink(images[0]).sum()) == 90
|
||||
|
||||
def test_wide_legitimate_content_is_left_alone(self):
|
||||
# geochron uses 444 of 512 columns; only the real tail should go.
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([canvas([(0, 444)])])
|
||||
images = adapter.get_content(plugin, 'geochron')
|
||||
assert images[0].width == 444
|
||||
|
||||
def test_non_black_background_is_untouched(self):
|
||||
adapter = adapter_with(content_padding=0)
|
||||
bg = Image.new('RGB', (DISPLAY_W, DISPLAY_H), (0, 0, 40))
|
||||
plugin = NativePlugin([bg])
|
||||
images = adapter.get_content(plugin, 'weather')
|
||||
assert images[0].width == DISPLAY_W
|
||||
|
||||
def test_each_image_of_a_multi_item_segment_is_trimmed(self):
|
||||
# compose_scroll_content treats every image as its own item, so a
|
||||
# per-image trim is what makes separator_width the real gap.
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([
|
||||
canvas([(168, 344)]),
|
||||
canvas([(200, 300)]),
|
||||
canvas([(0, 512)]),
|
||||
])
|
||||
images = adapter.get_content(plugin, 'ledmatrix-flights')
|
||||
assert [img.width for img in images] == [176, 100, 512]
|
||||
|
||||
def test_fully_blank_segment_contributes_nothing(self):
|
||||
adapter = adapter_with()
|
||||
plugin = NativePlugin([Image.new('RGB', (DISPLAY_W, DISPLAY_H))])
|
||||
assert adapter.get_content(plugin, 'empty') is None
|
||||
|
||||
def test_blank_images_are_dropped_but_others_kept(self):
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([
|
||||
canvas([(100, 150)]),
|
||||
Image.new('RGB', (DISPLAY_W, DISPLAY_H)),
|
||||
canvas([(200, 260)]),
|
||||
])
|
||||
images = adapter.get_content(plugin, 'mixed')
|
||||
assert [img.width for img in images] == [50, 60]
|
||||
|
||||
def test_min_plugin_width_rejects_noise(self):
|
||||
adapter = adapter_with(content_padding=0, min_plugin_width=32)
|
||||
plugin = NativePlugin([canvas([(10, 14)])])
|
||||
assert adapter.get_content(plugin, 'sliver') is None
|
||||
|
||||
def test_min_plugin_width_of_zero_keeps_everything(self):
|
||||
adapter = adapter_with(content_padding=0, min_plugin_width=0)
|
||||
plugin = NativePlugin([canvas([(10, 14)])])
|
||||
images = adapter.get_content(plugin, 'sliver')
|
||||
assert images[0].width == 4
|
||||
|
||||
def test_auto_trim_off_preserves_original_behaviour(self):
|
||||
adapter = adapter_with(auto_trim=False)
|
||||
plugin = NativePlugin([canvas([(4, 39)])])
|
||||
images = adapter.get_content(plugin, 'of-the-day')
|
||||
assert images[0].width == DISPLAY_W
|
||||
|
||||
def test_trim_threshold_ignores_near_black_noise(self):
|
||||
# A very dark band should not be mistaken for content.
|
||||
img = Image.new('RGB', (DISPLAY_W, DISPLAY_H), (0, 0, 0))
|
||||
img.paste(Image.new('RGB', (100, DISPLAY_H), (3, 3, 3)), (0, 0))
|
||||
img.paste(Image.new('RGB', (50, DISPLAY_H), (255, 255, 255)), (200, 0))
|
||||
adapter = adapter_with(content_padding=0, trim_threshold=10)
|
||||
images = adapter.get_content(NativePlugin([img]), 'noisy')
|
||||
assert images[0].width == 50
|
||||
|
||||
def test_height_is_preserved_through_trim(self):
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([canvas([(100, 200)])])
|
||||
images = adapter.get_content(plugin, 'x')
|
||||
assert images[0].height == DISPLAY_H
|
||||
|
||||
def test_trimmed_result_is_cached(self):
|
||||
adapter = adapter_with(content_padding=0)
|
||||
plugin = NativePlugin([canvas([(100, 200)])])
|
||||
first = adapter.get_content(plugin, 'cached')
|
||||
# Swap the plugin's content; the cache should still serve the old size.
|
||||
plugin._images = [canvas([(0, 512)])]
|
||||
second = adapter.get_content(plugin, 'cached')
|
||||
assert first[0].width == second[0].width == 100
|
||||
|
||||
def test_default_adapter_construction_still_works(self):
|
||||
# Existing callers pass only the display manager.
|
||||
adapter = PluginAdapter(FakeDisplayManager())
|
||||
assert adapter.config.auto_trim is True
|
||||
|
||||
|
||||
class TestWidthBudget:
|
||||
def test_segment_within_budget_is_untouched(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=3.0)
|
||||
plugin = NativePlugin([canvas([(0, 400)])])
|
||||
assert adapter.get_content(plugin, 'small')[0].width == 400
|
||||
|
||||
def test_oversized_multi_item_segment_is_capped(self):
|
||||
# 10 items of 400px = 4000px against a 1536px budget (3 x 512).
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=3.0)
|
||||
items = [canvas([(0, 400)], width=400) for _ in range(10)]
|
||||
images = adapter.get_content(NativePlugin(items), 'stock-news')
|
||||
assert sum(i.width for i in images) <= 3 * DISPLAY_W
|
||||
assert len(images) == 3 # 1200px; a 4th would exceed 1536
|
||||
|
||||
def test_deferred_items_appear_on_the_next_cycle(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
# Distinguish items by width so the rotation is observable.
|
||||
items = [canvas([(0, w)], width=w) for w in (200, 210, 220, 230, 240)]
|
||||
plugin = NativePlugin(items)
|
||||
|
||||
first = adapter.get_content(plugin, 'ticker')
|
||||
adapter.invalidate_cache('ticker')
|
||||
second = adapter.get_content(plugin, 'ticker')
|
||||
assert [i.width for i in first] != [i.width for i in second]
|
||||
|
||||
def test_rotation_eventually_covers_every_item(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
widths = (200, 210, 220, 230, 240)
|
||||
items = [canvas([(0, w)], width=w) for w in widths]
|
||||
plugin = NativePlugin(items)
|
||||
|
||||
seen = set()
|
||||
for _ in range(10):
|
||||
adapter.invalidate_cache('ticker')
|
||||
for img in adapter.get_content(plugin, 'ticker'):
|
||||
seen.add(img.width)
|
||||
assert seen == set(widths)
|
||||
|
||||
def test_single_oversized_image_is_cropped_to_budget(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
# A 6898px leaderboard strip, as measured on devpi. Solid ink means
|
||||
# there is no blank column to snap to, so the cut lands on the budget.
|
||||
plugin = NativePlugin([canvas([(0, 6898)], width=6898)])
|
||||
images = adapter.get_content(plugin, 'ledmatrix-leaderboard')
|
||||
assert len(images) == 1
|
||||
assert images[0].width == DISPLAY_W
|
||||
|
||||
def test_single_image_crop_snaps_to_a_blank_column(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
# Content blocks with gaps; the cut should land in a gap, not mid-block.
|
||||
spans = [(x, x + 90) for x in range(0, 2000, 100)]
|
||||
plugin = NativePlugin([canvas(spans, width=2000)])
|
||||
images = adapter.get_content(plugin, 'gapped')
|
||||
assert images[0].width != DISPLAY_W
|
||||
assert abs(images[0].width - DISPLAY_W) <= DISPLAY_W // 16 + 1
|
||||
|
||||
def test_single_image_window_advances_across_cycles(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
plugin = NativePlugin([canvas([(0, 3000)], width=3000)])
|
||||
adapter.get_content(plugin, 'strip')
|
||||
assert adapter._item_offsets['strip'] == DISPLAY_W
|
||||
|
||||
def test_budget_of_zero_disables_the_cap(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=0)
|
||||
plugin = NativePlugin([canvas([(0, 6898)], width=6898)])
|
||||
assert adapter.get_content(plugin, 'huge')[0].width == 6898
|
||||
|
||||
def test_rotation_resets_when_content_shrinks_to_fit(self):
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
big = [canvas([(0, 300)], width=300) for _ in range(5)]
|
||||
adapter.get_content(NativePlugin(big), 'shrink')
|
||||
assert 'shrink' in adapter._item_offsets
|
||||
|
||||
adapter.invalidate_cache('shrink')
|
||||
adapter.get_content(NativePlugin([canvas([(0, 100)], width=100)]), 'shrink')
|
||||
assert 'shrink' not in adapter._item_offsets
|
||||
|
||||
def test_one_item_wider_than_budget_is_still_shown(self):
|
||||
# Never return nothing just because the first whole item overflows.
|
||||
adapter = adapter_with(content_padding=0, max_plugin_width_ratio=1.0)
|
||||
items = [canvas([(0, 900)], width=900), canvas([(0, 100)], width=100)]
|
||||
images = adapter.get_content(NativePlugin(items), 'wide-first')
|
||||
assert len(images) >= 1
|
||||
assert images[0].width == 900
|
||||
|
||||
|
||||
class TestPluginBoundaryGaps:
|
||||
"""separator_width belongs between plugins; intra_plugin_gap within one."""
|
||||
|
||||
def _pipeline(self, grouped, **cfg):
|
||||
from src.vegas_mode.render_pipeline import RenderPipeline
|
||||
|
||||
class FakeStream:
|
||||
def get_grouped_content_for_composition(self):
|
||||
return grouped
|
||||
|
||||
def get_active_plugin_ids(self):
|
||||
return [pid for pid, _ in grouped]
|
||||
|
||||
class DM:
|
||||
width = DISPLAY_W
|
||||
height = DISPLAY_H
|
||||
|
||||
def set_scrolling_state(self, *a):
|
||||
pass
|
||||
|
||||
return RenderPipeline(VegasModeConfig(**cfg), DM(), FakeStream())
|
||||
|
||||
def test_separator_only_at_plugin_boundaries(self):
|
||||
# Two plugins, two rows each. Expect: row row [sep] row row, with the
|
||||
# small intra gap inside each pair.
|
||||
rows = [Image.new('RGB', (100, DISPLAY_H), (255, 255, 255)) for _ in range(4)]
|
||||
pipeline = self._pipeline(
|
||||
[('a', rows[:2]), ('b', rows[2:])],
|
||||
separator_width=32, intra_plugin_gap=8, lead_in_width=0,
|
||||
)
|
||||
assert pipeline.compose_scroll_content()
|
||||
|
||||
ink = column_has_ink(pipeline.scroll_helper.cached_image)
|
||||
assert ink[:100].all()
|
||||
assert not ink[100:108].any() # intra gap inside plugin a
|
||||
assert ink[108:208].all()
|
||||
assert not ink[208:240].any() # separator between a and b
|
||||
assert ink[240:340].all()
|
||||
assert not ink[340:348].any() # intra gap inside plugin b
|
||||
assert ink[348:448].all()
|
||||
|
||||
def test_total_width_uses_both_gap_sizes(self):
|
||||
rows = [Image.new('RGB', (100, DISPLAY_H), (255, 255, 255)) for _ in range(4)]
|
||||
pipeline = self._pipeline(
|
||||
[('a', rows[:2]), ('b', rows[2:])],
|
||||
separator_width=32, intra_plugin_gap=8, lead_in_width=0,
|
||||
)
|
||||
pipeline.compose_scroll_content()
|
||||
# 4 rows + 2 intra gaps + 1 separator
|
||||
assert pipeline.scroll_helper.cached_image.width == 400 + 16 + 32
|
||||
|
||||
def test_f1_shaped_case_reclaims_the_chasms(self):
|
||||
# 12 rows from one plugin: previously 11 separators at 32px = 352px of
|
||||
# gap; now 11 intra gaps at 8px = 88px.
|
||||
rows = [Image.new('RGB', (128, DISPLAY_H), (255, 255, 255)) for _ in range(12)]
|
||||
pipeline = self._pipeline(
|
||||
[('f1-scoreboard', rows)],
|
||||
separator_width=32, intra_plugin_gap=8, lead_in_width=0,
|
||||
)
|
||||
pipeline.compose_scroll_content()
|
||||
assert pipeline.scroll_helper.cached_image.width == 12 * 128 + 11 * 8
|
||||
|
||||
def test_single_row_plugin_image_is_not_copied(self):
|
||||
row = Image.new('RGB', (100, DISPLAY_H), (255, 255, 255))
|
||||
pipeline = self._pipeline([('solo', [row])], lead_in_width=0)
|
||||
assert pipeline._join_plugin_rows([row]) is row
|
||||
|
||||
def test_zero_intra_gap_butts_rows_together(self):
|
||||
rows = [Image.new('RGB', (50, DISPLAY_H), (255, 255, 255)) for _ in range(3)]
|
||||
pipeline = self._pipeline(
|
||||
[('a', rows)], separator_width=32, intra_plugin_gap=0, lead_in_width=0)
|
||||
pipeline.compose_scroll_content()
|
||||
assert pipeline.scroll_helper.cached_image.width == 150
|
||||
assert column_has_ink(pipeline.scroll_helper.cached_image).all()
|
||||
|
||||
def test_empty_grouping_fails_composition(self):
|
||||
pipeline = self._pipeline([])
|
||||
assert pipeline.compose_scroll_content() is False
|
||||
|
||||
|
||||
class TestWidthBudgetCountsGaps:
|
||||
def test_budget_accounts_for_intra_plugin_gaps(self):
|
||||
# 8 rows of 200px = 1600px of pixels, but with 8px gaps the real
|
||||
# occupancy is 1600 + 56 = 1656px. Against a 512px budget the row count
|
||||
# must be chosen using the gap-inclusive cost.
|
||||
adapter = adapter_with(
|
||||
content_padding=0, max_plugin_width_ratio=1.0, intra_plugin_gap=8)
|
||||
items = [canvas([(0, 200)], width=200) for _ in range(8)]
|
||||
images = adapter.get_content(NativePlugin(items), 'rows')
|
||||
n = len(images)
|
||||
assert 200 * n + 8 * (n - 1) <= DISPLAY_W
|
||||
|
||||
def test_gap_free_config_fits_more_rows(self):
|
||||
items = [canvas([(0, 200)], width=200) for _ in range(8)]
|
||||
with_gap = adapter_with(
|
||||
content_padding=0, max_plugin_width_ratio=1.0, intra_plugin_gap=64)
|
||||
without = adapter_with(
|
||||
content_padding=0, max_plugin_width_ratio=1.0, intra_plugin_gap=0)
|
||||
assert len(without.get_content(NativePlugin(items), 'r')) >= \
|
||||
len(with_gap.get_content(NativePlugin(items), 'r'))
|
||||
|
||||
|
||||
class TestStreamGrouping:
|
||||
def _stream(self, segments):
|
||||
from src.vegas_mode.stream_manager import StreamManager
|
||||
from collections import deque
|
||||
|
||||
sm = StreamManager.__new__(StreamManager)
|
||||
import threading
|
||||
sm._buffer_lock = threading.RLock()
|
||||
sm._active_buffer = deque(segments)
|
||||
return sm
|
||||
|
||||
def _seg(self, plugin_id, count, mode=None):
|
||||
from src.vegas_mode.stream_manager import ContentSegment
|
||||
from src.plugin_system.base_plugin import VegasDisplayMode
|
||||
imgs = [Image.new('RGB', (10, 8)) for _ in range(count)]
|
||||
return ContentSegment(
|
||||
plugin_id=plugin_id, images=imgs, total_width=10 * count,
|
||||
display_mode=mode or VegasDisplayMode.SCROLL)
|
||||
|
||||
def test_grouping_preserves_plugin_boundaries(self):
|
||||
sm = self._stream([self._seg('a', 3), self._seg('b', 1)])
|
||||
grouped = sm.get_grouped_content_for_composition()
|
||||
assert [(pid, len(imgs)) for pid, imgs in grouped] == [('a', 3), ('b', 1)]
|
||||
|
||||
def test_static_segments_are_skipped(self):
|
||||
from src.plugin_system.base_plugin import VegasDisplayMode
|
||||
sm = self._stream([
|
||||
self._seg('a', 2),
|
||||
self._seg('paused', 1, VegasDisplayMode.STATIC),
|
||||
self._seg('b', 1),
|
||||
])
|
||||
assert [pid for pid, _ in sm.get_grouped_content_for_composition()] == ['a', 'b']
|
||||
|
||||
def test_imageless_segments_are_skipped(self):
|
||||
sm = self._stream([self._seg('a', 0), self._seg('b', 2)])
|
||||
assert [pid for pid, _ in sm.get_grouped_content_for_composition()] == ['b']
|
||||
|
||||
def test_flat_accessor_still_matches_grouped_total(self):
|
||||
sm = self._stream([self._seg('a', 3), self._seg('b', 2)])
|
||||
assert len(sm.get_all_content_for_composition()) == 5
|
||||
|
||||
|
||||
class TestApiBoundsMatchValidate:
|
||||
"""
|
||||
The web API's accepted range for each Vegas setting must agree with
|
||||
VegasModeConfig.validate(), which is what actually gates Vegas starting.
|
||||
|
||||
A looser API bound saves a value with a 200 and then makes
|
||||
VegasModeCoordinator.start() bail out with only a log line, so the ticker
|
||||
silently never runs. A tighter one rejects a legitimate value with a 400.
|
||||
Both happened before this test existed.
|
||||
"""
|
||||
|
||||
# (config key, min, max) as validate() enforces them.
|
||||
EXPECTED = {
|
||||
'scroll_speed': (1, 200),
|
||||
'separator_width': (0, 128),
|
||||
'intra_plugin_gap': (0, 128),
|
||||
'target_fps': (30, 200),
|
||||
'buffer_ahead': (1, 5),
|
||||
'trim_threshold': (0, 254),
|
||||
'content_padding': (0, 128),
|
||||
'min_plugin_width': (0, 512),
|
||||
'plugins_per_cycle': (1, 50),
|
||||
}
|
||||
|
||||
def _api_numeric_fields(self):
|
||||
"""Extract the numeric_fields map from api_v3 without importing Flask."""
|
||||
import ast
|
||||
import pathlib
|
||||
src = pathlib.Path('web_interface/blueprints/api_v3.py').read_text()
|
||||
tree = ast.parse(src)
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Assign):
|
||||
continue
|
||||
targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
|
||||
if 'numeric_fields' not in targets:
|
||||
continue
|
||||
if not isinstance(node.value, ast.Dict):
|
||||
continue
|
||||
found = {}
|
||||
for key, value in zip(node.value.keys, node.value.values):
|
||||
if not isinstance(key, ast.Constant):
|
||||
continue
|
||||
if not str(key.value).startswith('vegas_'):
|
||||
break
|
||||
cfg_key, lo, hi = [ast.literal_eval(e) for e in value.elts]
|
||||
found[cfg_key] = (lo, hi)
|
||||
if found:
|
||||
return found
|
||||
raise AssertionError("could not locate the vegas numeric_fields map")
|
||||
|
||||
def test_every_bound_matches_validate(self):
|
||||
api = self._api_numeric_fields()
|
||||
mismatched = {
|
||||
key: (api[key], expected)
|
||||
for key, expected in self.EXPECTED.items()
|
||||
if key in api and api[key] != expected
|
||||
}
|
||||
assert not mismatched, f"API bounds disagree with validate(): {mismatched}"
|
||||
|
||||
@pytest.mark.parametrize('key,bounds', sorted(EXPECTED.items()))
|
||||
def test_validate_accepts_both_endpoints(self, key, bounds):
|
||||
lo, hi = bounds
|
||||
for value in (lo, hi):
|
||||
cfg = VegasModeConfig(**{key: value})
|
||||
errors = [e for e in cfg.validate() if key in e]
|
||||
assert not errors, f"{key}={value} should be valid, got {errors}"
|
||||
|
||||
@pytest.mark.parametrize('key,bounds', sorted(EXPECTED.items()))
|
||||
def test_validate_rejects_just_outside(self, key, bounds):
|
||||
lo, hi = bounds
|
||||
for value in (lo - 1, hi + 1):
|
||||
cfg = VegasModeConfig(**{key: value})
|
||||
errors = [e for e in cfg.validate() if key in e]
|
||||
assert errors, f"{key}={value} should be rejected"
|
||||
|
||||
|
||||
class TestCycleSizing:
|
||||
def test_plugins_per_cycle_defaults_above_buffer_ahead(self):
|
||||
cfg = VegasModeConfig()
|
||||
assert cfg.plugins_per_cycle == 6
|
||||
assert cfg.plugins_per_cycle > cfg.buffer_ahead + 1
|
||||
|
||||
def test_plugins_per_cycle_parses(self):
|
||||
cfg = VegasModeConfig.from_config(
|
||||
{'display': {'vegas_scroll': {'plugins_per_cycle': 10}}})
|
||||
assert cfg.plugins_per_cycle == 10
|
||||
|
||||
def test_max_plugin_width_ratio_parses(self):
|
||||
cfg = VegasModeConfig.from_config(
|
||||
{'display': {'vegas_scroll': {'max_plugin_width_ratio': 1.5}}})
|
||||
assert cfg.max_plugin_width_ratio == 1.5
|
||||
|
||||
@pytest.mark.parametrize('overrides,bad_key', [
|
||||
({'plugins_per_cycle': 0}, 'plugins_per_cycle'),
|
||||
({'plugins_per_cycle': 99}, 'plugins_per_cycle'),
|
||||
({'max_plugin_width_ratio': -1.0}, 'max_plugin_width_ratio'),
|
||||
])
|
||||
def test_validate_rejects_out_of_range(self, overrides, bad_key):
|
||||
errors = VegasModeConfig(**overrides).validate()
|
||||
assert any(bad_key in e for e in errors), errors
|
||||
|
||||
|
||||
class TestScrollHelperLeadGap:
|
||||
def test_default_lead_gap_is_display_width(self):
|
||||
# Standalone tickers rely on scrolling in from off-screen; that
|
||||
# behaviour must not change for the many non-Vegas callers.
|
||||
sh = ScrollHelper(128, 32)
|
||||
sh.create_scrolling_image([Image.new('RGB', (100, 32), (255, 0, 0))],
|
||||
item_gap=0, element_gap=0)
|
||||
assert sh.cached_image.width == 128 + 100
|
||||
assert not column_has_ink(sh.cached_image)[:128].any()
|
||||
|
||||
def test_zero_lead_gap_starts_on_content(self):
|
||||
sh = ScrollHelper(128, 32)
|
||||
sh.create_scrolling_image([Image.new('RGB', (100, 32), (255, 0, 0))],
|
||||
item_gap=0, element_gap=0, lead_gap=0)
|
||||
assert sh.cached_image.width == 100
|
||||
assert column_has_ink(sh.cached_image)[0]
|
||||
|
||||
def test_explicit_lead_gap_is_honoured(self):
|
||||
sh = ScrollHelper(128, 32)
|
||||
sh.create_scrolling_image([Image.new('RGB', (100, 32), (255, 0, 0))],
|
||||
item_gap=0, element_gap=0, lead_gap=16)
|
||||
assert sh.cached_image.width == 116
|
||||
ink = column_has_ink(sh.cached_image)
|
||||
assert not ink[:16].any()
|
||||
assert ink[16:].all()
|
||||
|
||||
def test_negative_lead_gap_is_clamped(self):
|
||||
sh = ScrollHelper(128, 32)
|
||||
sh.create_scrolling_image([Image.new('RGB', (100, 32), (255, 0, 0))],
|
||||
item_gap=0, element_gap=0, lead_gap=-50)
|
||||
assert sh.cached_image.width == 100
|
||||
|
||||
def test_total_scroll_width_matches_image(self):
|
||||
# The cycle-complete check compares against total_scroll_width, so a
|
||||
# mismatch here would cut cycles short or overrun them.
|
||||
sh = ScrollHelper(128, 32)
|
||||
items = [Image.new('RGB', (60, 32), (255, 0, 0)) for _ in range(3)]
|
||||
sh.create_scrolling_image(items, item_gap=32, element_gap=0, lead_gap=0)
|
||||
assert sh.total_scroll_width == sh.cached_image.width
|
||||
assert sh.cached_image.width == 60 * 3 + 32 * 2
|
||||
|
||||
def test_item_gaps_are_unaffected_by_lead_gap(self):
|
||||
sh = ScrollHelper(128, 32)
|
||||
items = [Image.new('RGB', (10, 32), (255, 0, 0)) for _ in range(2)]
|
||||
sh.create_scrolling_image(items, item_gap=20, element_gap=0, lead_gap=0)
|
||||
ink = column_has_ink(sh.cached_image)
|
||||
assert ink[:10].all()
|
||||
assert not ink[10:30].any()
|
||||
assert ink[30:40].all()
|
||||
|
||||
|
||||
class TestConfigSurface:
|
||||
def test_new_keys_parse_from_config(self):
|
||||
cfg = VegasModeConfig.from_config({'display': {'vegas_scroll': {
|
||||
'auto_trim': False,
|
||||
'trim_threshold': 25,
|
||||
'content_padding': 4,
|
||||
'min_plugin_width': 64,
|
||||
'lead_in_width': 32,
|
||||
}}})
|
||||
assert cfg.auto_trim is False
|
||||
assert cfg.trim_threshold == 25
|
||||
assert cfg.content_padding == 4
|
||||
assert cfg.min_plugin_width == 64
|
||||
assert cfg.lead_in_width == 32
|
||||
|
||||
def test_defaults_favour_trimming(self):
|
||||
cfg = VegasModeConfig.from_config({})
|
||||
assert cfg.auto_trim is True
|
||||
assert cfg.lead_in_width == 0
|
||||
assert cfg.content_padding == 8
|
||||
|
||||
def test_round_trips_through_to_dict(self):
|
||||
cfg = VegasModeConfig(trim_threshold=20, lead_in_width=64)
|
||||
restored = VegasModeConfig.from_config(
|
||||
{'display': {'vegas_scroll': cfg.to_dict()}})
|
||||
assert restored.trim_threshold == 20
|
||||
assert restored.lead_in_width == 64
|
||||
|
||||
def test_update_applies_new_keys(self):
|
||||
cfg = VegasModeConfig()
|
||||
cfg.update({'display': {'vegas_scroll': {'content_padding': 16}}})
|
||||
assert cfg.content_padding == 16
|
||||
|
||||
@pytest.mark.parametrize('overrides,bad_key', [
|
||||
({'trim_threshold': 300}, 'trim_threshold'),
|
||||
({'trim_threshold': -1}, 'trim_threshold'),
|
||||
({'content_padding': -5}, 'content_padding'),
|
||||
({'content_padding': 500}, 'content_padding'),
|
||||
({'min_plugin_width': -1}, 'min_plugin_width'),
|
||||
({'lead_in_width': -1}, 'lead_in_width'),
|
||||
])
|
||||
def test_validate_rejects_out_of_range(self, overrides, bad_key):
|
||||
errors = VegasModeConfig(**overrides).validate()
|
||||
assert any(bad_key in e for e in errors), errors
|
||||
|
||||
def test_valid_config_has_no_errors(self):
|
||||
assert VegasModeConfig(
|
||||
trim_threshold=10, content_padding=8,
|
||||
min_plugin_width=8, lead_in_width=0,
|
||||
).validate() == []
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Tests for Vegas mode geometry primitives."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from src.vegas_mode.geometry import (
|
||||
DEFAULT_INK_THRESHOLD,
|
||||
column_has_ink,
|
||||
content_bounds,
|
||||
dead_window_stats,
|
||||
trim_to_content,
|
||||
window_coverage_stats,
|
||||
)
|
||||
|
||||
|
||||
def make_img(width, height=8, fill=(0, 0, 0)):
|
||||
return Image.new('RGB', (width, height), fill)
|
||||
|
||||
|
||||
def paint(img, x0, x1, color=(255, 255, 255)):
|
||||
"""Fill columns [x0, x1) with a colour."""
|
||||
block = Image.new('RGB', (x1 - x0, img.height), color)
|
||||
img.paste(block, (x0, 0))
|
||||
return img
|
||||
|
||||
|
||||
class TestColumnHasInk:
|
||||
def test_all_black_has_no_ink(self):
|
||||
assert not column_has_ink(make_img(16)).any()
|
||||
|
||||
def test_marks_only_painted_columns(self):
|
||||
img = paint(make_img(16), 4, 8)
|
||||
ink = column_has_ink(img)
|
||||
assert ink.tolist() == [False] * 4 + [True] * 4 + [False] * 8
|
||||
|
||||
def test_threshold_is_exclusive(self):
|
||||
# A pixel exactly at the threshold is not ink; one above it is.
|
||||
at = paint(make_img(4), 0, 4, (DEFAULT_INK_THRESHOLD,) * 3)
|
||||
above = paint(make_img(4), 0, 4, (DEFAULT_INK_THRESHOLD + 1,) * 3)
|
||||
assert not column_has_ink(at).any()
|
||||
assert column_has_ink(above).all()
|
||||
|
||||
def test_single_bright_channel_counts(self):
|
||||
img = paint(make_img(4), 1, 2, (0, 0, 200))
|
||||
assert column_has_ink(img).tolist() == [False, True, False, False]
|
||||
|
||||
def test_one_lit_pixel_lights_the_column(self):
|
||||
img = make_img(4, height=8)
|
||||
img.putpixel((2, 5), (255, 255, 255))
|
||||
assert column_has_ink(img).tolist() == [False, False, True, False]
|
||||
|
||||
|
||||
class TestContentBounds:
|
||||
def test_blank_returns_none(self):
|
||||
assert content_bounds(make_img(16)) is None
|
||||
|
||||
def test_finds_inclusive_bounds(self):
|
||||
assert content_bounds(paint(make_img(20), 5, 12)) == (5, 11)
|
||||
|
||||
def test_full_width_content(self):
|
||||
assert content_bounds(paint(make_img(10), 0, 10)) == (0, 9)
|
||||
|
||||
def test_spans_interior_gap(self):
|
||||
img = paint(make_img(30), 2, 5)
|
||||
paint(img, 20, 25)
|
||||
assert content_bounds(img) == (2, 24)
|
||||
|
||||
|
||||
class TestTrimToContent:
|
||||
def test_blank_image_reports_blank(self):
|
||||
result = trim_to_content(make_img(512))
|
||||
assert result.is_blank
|
||||
assert result.image is None
|
||||
assert result.width == 0
|
||||
assert result.original_width == 512
|
||||
|
||||
def test_trims_both_edges(self):
|
||||
result = trim_to_content(paint(make_img(512), 100, 150))
|
||||
assert not result.is_blank
|
||||
assert result.width == 50
|
||||
assert result.trimmed_left == 100
|
||||
assert result.trimmed_right == 362
|
||||
assert result.removed == 462
|
||||
|
||||
def test_preserves_interior_gap(self):
|
||||
# Two content blocks with a wide blank between them: the gap is the
|
||||
# plugin's layout and must survive trimming.
|
||||
img = paint(make_img(400), 50, 80)
|
||||
paint(img, 300, 330)
|
||||
result = trim_to_content(img)
|
||||
assert result.width == 280 # 50..329 inclusive
|
||||
assert column_has_ink(result.image).sum() == 60
|
||||
|
||||
def test_full_width_content_is_returned_unchanged(self):
|
||||
img = paint(make_img(128), 0, 128)
|
||||
result = trim_to_content(img)
|
||||
assert result.image is img
|
||||
assert result.removed == 0
|
||||
|
||||
def test_non_black_background_is_never_trimmed(self):
|
||||
# A plugin drawing on a dark-but-not-black background fills every
|
||||
# column with ink, so there is nothing to reclaim.
|
||||
result = trim_to_content(make_img(256, fill=(0, 0, 40)))
|
||||
assert result.removed == 0
|
||||
assert result.width == 256
|
||||
|
||||
def test_padding_keeps_margin_up_to_what_exists(self):
|
||||
result = trim_to_content(paint(make_img(512), 100, 150), padding=8)
|
||||
assert result.trimmed_left == 92
|
||||
assert result.width == 66 # 50 content + 8 each side
|
||||
|
||||
def test_padding_cannot_widen_beyond_original(self):
|
||||
# Content starts 2px in; padding of 8 can only reclaim the 2 available.
|
||||
result = trim_to_content(paint(make_img(64), 2, 60), padding=8)
|
||||
assert result.trimmed_left == 0
|
||||
assert result.trimmed_right == 0
|
||||
assert result.width == 64
|
||||
|
||||
def test_height_is_preserved(self):
|
||||
result = trim_to_content(paint(make_img(200, height=64), 10, 20))
|
||||
assert result.image.height == 64
|
||||
|
||||
def test_real_world_of_the_day_case(self):
|
||||
# Measured on devpi: "No Data" occupying 35px of a 512px canvas.
|
||||
result = trim_to_content(paint(make_img(512, height=64), 4, 39))
|
||||
assert result.width == 35
|
||||
assert result.removed == 477
|
||||
|
||||
|
||||
class TestDeadWindowStats:
|
||||
def test_fully_inked_ticker_has_no_dead_windows(self):
|
||||
stats = dead_window_stats(paint(make_img(400), 0, 400), viewport_width=100)
|
||||
assert stats.dead_windows == 0
|
||||
assert stats.dead_ratio == 0.0
|
||||
assert stats.longest_dead_run == 0
|
||||
|
||||
def test_fully_blank_ticker_is_all_dead(self):
|
||||
stats = dead_window_stats(make_img(400), viewport_width=100)
|
||||
assert stats.total_windows == 301
|
||||
assert stats.dead_windows == 301
|
||||
assert stats.dead_ratio == 1.0
|
||||
assert stats.longest_dead_run == 301
|
||||
|
||||
def test_leading_blank_run_is_measured(self):
|
||||
# 512px of black then solid content: windows fully inside the black
|
||||
# stretch are dead. With a 100px viewport, starts 0..412 exist and a
|
||||
# window is dead while it holds >=95 blank columns.
|
||||
img = paint(make_img(1024), 512, 1024)
|
||||
stats = dead_window_stats(img, viewport_width=100)
|
||||
assert stats.dead_windows == 418 # starts 0..417 keep >=95 blank cols
|
||||
assert stats.longest_dead_run == 418
|
||||
|
||||
def test_narrow_content_island_still_leaves_dead_windows(self):
|
||||
# 35px of content in a 512px field, viewed 100px at a time: no window
|
||||
# can be 95% blank once it overlaps 35 lit columns, but the windows
|
||||
# clear of it are dead.
|
||||
img = paint(make_img(512), 100, 135)
|
||||
stats = dead_window_stats(img, viewport_width=100)
|
||||
assert stats.dead_windows > 0
|
||||
assert stats.dead_ratio == pytest.approx(
|
||||
stats.dead_windows / stats.total_windows
|
||||
)
|
||||
|
||||
def test_step_reduces_sampling(self):
|
||||
img = paint(make_img(1000), 500, 1000)
|
||||
exact = dead_window_stats(img, viewport_width=100, step=1)
|
||||
strided = dead_window_stats(img, viewport_width=100, step=10)
|
||||
assert strided.total_windows < exact.total_windows
|
||||
# Same underlying shape, so the ratios should stay close.
|
||||
assert strided.dead_ratio == pytest.approx(exact.dead_ratio, abs=0.02)
|
||||
|
||||
def test_image_narrower_than_viewport_is_one_window(self):
|
||||
stats = dead_window_stats(make_img(50), viewport_width=100)
|
||||
assert stats.total_windows == 1
|
||||
assert stats.dead_windows == 1
|
||||
|
||||
def test_zero_viewport_is_handled(self):
|
||||
stats = dead_window_stats(make_img(50), viewport_width=0)
|
||||
assert stats.total_windows == 0
|
||||
assert stats.dead_ratio == 0.0
|
||||
|
||||
def test_longest_run_picks_the_larger_of_two_gaps(self):
|
||||
# Short blank gap, content, then a long blank gap.
|
||||
img = make_img(1000)
|
||||
paint(img, 150, 400)
|
||||
paint(img, 500, 520)
|
||||
stats = dead_window_stats(img, viewport_width=100)
|
||||
# The 400..500 gap is only 100 wide; the tail from 520 is 480 wide.
|
||||
assert stats.longest_dead_run >= 380
|
||||
|
||||
|
||||
class TestWindowCoverageStats:
|
||||
def test_solid_content_is_fully_covered(self):
|
||||
stats = window_coverage_stats(paint(make_img(600), 0, 600), viewport_width=100)
|
||||
assert stats.mean_ink_ratio == 1.0
|
||||
assert stats.min_ink_ratio == 1.0
|
||||
assert stats.sparse_windows == 0
|
||||
|
||||
def test_blank_strip_is_entirely_sparse(self):
|
||||
stats = window_coverage_stats(make_img(600), viewport_width=100)
|
||||
assert stats.mean_ink_ratio == 0.0
|
||||
assert stats.sparse_ratio == 1.0
|
||||
|
||||
def test_catches_sliver_windows_that_dead_ratio_misses(self):
|
||||
# Narrow content islands separated by more than the viewport. A window
|
||||
# holding one whole 40px island carries 472 blank columns — under the
|
||||
# 486 needed to count as "dead" — yet only 7.8% ink, so it still reads
|
||||
# as an empty panel. Coverage must flag strictly more positions than
|
||||
# the dead-window scan does.
|
||||
img = paint(make_img(2000), 0, 40)
|
||||
paint(img, 1000, 1040)
|
||||
dead = dead_window_stats(img, viewport_width=512)
|
||||
cover = window_coverage_stats(img, viewport_width=512, sparse_ink_ratio=0.10)
|
||||
assert cover.sparse_windows > dead.dead_windows
|
||||
assert cover.min_ink_ratio == 0.0
|
||||
|
||||
def test_adjacent_full_width_segments_stay_partially_covered(self):
|
||||
# Documents why the dead-window scan alone understated the problem:
|
||||
# two 512px segments with mid-canvas content never fully blank the
|
||||
# viewport, they just hold it at a thin ~28%.
|
||||
img = paint(make_img(1024), 185, 330)
|
||||
paint(img, 697, 842)
|
||||
dead = dead_window_stats(img, viewport_width=512)
|
||||
cover = window_coverage_stats(img, viewport_width=512)
|
||||
assert dead.dead_windows == 0
|
||||
assert cover.mean_ink_ratio == pytest.approx(0.283, abs=0.01)
|
||||
|
||||
def test_min_ink_ratio_finds_the_worst_position(self):
|
||||
# A wide blank tail guarantees at least one totally empty viewport.
|
||||
img = paint(make_img(1200), 0, 200)
|
||||
stats = window_coverage_stats(img, viewport_width=200)
|
||||
assert stats.min_ink_ratio == 0.0
|
||||
assert stats.mean_ink_ratio > 0.0
|
||||
|
||||
def test_sparse_threshold_is_respected(self):
|
||||
# 40 inked columns in a 200px viewport = 20% coverage everywhere the
|
||||
# island is fully inside the window.
|
||||
img = paint(make_img(400), 100, 140)
|
||||
lenient = window_coverage_stats(img, viewport_width=200, sparse_ink_ratio=0.05)
|
||||
strict = window_coverage_stats(img, viewport_width=200, sparse_ink_ratio=0.50)
|
||||
assert strict.sparse_windows > lenient.sparse_windows
|
||||
|
||||
def test_step_approximates_exact_scan(self):
|
||||
img = paint(make_img(2000), 300, 500)
|
||||
paint(img, 1200, 1400)
|
||||
exact = window_coverage_stats(img, viewport_width=512, step=1)
|
||||
strided = window_coverage_stats(img, viewport_width=512, step=4)
|
||||
assert strided.mean_ink_ratio == pytest.approx(exact.mean_ink_ratio, abs=0.01)
|
||||
|
||||
def test_zero_viewport_is_handled(self):
|
||||
stats = window_coverage_stats(make_img(50), viewport_width=0)
|
||||
assert stats.total_windows == 0
|
||||
assert stats.sparse_ratio == 0.0
|
||||
|
||||
def test_image_narrower_than_viewport(self):
|
||||
stats = window_coverage_stats(paint(make_img(50), 0, 50), viewport_width=100)
|
||||
assert stats.total_windows == 1
|
||||
assert stats.mean_ink_ratio == pytest.approx(0.5)
|
||||
|
||||
|
||||
class TestLongestRunHelper:
|
||||
@pytest.mark.parametrize("flags,expected", [
|
||||
([], 0),
|
||||
([False, False], 0),
|
||||
([True], 1),
|
||||
([True, True, False, True], 2),
|
||||
([False, True, True, True, False, True], 3),
|
||||
([True, True, True], 3),
|
||||
])
|
||||
def test_run_lengths(self, flags, expected):
|
||||
from src.vegas_mode.geometry import _longest_true_run
|
||||
assert _longest_true_run(np.array(flags, dtype=bool)) == expected
|
||||
+152
-2
@@ -146,6 +146,11 @@ class TestConfigAPI:
|
||||
|
||||
def test_save_double_sided_settings(self, client, mock_config_manager):
|
||||
"""Double-sided form fields are persisted under display.double_sided."""
|
||||
# 2 copies on the vertical axis needs parallel to be a multiple of 2.
|
||||
mock_config_manager.load_config.return_value['display']['hardware'] = {
|
||||
'chain_length': 2, 'parallel': 2,
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
'/api/v3/config/main',
|
||||
data={
|
||||
@@ -175,6 +180,91 @@ class TestConfigAPI:
|
||||
assert ds['enabled'] is False
|
||||
assert ds['copies'] == 4
|
||||
|
||||
def test_save_double_sided_disabled_skips_divisibility_check(self, client, mock_config_manager):
|
||||
"""A copies/chain_length mismatch must not block saves while disabled.
|
||||
|
||||
The Display form posts copies/axis on every save, so validating them
|
||||
with the feature off locked users out of every other display setting.
|
||||
"""
|
||||
mock_config_manager.load_config.return_value['display']['hardware'] = {
|
||||
'chain_length': 3, 'parallel': 1,
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
'/api/v3/config/main',
|
||||
data={
|
||||
'double_sided_copies': '2',
|
||||
'double_sided_axis': 'horizontal',
|
||||
'brightness': '75',
|
||||
},
|
||||
content_type='application/x-www-form-urlencoded',
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
ds = mock_config_manager.save_config_atomic.call_args[0][0]['display']['double_sided']
|
||||
assert ds['enabled'] is False
|
||||
assert ds['copies'] == 2
|
||||
|
||||
def test_save_double_sided_enabled_enforces_divisibility(self, client, mock_config_manager):
|
||||
"""The same mismatch is still rejected once the feature is turned on."""
|
||||
mock_config_manager.load_config.return_value['display']['hardware'] = {
|
||||
'chain_length': 3, 'parallel': 1,
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
'/api/v3/config/main',
|
||||
data={
|
||||
'double_sided_enabled': 'true',
|
||||
'double_sided_copies': '2',
|
||||
'double_sided_axis': 'horizontal',
|
||||
},
|
||||
content_type='application/x-www-form-urlencoded',
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert 'chain length' in response.get_json()['message']
|
||||
mock_config_manager.save_config_atomic.assert_not_called()
|
||||
|
||||
def test_save_double_sided_vertical_checks_parallel(self, client, mock_config_manager):
|
||||
"""The vertical axis is checked against parallel, not chain_length."""
|
||||
mock_config_manager.load_config.return_value['display']['hardware'] = {
|
||||
'chain_length': 2, 'parallel': 3,
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
'/api/v3/config/main',
|
||||
data={
|
||||
'double_sided_enabled': 'true',
|
||||
'double_sided_copies': '2',
|
||||
'double_sided_axis': 'vertical',
|
||||
},
|
||||
content_type='application/x-www-form-urlencoded',
|
||||
)
|
||||
|
||||
# chain_length 2 would divide evenly — only parallel 3 rejects this.
|
||||
assert response.status_code == 400
|
||||
assert 'parallel' in response.get_json()['message']
|
||||
mock_config_manager.save_config_atomic.assert_not_called()
|
||||
|
||||
def test_save_double_sided_disabled_ignores_bad_values(self, client, mock_config_manager):
|
||||
"""While disabled, unusable copies/axis are dropped rather than rejected."""
|
||||
mock_config_manager.load_config.return_value['display']['double_sided'] = {
|
||||
'enabled': True, 'copies': 2, 'axis': 'horizontal',
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
'/api/v3/config/main',
|
||||
data={'double_sided_copies': 'abc', 'double_sided_axis': 'diagonal'},
|
||||
content_type='application/x-www-form-urlencoded',
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
ds = mock_config_manager.save_config_atomic.call_args[0][0]['display']['double_sided']
|
||||
assert ds['enabled'] is False
|
||||
# Stored values left untouched rather than overwritten with junk.
|
||||
assert ds['copies'] == 2
|
||||
assert ds['axis'] == 'horizontal'
|
||||
|
||||
def test_save_double_sided_invalid_copies_rejected(self, client, mock_config_manager):
|
||||
"""copies < 2 is rejected with a 400 before any save."""
|
||||
response = client.post(
|
||||
@@ -372,11 +462,71 @@ class TestPluginsAPI:
|
||||
}
|
||||
|
||||
response = client.get('/api/v3/plugins/installed')
|
||||
|
||||
|
||||
assert response.status_code == 200
|
||||
data = json.loads(response.data)
|
||||
assert isinstance(data, (list, dict))
|
||||
|
||||
|
||||
def test_installed_plugins_report_update_available(self, client, mock_plugin_manager):
|
||||
"""Installed-plugin entries surface latest_version + update_available
|
||||
by comparing the on-disk manifest version to the registry."""
|
||||
from web_interface.blueprints.api_v3 import api_v3
|
||||
api_v3.plugin_manager = mock_plugin_manager
|
||||
# No on-disk manifest to merge — keep the version we hand in below.
|
||||
mock_plugin_manager.plugins_dir = '/nonexistent-plugins-dir'
|
||||
mock_plugin_manager.get_all_plugin_info.return_value = [
|
||||
{'id': 'weather', 'name': 'Weather', 'version': '1.0.0'}
|
||||
]
|
||||
# Avoid touching plugin instances (Vegas hooks, enabled fallback).
|
||||
mock_plugin_manager.get_plugin.return_value = None
|
||||
# Registry advertises a newer version than the installed one.
|
||||
api_v3.plugin_store_manager.get_registry_info.return_value = {
|
||||
'verified': True, 'latest_version': '1.2.0'
|
||||
}
|
||||
|
||||
response = client.get('/api/v3/plugins/installed')
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.data)
|
||||
entry = payload['data']['plugins'][0]
|
||||
assert entry['version'] == '1.0.0'
|
||||
assert entry['latest_version'] == '1.2.0'
|
||||
assert entry['update_available'] is True
|
||||
|
||||
def test_installed_plugins_no_update_when_current(self, client, mock_plugin_manager):
|
||||
"""No update is flagged when installed version matches the registry."""
|
||||
from web_interface.blueprints.api_v3 import api_v3
|
||||
api_v3.plugin_manager = mock_plugin_manager
|
||||
mock_plugin_manager.plugins_dir = '/nonexistent-plugins-dir'
|
||||
mock_plugin_manager.get_all_plugin_info.return_value = [
|
||||
{'id': 'weather', 'name': 'Weather', 'version': '1.2.0'}
|
||||
]
|
||||
mock_plugin_manager.get_plugin.return_value = None
|
||||
api_v3.plugin_store_manager.get_registry_info.return_value = {
|
||||
'verified': True, 'latest_version': '1.2.0'
|
||||
}
|
||||
|
||||
response = client.get('/api/v3/plugins/installed')
|
||||
|
||||
assert response.status_code == 200
|
||||
entry = json.loads(response.data)['data']['plugins'][0]
|
||||
assert entry['latest_version'] == '1.2.0'
|
||||
assert entry['update_available'] is False
|
||||
|
||||
def test_is_plugin_update_available_helper(self):
|
||||
"""Unit-level checks for the semver-aware update comparison."""
|
||||
from web_interface.blueprints.api_v3 import _is_plugin_update_available
|
||||
assert _is_plugin_update_available('1.0.0', '1.0.1') is True
|
||||
assert _is_plugin_update_available('1.0.1', '1.0.1') is False
|
||||
# Local build ahead of the registry must not be flagged.
|
||||
assert _is_plugin_update_available('2.0.0', '1.9.9') is False
|
||||
# Missing either side yields no signal.
|
||||
assert _is_plugin_update_available('', '1.0.0') is False
|
||||
assert _is_plugin_update_available('1.0.0', '') is False
|
||||
# Unparseable version differing from the installed one surfaces the
|
||||
# mismatch rather than hiding a possible update.
|
||||
assert _is_plugin_update_available('1.0.0', 'not-a-semver') is True
|
||||
|
||||
def test_get_plugin_health(self, client, mock_plugin_manager):
|
||||
"""Test getting plugin health information."""
|
||||
from web_interface.blueprints.api_v3 import api_v3
|
||||
|
||||
@@ -13,7 +13,7 @@ import uuid
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any
|
||||
from typing import Dict, Any, Optional
|
||||
from urllib.parse import urlparse, urlunparse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -120,6 +120,33 @@ def _get_plugin_version(plugin_id: str) -> str:
|
||||
logger.warning("[PluginVersion] Invalid JSON in manifest for %s at %s: %s", plugin_id, manifest_path, e)
|
||||
return ''
|
||||
|
||||
def _is_plugin_update_available(installed_version: str, latest_version: str) -> bool:
|
||||
"""Return True when the registry's ``latest_version`` is strictly newer
|
||||
than the installed version.
|
||||
|
||||
Uses PEP 440 / semver-aware comparison so a locally modified plugin whose
|
||||
version is *ahead* of the published registry is not flagged as needing an
|
||||
update. If either version string can't be parsed, falls back to a plain
|
||||
inequality check (any difference is surfaced so the user can reconcile).
|
||||
"""
|
||||
if not installed_version or not latest_version:
|
||||
return False
|
||||
if installed_version == latest_version:
|
||||
return False
|
||||
try:
|
||||
from packaging.version import parse as _parse_version, InvalidVersion
|
||||
except ImportError:
|
||||
# packaging is a core dependency, but if it's somehow unavailable we
|
||||
# can't compare semantically — surface the mismatch we already know
|
||||
# exists (the two strings differ).
|
||||
return True
|
||||
try:
|
||||
return _parse_version(latest_version) > _parse_version(installed_version)
|
||||
except InvalidVersion:
|
||||
# Unparseable version string: we can't tell direction, so surface the
|
||||
# mismatch rather than silently hiding a potential update.
|
||||
return True
|
||||
|
||||
def _ensure_cache_manager():
|
||||
"""Ensure cache manager is initialized."""
|
||||
global cache_manager
|
||||
@@ -837,16 +864,15 @@ def save_main_config():
|
||||
ds_config = current_config['display']['double_sided']
|
||||
|
||||
# Enabled checkbox: omitted from the form when unchecked.
|
||||
ds_config['enabled'] = _coerce_to_bool(data.get('double_sided_enabled'))
|
||||
# The Display form posts copies/axis on every save regardless of this
|
||||
# checkbox, so when the feature is off we accept the values without
|
||||
# rejecting the whole save — otherwise a stale copies/chain_length
|
||||
# mismatch locks the user out of every other display setting.
|
||||
enabled = _coerce_to_bool(data.get('double_sided_enabled'))
|
||||
ds_config['enabled'] = enabled
|
||||
|
||||
if 'double_sided_copies' in data and data['double_sided_copies'] not in ('', None):
|
||||
try:
|
||||
copies = int(data['double_sided_copies'])
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({'status': 'error', 'message': "Double-sided copies must be an integer"}), 400
|
||||
if not (2 <= copies <= 8):
|
||||
return jsonify({'status': 'error', 'message': "Double-sided copies must be between 2 and 8"}), 400
|
||||
# Validate divisibility against the relevant hardware dimension.
|
||||
def _copies_fits_hardware(copies: int) -> Optional[str]:
|
||||
"""Error message if copies doesn't divide the panel evenly, else None."""
|
||||
# Use axis from this request if provided, else from stored config.
|
||||
hw = current_config.get('display', {}).get('hardware', {})
|
||||
effective_axis = (data.get('double_sided_axis')
|
||||
@@ -854,22 +880,50 @@ def save_main_config():
|
||||
if effective_axis == 'horizontal':
|
||||
chain_length = int(hw.get('chain_length', 2) or 2)
|
||||
if chain_length % copies != 0:
|
||||
return jsonify({'status': 'error', 'message': f"Double-sided copies ({copies}) must divide chain length ({chain_length}) evenly"}), 400
|
||||
return f"Double-sided copies ({copies}) must divide chain length ({chain_length}) evenly"
|
||||
elif effective_axis == 'vertical':
|
||||
parallel = int(hw.get('parallel', 1) or 1)
|
||||
if parallel % copies != 0:
|
||||
return jsonify({'status': 'error', 'message': f"Double-sided copies ({copies}) must divide parallel ({parallel}) evenly"}), 400
|
||||
ds_config['copies'] = copies
|
||||
return f"Double-sided copies ({copies}) must divide parallel ({parallel}) evenly"
|
||||
return None
|
||||
|
||||
if 'double_sided_copies' in data and data['double_sided_copies'] not in ('', None):
|
||||
copies = None
|
||||
try:
|
||||
copies = int(data['double_sided_copies'])
|
||||
except (ValueError, TypeError):
|
||||
if enabled:
|
||||
return jsonify({'status': 'error', 'message': "Double-sided copies must be an integer"}), 400
|
||||
if copies is not None and not (2 <= copies <= 8):
|
||||
if enabled:
|
||||
return jsonify({'status': 'error', 'message': "Double-sided copies must be between 2 and 8"}), 400
|
||||
# Disabled: leave the stored value alone rather than writing junk.
|
||||
copies = None
|
||||
if copies is not None:
|
||||
# Divisibility is a hardware-relational check — only meaningful
|
||||
# when the feature is actually on.
|
||||
if enabled:
|
||||
fit_error = _copies_fits_hardware(copies)
|
||||
if fit_error:
|
||||
return jsonify({'status': 'error', 'message': fit_error}), 400
|
||||
ds_config['copies'] = copies
|
||||
|
||||
if 'double_sided_axis' in data:
|
||||
axis = data['double_sided_axis']
|
||||
if axis not in ('horizontal', 'vertical'):
|
||||
return jsonify({'status': 'error', 'message': "Double-sided axis must be 'horizontal' or 'vertical'"}), 400
|
||||
ds_config['axis'] = axis
|
||||
if enabled:
|
||||
return jsonify({'status': 'error', 'message': "Double-sided axis must be 'horizontal' or 'vertical'"}), 400
|
||||
else:
|
||||
ds_config['axis'] = axis
|
||||
|
||||
# Handle Vegas scroll mode settings
|
||||
vegas_fields = ['vegas_scroll_enabled', 'vegas_scroll_speed', 'vegas_separator_width',
|
||||
'vegas_target_fps', 'vegas_buffer_ahead', 'vegas_plugin_order', 'vegas_excluded_plugins']
|
||||
'vegas_target_fps', 'vegas_buffer_ahead', 'vegas_plugin_order', 'vegas_excluded_plugins',
|
||||
'vegas_auto_trim', 'vegas_trim_threshold', 'vegas_content_padding',
|
||||
'vegas_min_plugin_width', 'vegas_lead_in_width', 'vegas_plugins_per_cycle',
|
||||
'vegas_max_plugin_width_ratio', 'vegas_dynamic_duration_enabled',
|
||||
'vegas_min_cycle_duration', 'vegas_max_cycle_duration',
|
||||
'vegas_intra_plugin_gap']
|
||||
|
||||
if any(k in data for k in vegas_fields):
|
||||
if 'display' not in current_config:
|
||||
@@ -884,13 +938,51 @@ def save_main_config():
|
||||
# was submitted (any vegas field present) but enabled key is missing,
|
||||
# the checkbox was unchecked and we should set enabled=False
|
||||
vegas_config['enabled'] = _coerce_to_bool(data.get('vegas_scroll_enabled'))
|
||||
vegas_config['auto_trim'] = _coerce_to_bool(data.get('vegas_auto_trim'))
|
||||
vegas_config['dynamic_duration_enabled'] = _coerce_to_bool(
|
||||
data.get('vegas_dynamic_duration_enabled'))
|
||||
|
||||
# Handle numeric settings with validation
|
||||
# max_plugin_width_ratio is the one fractional setting, so it is
|
||||
# handled outside the integer loop below.
|
||||
if data.get('vegas_max_plugin_width_ratio') not in ('', None):
|
||||
try:
|
||||
ratio = float(data['vegas_max_plugin_width_ratio'])
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({
|
||||
'status': 'error',
|
||||
'message': "Invalid value for vegas_max_plugin_width_ratio: "
|
||||
"must be a number"
|
||||
}), 400
|
||||
if not (0 <= ratio <= 20):
|
||||
return jsonify({
|
||||
'status': 'error',
|
||||
'message': "Invalid value for vegas_max_plugin_width_ratio: "
|
||||
"must be between 0 and 20 (0 disables the cap)"
|
||||
}), 400
|
||||
vegas_config['max_plugin_width_ratio'] = ratio
|
||||
|
||||
# Handle numeric settings with validation.
|
||||
#
|
||||
# These bounds must match VegasModeConfig.validate(), which is what
|
||||
# actually gates Vegas starting. Where they were looser, a value
|
||||
# saved with a 200 and then made VegasModeCoordinator.start() bail
|
||||
# out with only a log line, so the ticker silently never ran.
|
||||
# Where they were tighter (scroll_speed capped at 100 against a
|
||||
# slider that goes to 200), a legitimate value was rejected with a
|
||||
# 400. See test_vegas_api_bounds_match_validate.
|
||||
numeric_fields = {
|
||||
'vegas_scroll_speed': ('scroll_speed', 1, 100),
|
||||
'vegas_separator_width': ('separator_width', 0, 500),
|
||||
'vegas_target_fps': ('target_fps', 1, 200),
|
||||
'vegas_buffer_ahead': ('buffer_ahead', 1, 20),
|
||||
'vegas_scroll_speed': ('scroll_speed', 1, 200),
|
||||
'vegas_separator_width': ('separator_width', 0, 128),
|
||||
'vegas_intra_plugin_gap': ('intra_plugin_gap', 0, 128),
|
||||
'vegas_target_fps': ('target_fps', 30, 200),
|
||||
'vegas_buffer_ahead': ('buffer_ahead', 1, 5),
|
||||
'vegas_trim_threshold': ('trim_threshold', 0, 254),
|
||||
'vegas_content_padding': ('content_padding', 0, 128),
|
||||
'vegas_min_plugin_width': ('min_plugin_width', 0, 512),
|
||||
'vegas_lead_in_width': ('lead_in_width', 0, 2048),
|
||||
'vegas_plugins_per_cycle': ('plugins_per_cycle', 1, 50),
|
||||
'vegas_min_cycle_duration': ('min_cycle_duration', 5, 3600),
|
||||
'vegas_max_cycle_duration': ('max_cycle_duration', 10, 3600),
|
||||
}
|
||||
for field_name, (config_key, min_val, max_val) in numeric_fields.items():
|
||||
if field_name in data:
|
||||
@@ -2242,9 +2334,12 @@ def get_installed_plugins():
|
||||
if enabled is None:
|
||||
enabled = plugin_instance.enabled if plugin_instance else True
|
||||
|
||||
# Verified from registry (no network call)
|
||||
# Verified + latest published version from registry (no network call)
|
||||
store_info = api_v3.plugin_store_manager.get_registry_info(plugin_id)
|
||||
verified = store_info.get('verified', False) if store_info else False
|
||||
latest_version = store_info.get('latest_version', '') if store_info else ''
|
||||
installed_version = plugin_info.get('version', '')
|
||||
update_available = _is_plugin_update_available(installed_version, latest_version)
|
||||
|
||||
# Local git info (single subprocess on cache miss, zero on hit)
|
||||
plugin_path = Path(api_v3.plugin_manager.plugins_dir) / plugin_id
|
||||
@@ -2291,6 +2386,8 @@ def get_installed_plugins():
|
||||
'id': plugin_id,
|
||||
'name': plugin_info.get('name', plugin_id),
|
||||
'version': plugin_info.get('version', ''),
|
||||
'latest_version': latest_version,
|
||||
'update_available': update_available,
|
||||
'author': plugin_info.get('author', 'Unknown'),
|
||||
'category': plugin_info.get('category', 'General'),
|
||||
'description': plugin_info.get('description', 'No description available'),
|
||||
@@ -5393,6 +5490,18 @@ def get_plugin_schema():
|
||||
schema = schema_mgr.load_schema(plugin_id, use_cache=True)
|
||||
|
||||
if schema:
|
||||
# Offer installed visual skins as a dropdown (returns a copy;
|
||||
# the cached schema and validation are never enum-restricted)
|
||||
try:
|
||||
current_skin = None
|
||||
if api_v3.config_manager:
|
||||
config = api_v3.config_manager.load_config()
|
||||
current_skin = config.get(plugin_id, {}).get('skin')
|
||||
injected = schema_mgr.inject_skin_selector(schema, plugin_id, current_skin)
|
||||
if isinstance(injected, dict):
|
||||
schema = injected
|
||||
except Exception:
|
||||
logger.debug('Skin selector injection failed for %s', plugin_id, exc_info=True)
|
||||
return jsonify({'status': 'success', 'data': {'schema': schema}})
|
||||
|
||||
# Return a simple default schema if file not found
|
||||
@@ -5421,6 +5530,43 @@ def get_plugin_schema():
|
||||
logger.error('Error in get_plugin_schema', exc_info=True)
|
||||
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details'}), 500
|
||||
|
||||
@api_v3.route('/skins', methods=['GET'])
|
||||
def list_skins():
|
||||
"""List installed visual skins (docs/SKIN_SYSTEM.md).
|
||||
|
||||
Optional ?plugin_id=... filters to skins matching that plugin.
|
||||
"""
|
||||
try:
|
||||
from src.skin_system import skin_runtime
|
||||
|
||||
plugin_id = request.args.get('plugin_id')
|
||||
if plugin_id:
|
||||
skins = skin_runtime.skins_for_plugin(plugin_id)
|
||||
else:
|
||||
# The discovery cache self-invalidates on directory/manifest
|
||||
# mtime changes, so no force_refresh — keeps Pi disk I/O down.
|
||||
skins = skin_runtime.discover_skins()
|
||||
|
||||
payload = []
|
||||
for skin_id, manifest in sorted(skins.items()):
|
||||
skin_dir = Path(manifest['_skin_dir'])
|
||||
preview = manifest.get('preview')
|
||||
payload.append({
|
||||
'id': skin_id,
|
||||
'name': manifest.get('name', skin_id),
|
||||
'version': manifest.get('version'),
|
||||
'author': manifest.get('author'),
|
||||
'description': manifest.get('description', ''),
|
||||
'skin_api_version': manifest.get('skin_api_version'),
|
||||
'targets': manifest.get('targets', {}),
|
||||
'modes': manifest.get('modes', []),
|
||||
'has_preview': bool(preview and (skin_dir / preview).is_file()),
|
||||
})
|
||||
return jsonify({'status': 'success', 'data': {'skins': payload}})
|
||||
except Exception:
|
||||
logger.error('Error in list_skins', exc_info=True)
|
||||
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details'}), 500
|
||||
|
||||
@api_v3.route('/plugins/config/reset', methods=['POST'])
|
||||
def reset_plugin_config():
|
||||
"""Reset plugin configuration to schema defaults"""
|
||||
@@ -7022,6 +7168,29 @@ def list_plugin_assets():
|
||||
logger.error('Unhandled exception', exc_info=True)
|
||||
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details'}), 500
|
||||
|
||||
@api_v3.route('/display/current-status', methods=['GET'])
|
||||
def get_current_display_status():
|
||||
"""Return the display mode/plugin currently intended to be shown.
|
||||
|
||||
Published by the display process (display_controller._publish_current_mode_state)
|
||||
to the shared cache whenever the active mode changes, so the web UI (e.g. the
|
||||
System Logs page) can show what's on screen without querying the display
|
||||
process directly.
|
||||
"""
|
||||
try:
|
||||
cache = _ensure_cache_manager()
|
||||
state = cache.get('display_current_state', max_age=120)
|
||||
if state is None:
|
||||
state = {
|
||||
'mode': None,
|
||||
'plugin_id': None,
|
||||
'last_updated': None,
|
||||
}
|
||||
return jsonify({'status': 'success', 'data': state})
|
||||
except Exception:
|
||||
logger.error('Error in get_current_display_status', exc_info=True)
|
||||
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details'}), 500
|
||||
|
||||
@api_v3.route('/logs', methods=['GET'])
|
||||
def get_logs():
|
||||
"""Get system logs from journalctl"""
|
||||
|
||||
@@ -1334,6 +1334,21 @@ button.bg-white {
|
||||
color: #93c5fd;
|
||||
}
|
||||
|
||||
/* Installed-plugin "Update" button when a newer version is published.
|
||||
A gentle pulsing ring draws the eye without being noisy. */
|
||||
.plugin-update-available {
|
||||
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.6);
|
||||
animation: plugin-update-pulse 2s ease-out infinite;
|
||||
}
|
||||
@keyframes plugin-update-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.55); }
|
||||
70% { box-shadow: 0 0 0 6px rgba(59, 130, 246, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.plugin-update-available { animation: none; }
|
||||
}
|
||||
|
||||
/* Under-voltage / throttling warning banner */
|
||||
.power-warning-banner {
|
||||
background-color: #fef2f2;
|
||||
|
||||
@@ -406,12 +406,18 @@
|
||||
if (!file) return;
|
||||
|
||||
const formData = new FormData();
|
||||
// Backend contract (see api_v3.upload_plugin_asset): the request
|
||||
// field must be named "files" (it does request.files.getlist('files')
|
||||
// and 400s with "No files provided" otherwise), and the response
|
||||
// carries the result in a top-level "uploaded_files" key, not nested
|
||||
// under "data". file-upload-single.js's working upload flow uses this
|
||||
// same contract.
|
||||
// Backend contract (api_v3.upload_plugin_asset): field must be named
|
||||
// "files" (request.files.getlist('files')), and the response carries
|
||||
// results in a top-level "uploaded_files" key, not nested under "data".
|
||||
formData.append('files', file);
|
||||
formData.append('plugin_id', pluginId);
|
||||
|
||||
|
||||
fetch('/api/v3/plugins/assets/upload', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
|
||||
@@ -1454,7 +1454,7 @@ function renderInstalledPlugins(plugins) {
|
||||
</div>
|
||||
<div class="text-sm text-gray-600 space-y-1.5 mb-3">
|
||||
<p class="flex items-center"><i class="fas fa-user mr-2 text-gray-400 w-4"></i>${escapeHtml(plugin.author || 'Unknown')}</p>
|
||||
${plugin.version ? `<p class="flex items-center"><i class="fas fa-tag mr-2 text-gray-400 w-4"></i>v${escapeHtml(plugin.version)}</p>` : ''}
|
||||
${plugin.version ? `<p class="flex items-center flex-wrap gap-1.5"><i class="fas fa-tag mr-2 text-gray-400 w-4"></i>v${escapeHtml(plugin.version)}${plugin.update_available && plugin.latest_version ? `<span class="badge badge-info" title="Installed v${escapeAttr(plugin.version)} → latest v${escapeAttr(plugin.latest_version)}"><i class="fas fa-arrow-circle-up mr-1"></i>v${escapeHtml(plugin.latest_version)} available</span>` : ''}</p>` : ''}
|
||||
<p class="flex items-center"><i class="fas fa-folder mr-2 text-gray-400 w-4"></i>${escapeHtml(plugin.category || 'General')}</p>
|
||||
</div>
|
||||
<p class="text-sm text-gray-700 leading-relaxed">${escapeHtml(plugin.description || 'No description available')}</p>
|
||||
@@ -1501,11 +1501,12 @@ function renderInstalledPlugins(plugins) {
|
||||
<i class="fas fa-cog mr-2"></i>Configure
|
||||
</button>
|
||||
<div style="display: flex; gap: 0.5rem;">
|
||||
<button class="btn bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-md text-sm font-semibold"
|
||||
<button class="btn ${plugin.update_available ? 'bg-blue-600 hover:bg-blue-700 plugin-update-available' : 'bg-yellow-600 hover:bg-yellow-700'} text-white px-4 py-2 rounded-md text-sm font-semibold"
|
||||
style="flex: 1;"
|
||||
data-plugin-id="${escapedPluginId}"
|
||||
data-action="update">
|
||||
<i class="fas fa-sync mr-2"></i>Update
|
||||
data-action="update"
|
||||
title="${plugin.update_available && plugin.latest_version ? 'Update to v' + escapeAttr(plugin.latest_version) : 'Reinstall the latest published version'}">
|
||||
<i class="fas ${plugin.update_available ? 'fa-arrow-circle-up' : 'fa-sync'} mr-2"></i>${plugin.update_available && plugin.latest_version ? 'Update to v' + escapeHtml(plugin.latest_version) : 'Update'}
|
||||
</button>
|
||||
<button class="btn bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-semibold"
|
||||
style="flex: 1;"
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
hx-ext="json-enc"
|
||||
hx-headers='{"Content-Type": "application/json"}'
|
||||
hx-swap="none"
|
||||
hx-on:htmx:after-request="showNotification(event.detail.xhr.responseJSON?.message || 'Display settings saved', event.detail.xhr.responseJSON?.status || 'success')"
|
||||
hx-on:htmx:after-request="showDisplaySaveResult(event.detail.xhr)"
|
||||
class="space-y-6"
|
||||
novalidate
|
||||
onsubmit="fixInvalidNumberInputs(this); return true;">
|
||||
@@ -425,7 +425,7 @@
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="setting-display-vegas_separator_width" data-setting-key="display.vegas_scroll.separator_width">
|
||||
<label for="vegas_separator_width" class="block text-sm font-medium text-gray-700">Separator Width (pixels){{ ui.help_tip('Blank gap inserted between each plugin block in the ticker (0–128 px).\nDefault: 32. Larger values make the boundary between plugins clearer.', 'Separator Width') }}</label>
|
||||
<label for="vegas_separator_width" class="block text-sm font-medium text-gray-700">Separator Width (pixels){{ ui.help_tip('Blank gap where one plugin hands off to the next (0–128 px).\nDefault: 32. Larger values make the boundary between plugins clearer. This does not apply between rows of the same plugin — see Row Gap for that.', 'Separator Width') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_separator_width"
|
||||
name="vegas_separator_width"
|
||||
@@ -436,6 +436,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="form-group" id="setting-display-vegas_intra_plugin_gap" data-setting-key="display.vegas_scroll.intra_plugin_gap">
|
||||
<label for="vegas_intra_plugin_gap" class="block text-sm font-medium text-gray-700">Row Gap (pixels){{ ui.help_tip('Gap between rows contributed by the same plugin (0–128 px).\nDefault: 8. Multi-row plugins such as sports scoreboards, news feeds and the F1 standings return one image per row; this keeps those rows close together while Separator Width still marks the jump to the next plugin. Set 0 to butt rows directly together.', 'Row Gap') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_intra_plugin_gap"
|
||||
name="vegas_intra_plugin_gap"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('intra_plugin_gap', 8) }}"
|
||||
min="0"
|
||||
max="128"
|
||||
class="form-control">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="form-group" id="setting-display-vegas_target_fps" data-setting-key="display.vegas_scroll.target_fps">
|
||||
<label for="vegas_target_fps" class="block text-sm font-medium text-gray-700">Target FPS{{ ui.help_tip('Frames per second the Vegas ticker aims to render.\nHigher = smoother scrolling but more CPU. Default: 125 (smoothest). Drop to 60/90 if the Pi runs hot.', 'Target FPS') }}</label>
|
||||
@@ -456,6 +469,137 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cycle Pacing -->
|
||||
<div class="mt-4 pt-4 border-t border-gray-200">
|
||||
<h4 class="text-sm font-medium text-gray-900 mb-3">Cycle Pacing</h4>
|
||||
<p class="text-sm text-gray-600 mb-3">How long one pass through the ticker lasts, and how many plugins it covers.</p>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="form-group" id="setting-display-vegas_plugins_per_cycle" data-setting-key="display.vegas_scroll.plugins_per_cycle">
|
||||
<label for="vegas_plugins_per_cycle" class="block text-sm font-medium text-gray-700">Plugins Per Cycle{{ ui.help_tip('How many plugins are composed into one pass of the ticker (1–50).\nDefault: 6. Higher means more variety before the ticker restarts, and fewer recompose pauses. Lower means each plugin comes around sooner.', 'Plugins Per Cycle') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_plugins_per_cycle"
|
||||
name="vegas_plugins_per_cycle"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('plugins_per_cycle', 6) }}"
|
||||
min="1"
|
||||
max="50"
|
||||
class="form-control">
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="setting-display-vegas_max_plugin_width_ratio" data-setting-key="display.vegas_scroll.max_plugin_width_ratio">
|
||||
<label for="vegas_max_plugin_width_ratio" class="block text-sm font-medium text-gray-700">Max Plugin Width (screens){{ ui.help_tip('Caps how much of one cycle a single plugin may occupy, measured in screen widths (0–20).\nDefault: 3. A long ticker such as a news feed or leaderboard is trimmed to this and the remainder shown on later cycles, so one plugin cannot hold the display for minutes. Set 0 for no limit.', 'Max Plugin Width') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_max_plugin_width_ratio"
|
||||
name="vegas_max_plugin_width_ratio"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('max_plugin_width_ratio', 3.0) }}"
|
||||
min="0"
|
||||
max="20"
|
||||
step="0.5"
|
||||
class="form-control">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group mt-4" id="setting-display-vegas_dynamic_duration_enabled" data-setting-key="display.vegas_scroll.dynamic_duration_enabled">
|
||||
<label class="flex items-center">
|
||||
<input type="checkbox"
|
||||
id="vegas_dynamic_duration_enabled"
|
||||
name="vegas_dynamic_duration_enabled"
|
||||
{% if main_config.display.get('vegas_scroll', {}).get('dynamic_duration_enabled', True) %}checked{% endif %}
|
||||
class="form-checkbox">
|
||||
<span class="ml-2 text-sm text-gray-700">Size cycle time to the content{{ ui.help_tip('When on, each cycle runs just long enough to scroll all its content past, clamped to the min and max below.\nWhen off, the max is always used. Default: on.', 'Dynamic Cycle Duration') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-2">
|
||||
<div class="form-group" id="setting-display-vegas_min_cycle_duration" data-setting-key="display.vegas_scroll.min_cycle_duration">
|
||||
<label for="vegas_min_cycle_duration" class="block text-sm font-medium text-gray-700">Min Cycle Time (seconds){{ ui.help_tip('Shortest a single ticker pass may last (5–3600 s).\nDefault: 60.', 'Min Cycle Time') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_min_cycle_duration"
|
||||
name="vegas_min_cycle_duration"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('min_cycle_duration', 60) }}"
|
||||
min="5"
|
||||
max="3600"
|
||||
class="form-control">
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="setting-display-vegas_max_cycle_duration" data-setting-key="display.vegas_scroll.max_cycle_duration">
|
||||
<label for="vegas_max_cycle_duration" class="block text-sm font-medium text-gray-700">Max Cycle Time (seconds){{ ui.help_tip('Longest a single ticker pass may last before it restarts with fresh content (10–3600 s).\nThis is the setting that caps total Vegas scroll time. Default: 240. Lower it if the ticker feels like it takes too long to come back around.', 'Max Cycle Time') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_max_cycle_duration"
|
||||
name="vegas_max_cycle_duration"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('max_cycle_duration', 240) }}"
|
||||
min="10"
|
||||
max="3600"
|
||||
class="form-control">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dead Space -->
|
||||
<div class="mt-4 pt-4 border-t border-gray-200">
|
||||
<h4 class="text-sm font-medium text-gray-900 mb-3">Dead Space</h4>
|
||||
<p class="text-sm text-gray-600 mb-3">Plugins that draw onto a full-screen canvas contribute all the empty space around their content. Trimming reclaims it so the ticker stays full.</p>
|
||||
|
||||
<div class="form-group mb-4" id="setting-display-vegas_auto_trim" data-setting-key="display.vegas_scroll.auto_trim">
|
||||
<label class="flex items-center">
|
||||
<input type="checkbox"
|
||||
id="vegas_auto_trim"
|
||||
name="vegas_auto_trim"
|
||||
{% if main_config.display.get('vegas_scroll', {}).get('auto_trim', True) %}checked{% endif %}
|
||||
class="form-checkbox">
|
||||
<span class="ml-2 text-sm text-gray-700">Trim empty edges from plugin content{{ ui.help_tip('Crops blank columns from the left and right of each plugin block before it enters the ticker. Space between two pieces of content inside a block is left alone, so layouts are not altered. Default: on.', 'Auto Trim') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="form-group" id="setting-display-vegas_content_padding" data-setting-key="display.vegas_scroll.content_padding">
|
||||
<label for="vegas_content_padding" class="block text-sm font-medium text-gray-700">Content Padding (pixels){{ ui.help_tip('Blank columns kept either side of trimmed content, so it does not butt against the separator (0–128 px).\nDefault: 8.', 'Content Padding') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_content_padding"
|
||||
name="vegas_content_padding"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('content_padding', 8) }}"
|
||||
min="0"
|
||||
max="128"
|
||||
class="form-control">
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="setting-display-vegas_lead_in_width" data-setting-key="display.vegas_scroll.lead_in_width">
|
||||
<label for="vegas_lead_in_width" class="block text-sm font-medium text-gray-700">Lead-In Gap (pixels){{ ui.help_tip('Blank space before the first plugin of each cycle (0–2048 px).\nDefault: 0. Anything approaching your screen width reads as the display switching off at the start of every cycle.', 'Lead-In Gap') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_lead_in_width"
|
||||
name="vegas_lead_in_width"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('lead_in_width', 0) }}"
|
||||
min="0"
|
||||
max="2048"
|
||||
class="form-control">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
|
||||
<div class="form-group" id="setting-display-vegas_trim_threshold" data-setting-key="display.vegas_scroll.trim_threshold">
|
||||
<label for="vegas_trim_threshold" class="block text-sm font-medium text-gray-700">Trim Threshold{{ ui.help_tip('How bright a pixel must be to count as content rather than empty space (0–254).\nDefault: 10, which ignores the near-black noise left by image compression. Raise it if very dark artwork is being kept; lower it if dark detail is being cropped.', 'Trim Threshold') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_trim_threshold"
|
||||
name="vegas_trim_threshold"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('trim_threshold', 10) }}"
|
||||
min="0"
|
||||
max="254"
|
||||
class="form-control">
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="setting-display-vegas_min_plugin_width" data-setting-key="display.vegas_scroll.min_plugin_width">
|
||||
<label for="vegas_min_plugin_width" class="block text-sm font-medium text-gray-700">Min Plugin Width (pixels){{ ui.help_tip('Plugin blocks narrower than this after trimming are skipped for that cycle (0–512 px).\nDefault: 8. Raise it to hide plugins showing only a tiny placeholder such as "No Data" until they have real content.', 'Min Plugin Width') }}</label>
|
||||
<input type="number"
|
||||
id="vegas_min_plugin_width"
|
||||
name="vegas_min_plugin_width"
|
||||
value="{{ main_config.display.get('vegas_scroll', {}).get('min_plugin_width', 8) }}"
|
||||
min="0"
|
||||
max="512"
|
||||
class="form-control">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Plugin Order Section -->
|
||||
<div class="mt-4 pt-4 border-t border-gray-200">
|
||||
<h4 class="text-sm font-medium text-gray-900 mb-3">Plugin Order</h4>
|
||||
@@ -475,22 +619,26 @@
|
||||
<h3 class="text-md font-medium text-gray-900 mb-1">Double-Sided Display</h3>
|
||||
<p class="text-sm text-gray-600 mb-4">Show the same content on every panel in the chain — e.g. two 64×32 panels mirrored, or four panels as two identical screens. Rendered once and duplicated, so it adds no extra CPU. Takes effect after a display restart.</p>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div class="form-group" id="setting-display-double_sided_enabled" data-setting-key="display.double_sided.enabled">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox"
|
||||
id="double_sided_enabled"
|
||||
name="double_sided_enabled"
|
||||
value="true"
|
||||
{% if main_config.display.get('double_sided', {}).get('enabled') %}checked{% endif %}
|
||||
class="form-control h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
|
||||
<span class="text-sm font-medium text-gray-700">Enabled</span>
|
||||
{{ ui.help_tip('Show the same content mirrored across every panel in the chain.\nRendered once and duplicated, so it adds no extra CPU. Takes effect after a display restart.', 'Double-Sided Enabled') }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-group mb-4" id="setting-display-double_sided_enabled" data-setting-key="display.double_sided.enabled">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox"
|
||||
id="double_sided_enabled"
|
||||
name="double_sided_enabled"
|
||||
value="true"
|
||||
{% if main_config.display.get('double_sided', {}).get('enabled') %}checked{% endif %}
|
||||
class="form-control h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
|
||||
<span class="text-sm font-medium text-gray-700">Enabled</span>
|
||||
{{ ui.help_tip('Show the same content mirrored across every panel in the chain.\nRendered once and duplicated, so it adds no extra CPU. Takes effect after a display restart.', 'Double-Sided Enabled') }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Hidden (not disabled) when the feature is off, so the values are
|
||||
still submitted and round-trip through a save. -->
|
||||
<div id="double_sided_settings"
|
||||
class="grid grid-cols-1 md:grid-cols-2 gap-4"
|
||||
{% if not main_config.display.get('double_sided', {}).get('enabled') %}style="display: none;"{% endif %}>
|
||||
<div class="form-group" id="setting-display-double_sided_copies" data-setting-key="display.double_sided.copies">
|
||||
<label for="double_sided_copies" class="block text-sm font-medium text-gray-700">Copies{{ ui.help_tip('How many identical screens to split the panel area into (2–8).\nMust divide the panel evenly — e.g. 2 for a two-sided cube.', 'Copies') }}</label>
|
||||
<label for="double_sided_copies" class="block text-sm font-medium text-gray-700">Copies{{ ui.help_tip('How many identical screens to split the panel area into (2–8).\nWhen enabled, this must divide the panel evenly — e.g. 2 for a two-sided cube.', 'Copies') }}</label>
|
||||
<input type="number"
|
||||
id="double_sided_copies"
|
||||
name="double_sided_copies"
|
||||
@@ -607,6 +755,28 @@ if (typeof window.fixInvalidNumberInputs !== 'function') {
|
||||
};
|
||||
}
|
||||
|
||||
// Report the outcome of a display-settings save. XMLHttpRequest has no
|
||||
// `responseJSON` (that's a jQuery property) — read `responseText` and the real
|
||||
// status code, otherwise a failed save reports success.
|
||||
window.showDisplaySaveResult = function(xhr) {
|
||||
// Only 2xx counts as saved. A network failure reports status 0, which any
|
||||
// `>= 400` test would wave through as success.
|
||||
const httpSuccess = xhr.status >= 200 && xhr.status < 300;
|
||||
let message = httpSuccess
|
||||
? 'Display settings saved'
|
||||
: 'Display settings were not saved. Check your connection and try again.';
|
||||
let status = httpSuccess ? 'success' : 'error';
|
||||
try {
|
||||
const data = JSON.parse(xhr.responseText);
|
||||
if (data.message) message = data.message;
|
||||
// A body can refine a successful verdict but never overturn a failed one.
|
||||
if (httpSuccess && data.status) status = data.status;
|
||||
} catch {
|
||||
// Non-JSON body — fall back to the status-code verdict above.
|
||||
}
|
||||
showNotification(message, status);
|
||||
};
|
||||
|
||||
// Vegas Scroll Mode Settings
|
||||
(function() {
|
||||
// Escape HTML to prevent XSS
|
||||
@@ -631,6 +801,18 @@ if (typeof window.fixInvalidNumberInputs !== 'function') {
|
||||
});
|
||||
}
|
||||
|
||||
// Double-sided: copies/axis only mean anything while the feature is on.
|
||||
// Hidden rather than disabled so the fields keep submitting and the server
|
||||
// still sees an 'off' state to persist.
|
||||
const doubleSidedCheckbox = document.getElementById('double_sided_enabled');
|
||||
const doubleSidedSettings = document.getElementById('double_sided_settings');
|
||||
|
||||
if (doubleSidedCheckbox && doubleSidedSettings) {
|
||||
doubleSidedCheckbox.addEventListener('change', function() {
|
||||
doubleSidedSettings.style.display = this.checked ? 'grid' : 'none';
|
||||
});
|
||||
}
|
||||
|
||||
// Update scroll speed display
|
||||
const scrollSpeedSlider = document.getElementById('vegas_scroll_speed');
|
||||
const scrollSpeedValue = document.getElementById('vegas_scroll_speed_value');
|
||||
|
||||
@@ -4,6 +4,17 @@
|
||||
<p class="mt-1 text-sm text-gray-600">View real-time logs from the LED matrix service for troubleshooting.</p>
|
||||
</div>
|
||||
|
||||
<!-- Currently displayed plugin -->
|
||||
<div id="current-plugin-banner" class="hidden mb-4 flex items-center gap-2 text-sm bg-blue-50 border border-blue-200 text-blue-800 rounded-lg px-3 py-2">
|
||||
<i class="fas fa-tv"></i>
|
||||
<span>Now showing: <strong id="current-plugin-mode">-</strong>
|
||||
<span id="current-plugin-id-wrap" class="hidden">(plugin: <code id="current-plugin-id" class="bg-blue-100 px-1 rounded"></code>)</span>
|
||||
</span>
|
||||
<button id="current-plugin-filter-btn" class="hidden ml-auto btn bg-blue-600 hover:bg-blue-700 text-white px-2 py-0.5 rounded text-xs">
|
||||
Filter to this plugin
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Controls -->
|
||||
<div class="flex flex-wrap items-center justify-between gap-4 mb-6">
|
||||
<div class="flex items-center space-x-4">
|
||||
@@ -27,6 +38,11 @@
|
||||
<option value="INFO">Info & Above</option>
|
||||
</select>
|
||||
|
||||
<!-- Plugin Filter -->
|
||||
<select id="log-plugin-filter" class="form-control text-sm">
|
||||
<option value="">All Plugins</option>
|
||||
</select>
|
||||
|
||||
<!-- Search -->
|
||||
<div class="relative">
|
||||
<input type="text" id="log-search" placeholder="Search logs..." class="form-control text-sm pl-8 pr-4 py-1 w-48">
|
||||
@@ -139,6 +155,7 @@ window._filteredLogs = [];
|
||||
const realtimeToggle = document.getElementById('log-realtime-toggle');
|
||||
const refreshBtn = document.getElementById('refresh-logs-btn');
|
||||
const levelFilter = document.getElementById('log-level-filter');
|
||||
const pluginFilter = document.getElementById('log-plugin-filter');
|
||||
const searchInput = document.getElementById('log-search');
|
||||
const autoscrollToggle = document.getElementById('log-autoscroll');
|
||||
const clearBtn = document.getElementById('clear-logs-btn');
|
||||
@@ -160,6 +177,11 @@ window._filteredLogs = [];
|
||||
levelFilter.parentNode.replaceChild(newFilter, levelFilter);
|
||||
newFilter.addEventListener('change', filterLogs);
|
||||
}
|
||||
if (pluginFilter) {
|
||||
const newFilter = pluginFilter.cloneNode(true);
|
||||
pluginFilter.parentNode.replaceChild(newFilter, pluginFilter);
|
||||
newFilter.addEventListener('change', filterLogs);
|
||||
}
|
||||
if (searchInput) {
|
||||
const newInput = searchInput.cloneNode(true);
|
||||
searchInput.parentNode.replaceChild(newInput, searchInput);
|
||||
@@ -180,6 +202,24 @@ window._filteredLogs = [];
|
||||
downloadBtn.parentNode.replaceChild(newBtn, downloadBtn);
|
||||
newBtn.addEventListener('click', downloadLogs);
|
||||
}
|
||||
const currentPluginFilterBtn = document.getElementById('current-plugin-filter-btn');
|
||||
if (currentPluginFilterBtn) {
|
||||
const newBtn = currentPluginFilterBtn.cloneNode(true);
|
||||
currentPluginFilterBtn.parentNode.replaceChild(newBtn, currentPluginFilterBtn);
|
||||
newBtn.addEventListener('click', function() {
|
||||
const pluginFilterEl = document.getElementById('log-plugin-filter');
|
||||
if (pluginFilterEl && window._currentPluginId) {
|
||||
pluginFilterEl.value = window._currentPluginId;
|
||||
filterLogs();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
refreshCurrentPluginStatus();
|
||||
if (window._currentPluginPollTimer) {
|
||||
clearInterval(window._currentPluginPollTimer);
|
||||
}
|
||||
window._currentPluginPollTimer = setInterval(refreshCurrentPluginStatus, 5000);
|
||||
|
||||
// Handle window resize for responsive height
|
||||
window.addEventListener('resize', function() {
|
||||
@@ -284,37 +324,25 @@ function processLogs(logsText, append = false) {
|
||||
// Skip empty lines
|
||||
if (!line.trim()) return;
|
||||
|
||||
// Try to parse journalctl format: "MMM DD HH:MM:SS hostname service[pid]: message"
|
||||
// Example: "Oct 13 14:23:45 raspberrypi ledmatrix[1234]: INFO: Starting display"
|
||||
|
||||
// journalctl (--output=short-iso) emits: "YYYY-MM-DDTHH:MM:SS+ZZZZ hostname service[pid]: message"
|
||||
// Example: "2024-01-15T10:23:45+0000 raspberrypi ledmatrix[1234]: INFO - plugin.nhl_scoreboard - [Plugin: nhl_scoreboard] Updated scores"
|
||||
// Also accept the older syslog-style "MMM DD HH:MM:SS" timestamp for compatibility.
|
||||
|
||||
let timestamp = '';
|
||||
let level = 'INFO';
|
||||
let message = line;
|
||||
|
||||
// Extract timestamp (first part before hostname)
|
||||
const timestampMatch = line.match(/^([A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})/);
|
||||
if (timestampMatch) {
|
||||
timestamp = timestampMatch[1];
|
||||
|
||||
// Find the message part (after service name and pid)
|
||||
const messageMatch = line.match(/:\s*(.+)$/);
|
||||
if (messageMatch) {
|
||||
message = messageMatch[1];
|
||||
|
||||
// Detect log level from message
|
||||
if (message.match(/\b(ERROR|CRITICAL|FATAL)\b/i)) {
|
||||
level = 'ERROR';
|
||||
} else if (message.match(/\b(WARNING|WARN)\b/i)) {
|
||||
level = 'WARNING';
|
||||
} else if (message.match(/\bDEBUG\b/i)) {
|
||||
level = 'DEBUG';
|
||||
} else if (message.match(/\bINFO\b/i)) {
|
||||
level = 'INFO';
|
||||
}
|
||||
|
||||
// Clean up level prefix from message if it exists
|
||||
message = message.replace(/^(ERROR|WARNING|WARN|INFO|DEBUG):\s*/i, '');
|
||||
}
|
||||
let plugin = '';
|
||||
let rest = null;
|
||||
|
||||
const isoMatch = line.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[+-]\d{2}:?\d{2}|Z))\s+(.*)$/);
|
||||
const syslogMatch = !isoMatch && line.match(/^([A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+(.*)$/);
|
||||
|
||||
if (isoMatch) {
|
||||
timestamp = isoMatch[1];
|
||||
rest = isoMatch[2];
|
||||
} else if (syslogMatch) {
|
||||
timestamp = syslogMatch[1];
|
||||
rest = syslogMatch[2];
|
||||
} else {
|
||||
// If no timestamp, use current time
|
||||
timestamp = new Date().toLocaleString('en-US', {
|
||||
@@ -327,14 +355,58 @@ function processLogs(logsText, append = false) {
|
||||
});
|
||||
}
|
||||
|
||||
if (rest !== null) {
|
||||
// Find the message part (after hostname + service name/pid)
|
||||
const messageMatch = rest.match(/:\s*(.+)$/);
|
||||
if (messageMatch) {
|
||||
message = messageMatch[1];
|
||||
|
||||
// Detect log level from message
|
||||
if (message.match(/\b(ERROR|CRITICAL|FATAL)\b/i)) {
|
||||
level = 'ERROR';
|
||||
} else if (message.match(/\b(WARNING|WARN)\b/i)) {
|
||||
level = 'WARNING';
|
||||
} else if (message.match(/\bDEBUG\b/i)) {
|
||||
level = 'DEBUG';
|
||||
} else if (message.match(/\bINFO\b/i)) {
|
||||
level = 'INFO';
|
||||
}
|
||||
|
||||
// Clean up level prefix from message if it exists
|
||||
message = message.replace(/^(ERROR|WARNING|WARN|INFO|DEBUG)\s*[-:]\s*/i, '');
|
||||
|
||||
// journalctl already carries its own timestamp; strip the app's
|
||||
// internal "YYYY-MM-DD HH:MM:SS.mmm - LEVEL - logger.name - "
|
||||
// prefix (see ContextualFormatter in src/logging_config.py) so
|
||||
// it isn't duplicated in the displayed message.
|
||||
message = message.replace(
|
||||
/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:\.\d+)?\s*-\s*(ERROR|WARNING|WARN|INFO|DEBUG|CRITICAL)\s*-\s*[\w.]+\s*-\s*/i,
|
||||
''
|
||||
);
|
||||
|
||||
// Extract the "[Plugin: <id>]" context tag emitted by
|
||||
// ContextualFormatter for every plugin logger (see
|
||||
// src/logging_config.py PluginLoggerAdapter), and pull it out
|
||||
// of the displayed message into its own field.
|
||||
const pluginMatch = message.match(/^\[Plugin:\s*([^\]]+)\]\s*/);
|
||||
if (pluginMatch) {
|
||||
plugin = pluginMatch[1].trim();
|
||||
message = message.replace(pluginMatch[0], '');
|
||||
}
|
||||
} else {
|
||||
message = rest;
|
||||
}
|
||||
}
|
||||
|
||||
const logEntry = {
|
||||
timestamp: timestamp,
|
||||
level: level,
|
||||
plugin: plugin,
|
||||
message: message,
|
||||
raw: line,
|
||||
id: Date.now() + Math.random()
|
||||
};
|
||||
|
||||
|
||||
// Don't add duplicate entries when appending
|
||||
if (!append || !window._allLogs.find(log => log.raw === line)) {
|
||||
window._allLogs.push(logEntry);
|
||||
@@ -346,9 +418,26 @@ function processLogs(logsText, append = false) {
|
||||
window._allLogs = window._allLogs.slice(-window._MAX_LOGS);
|
||||
}
|
||||
|
||||
updatePluginFilterOptions();
|
||||
filterLogs();
|
||||
}
|
||||
|
||||
function updatePluginFilterOptions() {
|
||||
const pluginFilterEl = document.getElementById('log-plugin-filter');
|
||||
if (!pluginFilterEl) return;
|
||||
|
||||
const previousValue = pluginFilterEl.value;
|
||||
const plugins = Array.from(new Set(window._allLogs.map(log => log.plugin).filter(Boolean))).sort();
|
||||
|
||||
pluginFilterEl.innerHTML = '<option value="">All Plugins</option>' +
|
||||
plugins.map(p => `<option value="${escapeHtml(p)}">${escapeHtml(p)}</option>`).join('');
|
||||
|
||||
// Restore previous selection if it's still a valid option
|
||||
if (previousValue && plugins.includes(previousValue)) {
|
||||
pluginFilterEl.value = previousValue;
|
||||
}
|
||||
}
|
||||
|
||||
function renderLogs() {
|
||||
if (window._filteredLogs.length === 0) {
|
||||
showEmptyState();
|
||||
@@ -364,10 +453,14 @@ function renderLogs() {
|
||||
window._filteredLogs.forEach(log => {
|
||||
const logElement = document.createElement('div');
|
||||
logElement.className = `log-entry py-1 px-2 hover:bg-gray-800 rounded transition-colors duration-150 ${getLogLevelClass(log.level)}`;
|
||||
const pluginBadge = log.plugin
|
||||
? `<span class="log-plugin flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold bg-purple-700 text-white" title="Plugin: ${escapeHtml(log.plugin)}">${escapeHtml(log.plugin)}</span>`
|
||||
: '';
|
||||
logElement.innerHTML = `
|
||||
<div class="flex items-start gap-3 text-xs font-mono">
|
||||
<span class="log-timestamp text-gray-400 flex-shrink-0 w-32">${escapeHtml(log.timestamp)}</span>
|
||||
<span class="log-level flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold ${getLogLevelBadgeClass(log.level)}">${log.level}</span>
|
||||
${pluginBadge}
|
||||
<span class="log-message flex-1 ${getLogLevelTextClass(log.level)} break-words">${escapeHtml(log.message)}</span>
|
||||
</div>
|
||||
`;
|
||||
@@ -410,10 +503,12 @@ function getLogLevelTextClass(level) {
|
||||
|
||||
function filterLogs() {
|
||||
const levelFilterEl = document.getElementById('log-level-filter');
|
||||
const pluginFilterEl = document.getElementById('log-plugin-filter');
|
||||
const searchEl = document.getElementById('log-search');
|
||||
if (!levelFilterEl || !searchEl) return;
|
||||
|
||||
|
||||
const levelFilter = levelFilterEl.value;
|
||||
const pluginFilter = pluginFilterEl ? pluginFilterEl.value : '';
|
||||
const searchTerm = searchEl.value.toLowerCase();
|
||||
|
||||
window._filteredLogs = window._allLogs.filter(log => {
|
||||
@@ -430,8 +525,14 @@ function filterLogs() {
|
||||
}
|
||||
}
|
||||
|
||||
// Plugin filter
|
||||
if (pluginFilter && log.plugin !== pluginFilter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Search filter
|
||||
if (searchTerm && !log.message.toLowerCase().includes(searchTerm)) {
|
||||
if (searchTerm && !log.message.toLowerCase().includes(searchTerm) &&
|
||||
!(log.plugin && log.plugin.toLowerCase().includes(searchTerm))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -617,10 +718,45 @@ function escapeHtml(text) {
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function refreshCurrentPluginStatus() {
|
||||
fetch('/api/v3/display/current-status')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.status !== 'success' || !data.data) return;
|
||||
const state = data.data;
|
||||
const banner = document.getElementById('current-plugin-banner');
|
||||
const modeEl = document.getElementById('current-plugin-mode');
|
||||
const idWrap = document.getElementById('current-plugin-id-wrap');
|
||||
const idEl = document.getElementById('current-plugin-id');
|
||||
const filterBtn = document.getElementById('current-plugin-filter-btn');
|
||||
if (!banner || !modeEl) return;
|
||||
|
||||
window._currentPluginId = state.plugin_id || null;
|
||||
|
||||
modeEl.textContent = state.mode || 'unknown';
|
||||
if (state.plugin_id) {
|
||||
idEl.textContent = state.plugin_id;
|
||||
idWrap.classList.remove('hidden');
|
||||
if (filterBtn) filterBtn.classList.remove('hidden');
|
||||
} else {
|
||||
idWrap.classList.add('hidden');
|
||||
if (filterBtn) filterBtn.classList.add('hidden');
|
||||
}
|
||||
banner.classList.remove('hidden');
|
||||
})
|
||||
.catch(() => {
|
||||
// Silently ignore - banner just stays hidden/stale
|
||||
});
|
||||
}
|
||||
|
||||
// Cleanup on page unload
|
||||
window.addEventListener('beforeunload', function() {
|
||||
if (window._logsEventSource) {
|
||||
window._logsEventSource.close();
|
||||
}
|
||||
if (window._currentPluginPollTimer) {
|
||||
clearInterval(window._currentPluginPollTimer);
|
||||
window._currentPluginPollTimer = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user