mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-10 17:16:36 +00:00
* fix(sports): share the ESPN rejected-range memo with the background service BackgroundDataService always sent a season range first and, on a 400, fell back to chunks without recording the rejection, so every background season fetch spent a doomed request and live scoreboards learned nothing from it (or it from them). The worker now consults and sets the same 6-hour memo fetch_espn_scoreboard() uses: a known rejection goes straight to month/day chunks, and if every chunk fails the range is asked once for a real error without re-spending the chunks. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): keep plugin asset and action routes inside their directories POST /plugins/assets/upload, GET /plugins/assets/list and POST /plugins/assets/delete joined the request's plugin_id onto assets/plugins unchecked, so '../../config' created, wrote, listed and deleted outside it. #561 guarded only the route that serves the files. All three now go through path_safety.resolve_under and answer 400 for anything but a plain name, and delete only unlinks a metadata path that resolves into that plugin's uploads directory. PluginManager.get_plugin_directory refuses ids that are not one plain path segment, so /plugins/action (which runs a manifest script from the returned directory) and every other caller get the guard; the action route also rejects such ids up front, covering its no-manager fallback. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): report a no-op plugin update as already up to date update_plugin() returns True both for a real update and for "nothing to do" (a ZIP-installed monorepo plugin already at the registry version, a bundled plugin). With no git commit to compare, POST /plugins/update called every such success "updated successfully", so Check & Update All counted most official plugins as updated on every run. The route now reads what changed off the plugin itself (commit, else manifest version, else last_updated) and returns data.update_status (updated / up_to_date / local_only). The update-all toast is summarised by PluginInstallManager.summarizeUpdateResults from that status, falling back to the message for older servers. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(sports): scoreboard scroll speed no longer follows target_fps sports_scroll computed the crisp speed ladder against the global target_fps whenever limit_refresh_rate_hz was the 100 Hz default. Since frame-locked presentation (#545) the helper steps a fixed number of whole pixels per presented frame and the panel presents at its real refresh, so the General tab's "Scroll Frame Rate" became a speed multiplier: 60 ran a 50 px/s scoreboard at 100 px/s, 200 ran it at 25 px/s. The ladder now uses the display manager's refresh_hz, then display.hardware.limit_refresh_rate_hz, then the default. target_fps is not consulted. Docstrings now say scroll_delay is ignored for pacing (no behaviour change there) and describe the fixed-step model. Tests: replace the tests that pinned target_fps as the ladder refresh and described time-based stepping; assert speed independence from target_fps (unit and end-to-end presented px/s against the real helper), that the fixed per-frame step is applied, and that scroll_delay does not change speed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): escape registry and upload values in plugin manager inline handlers The store, saved-repository and custom-registry buttons built onclick='...(${JSON.stringify(id)})...'. JSON.stringify leaves ' alone, so a custom registry entry whose id contained ' closed the attribute and added its own handler. One helper, jsStringAttr(), now HTML-escapes the JSON literal for every one of those handlers, and the store View button opens only http(s) repo links. The live window.updateImageList (plugins_manager.js loads last, so its copy wins over the file-upload widget's) wrote the uploaded file's original name, path and ids into markup raw; they are escaped now. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): note plugin asset, action and inline handler guards Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): let the root pip wrapper install web_interface/requirements.txt Update Code, the automatic update's health check and Install Base Requirements install web_interface/requirements.txt through safe_pip_install.sh, which only allowed the root requirements.txt. The first commit changing that file would fail its dependency install, and the automatic updater rolls back any update whose dependencies did not install -- on every device, for every newer commit. The wrapper now lists both core requirement files. Only their folders are resolved, so a requirements.txt symlinked out of the project is compared by its target and refused (previously the root file's own symlink target was what got allowed). The updater's file list is a named constant, and a test runs the real wrapper (pip stubbed) on every file Update Code and the rollback install. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): do not retry plugin requests that got an HTTP answer PluginAPI.request wrapped everything that was not a structured error as NETWORK_ERROR: a proxy's 502 HTML page (response.json() throws) and a JSON error without error_code included. Check & Update All retries NETWORK_ERROR, so those updates were re-sent five more times with backoff, contrary to the #587 contract that an HTTP error response is the server's answer. NETWORK_ERROR now means only that fetch() rejected. Any HTTP response without an error_code, or with a body that is not JSON, is API_ERROR with the HTTP status attached. Tested against the shipped api_client.js. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scroll): restart the stats window when an idle gap is dropped by size #582 dropped an idle gap from the frame stats two ways: the reset_scroll() sentinel, which also restarts the 5s window timer, and a size guard for scrollers that never call reset_scroll(), which did not. On that path the first real frame after the gap found the boundary overdue and logged a stats line for a one-frame window. Both paths now share one seeding helper. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): leave plugins alone when update_core's own rollback fails update_core returns rollback_failed directly when a partial pull or an update whose health check never started cannot be rolled back. run() only held plugins back for 'verifying', so those devices still got new plugin versions and a display restart on top of a core in an unknown state -- the opposite of what the health-check path does, and of the 3.4.0 changelog (plugins are left alone if the rollback fails). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(api): make the REST reference match the api_v3 package Every documented request body, query parameter and response shape was re-checked against the handlers in web_interface/blueprints/api_v3/. Fixes calls that failed as documented (repo_url, action_id/params, files/image_id, font_file+font_family, ?font=, cache key, auto_enable_ap_mode, plugin limit keys), removes the font-override endpoints dropped in #566, corrects response shapes (plugins/config, plugins/schema, health, metrics, operation history, github-status, fonts/catalog, cache/list, logs, wifi, on-demand, SSE streams), and adds the 26 routes it omitted (backup, system auto-update/git, wifi radio, starlark editor, MQTT bridge, status endpoints, skins). Documents the merge semantics of partial JSON saves to /config/main and /plugins/config and the dim-schedule POST accepting GET's days shape, which land in the same change set. Replaces app.py line numbers and the removed api_v3.py path with file and function names. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): remove the General-tab plugin system toggles that did nothing plugin_system.auto_discover, auto_load_enabled and development_mode had General-tab toggles whose help tips promised dormant plugins and verbose logging, but nothing reads them: every enabled plugin is discovered and loaded regardless. Remove the three toggles. The keys stay tolerated in stored configs. The save handler now stores a flag only when a client sends it; treating a missing key as an unchecked box would otherwise rewrite all three to false on every General-tab save, which still posts plugins_directory. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(scroll): remove dead code left by #523/#570 - Drop the optional scipy.ndimage import and HAS_SCIPY; nothing read them since the numpy blend replaced the scipy path. - Drop ScrollHelper._last_integer_position and frame_time_target, which were written but never read. - Keep target_fps and set_target_fps() but document them as informational: nothing paces off them, yet ledmatrix-elections' test_scroll_pacing.py reads helper.target_fps back and third-party plugins may call the setter. - Fix stale comments: fixed_pixels_per_frame's "use scroll_delay to throttle", set_sub_pixel_scrolling's "default: True", and set_frame_based_scrolling's claim that it steps. The plugins monorepo was grepped for every removed name; none is used. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(fonts): point plugins at plugin_manager.font_manager; drop removed overrides UI FONT_MANAGER.md told plugins to read display_manager.font_manager, which does not exist, so a plugin following it failed to load with AttributeError. The shared FontManager lives on the PluginManager and BasePlugin._get_font_manager() returns it (with a fallback for harnesses). Also removes the Fonts-tab override workflow and element-override panels that #566 deleted, from FONT_MANAGER.md and WEB_INTERFACE_GUIDE.md. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(store): search via /plugins/store/list?query=; send Content-Type on registry curls /plugins/store/search does not exist (404) and the list endpoint reads query, not q. The registry guide's curl examples omitted the JSON Content-Type, so the handlers saw an empty body and answered 400. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(config): use the shared core-key list in the last three private copies StartupValidator warned "Plugin 'auto_update' is enabled but not found" on every display start with auto-update or a dim schedule on; the reserved plugin-id check missed auto_update, sync, location and the rest; and ConfigManager's (uncalled) orphan cleanup would have deleted display, schedule and auto_update. All three now read src/core_config_keys.py, which also gains CORE_SECRETS_KEYS for the github/youtube secrets sections. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): partial JSON saves to /config/main change only what they send A JSON body with one field reset every checkbox in the sections it touched: the MQTT bridge's brightness slider turned off disable_hardware_pulsing, inverse_colors, show_refresh_rate and use_short_date_format, and a timezone-only save turned off web-UI autostart and weekly auto-updates. Missing-means-unchecked now applies only to form posts: form-encoded bodies and the v3 forms, which mark themselves with a hidden __form_section input. Also on the config routes: - vegas_min/max_cycle_duration no longer match the generic *_duration rule, so they stop landing in display_durations and a blank one no longer rejects the whole Display save; - saving from the Raw JSON editor calls start_setup_if_needed like the General form, so enabling auto-update there finishes its setup; - the schedule and dim-schedule POSTs accept the per-day days.<day> shape their GETs return, as well as the flat form keys. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): install plugin dependencies from the configured plugins directory install_plugin_dependencies.sh scanned only plugins/, but the Plugin Store installs into plugin_system.plugins_directory (default plugin-repos), so the documented "Recommended" fix found 0 plugins on every store install. It now reads plugins_directory from config/config.json (relative to the project root or absolute, default plugin-repos) and also scans plugins/ for dev symlinks, installing a plugin reached through both only once. With set -e alone, `pip ... | tee` took tee's exit status, so a failed pip install was reported as success; set -o pipefail. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs: replace stale API names, line numbers and the api_v3.py path - ADVANCED_FEATURES: StreamManager methods that exist (get_next_segment, take_next_group, refresh, advance_cycle, ...), and the real on-demand status envelope ({status, data: {state, service}}) - app.py:199 / :144 / :607-619 line citations and web_interface/blueprints/api_v3.py (now a package) replaced with file and function names in ADVANCED_FEATURES, CONFIG_DEBUGGING, PLUGIN_ARCHITECTURE_SPEC, PLUGIN_QUICK_REFERENCE, PLUGIN_CONFIGURATION_TABS, TROUBLESHOOTING and web_interface/README - CONFIG_DEBUGGING: partial /config/main saves change only sent keys; use /config/raw/main to replace the file; describe where validation runs - TROUBLESHOOTING: clear_cache.py needs --clear-all (no args only prints usage) Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): verify the web interface that actually ships, on port 5000 verify_installation.sh failed every healthy install: it required the long-removed web_interface_v2.py and looked for a listener on port 5001, while the web interface binds 5000 (web_interface/start.py). It now checks the files ledmatrix-web.service runs (start_web_conditionally.py, web_interface/start.py, app.py) and port 5000. verify_web_ui.sh had the same 5001 port in its listen check, HTTP probe and printed URLs. Port matches are anchored so :50001 no longer counts as :5000. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(plugins): one display-size contract: display_manager.width/height CLAUDE.md (#580) says to read display_manager.width/height because matrix is None when hardware init fails; the development guide, the safety-harness doc and two DisplayManager docstrings still recommended matrix.width/height. The bundled starlark-apps plugin read matrix.width unguarded, so its magnify recommendation and frame scaling raised in fallback mode (e.g. after the Pi 5 hardware refusal). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(install): make install_service.sh --help print usage instead of installing install_service.sh parsed no arguments, so `sudo ./scripts/install/ install_service.sh --help` (presented as harmless in MIGRATION_GUIDE.md) rewrote ledmatrix.service, ledmatrix-web.service and both update-verify units and enabled/started them. It now handles -h/--help (usage, exit 0, no changes) and rejects any other argument with exit 2 before doing anything. Running it with no arguments, as first_time_install.sh does, is unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(scroll): describe the fixed-step model and document frame_hold Since #545 a crisp speed from scroll_config.configure() makes the helper advance a fixed whole-pixel step per presented frame with no clock, and the display manager's frame hold is part of the speed. The docs still described the removed wall-clock model: - scroll_config's module and configure() docstrings said speed is applied in time-based mode and that omitting the hold "falls back to fractional pixels"; omitting it actually runs the scroll frame_hold times too fast. - SCROLL_PERFORMANCE.md said ScrollHelper accumulates elapsed time in both modes, and read a 20 ms stats median as missed refreshes although that is a healthy 50 px/s (hold 2) scroll. It now explains the fixed step, the hold-dependent healthy median, that target_fps plays no part, and that a hand-added scroll_pixels_per_second loses to a schema-default pair. - PLUGIN_API_REFERENCE.md documented set_scrolling_state(is_scrolling) without frame_hold; it now documents the parameter (core 3.4.0) with a configure() + set_scrolling_state example. - update_scroll_position/set_scroll_speed and set_scrolling_state docstrings say the same. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(config): mark target_fps legacy; describe what Vegas scroll_delay does - General tab "Scroll Frame Rate" (target_fps) is labelled legacy: after the sports_scroll fix nothing in core scrolling reads it. The field and its API validation stay so saved configs and plugins that read global_config['target_fps'] keep working. CONFIG_REFERENCE says the same. - Vegas frame_based_scrolling/scroll_delay were described as frame-count stepping at ~50 FPS. Neither steps nor sets a frame rate: frame-based mode converts the speed to px per scroll_delay, clamps it to 0.1-5, and still advances by elapsed time, so the applied speed is clamp(scroll_speed * scroll_delay, 0.1, 5) / scroll_delay px/s. The config comments, render_pipeline comment and CONFIG_REFERENCE rows now say so. No behaviour change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(deps): describe how plugin dependencies are really installed The guides said the web service runs as root, that installs pick --user from os.geteuid(), and quoted a warning and a PluginManager._install_plugin_dependencies() method that don't exist. The web unit runs as the installing user; store installs go through install_requirements_file() and sudo safe_pip_install.sh (root), with a user-level fallback that says so, and load-time installs run in the display service's own (root) interpreter. Manual paths now use the configured plugins directory (plugin-repos/ by default) instead of plugins/, which store installs no longer use, and install_plugin_dependencies.sh is described as scanning that directory. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): count local changes one way for the preflight and the pull The automatic update's preflight ignored mode-only changes and anything whose status line contained plugins/ or plugin-repos/, then promised "Automatic updates will not stash your changes". perform_core_update used plain git status (modes count) and ignored only 'plugins/', then ran 'git stash push -- :!plugins', which nothing ever pops. So an edit to a bundled plugin under plugin-repos/, or the installer's chmods on tracked scripts, passed the preflight and was stashed away for good. - auto_update.local_changes() is the one predicate both use: core.fileMode=false, porcelain -z, and plugins/ and plugin-repos/ excluded by leading folder rather than substring (a core file under web_interface/static/v3/js/plugins/ now counts). - Update Code's explicit stash leaves out both plugin folders; the pull's --autostash carries their edits and mode changes across and reapplies them. - The automatic updater calls perform_core_update(stash_local_changes= False), which refuses instead of stashing edits that appeared after the preflight; update_core reports that as 'blocked'. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): diagnostics follow the web autostart default and api_v3 package #556 made a missing web_display_autostart mean "start" (only an explicit false/off keeps the web interface down), but the diagnostics still said otherwise: diagnose_web_ui.sh reported a missing key as "defaults to false", diagnose_web_interface.sh said the web interface "will not start unless this is set to true" and recommended enabling it, and debug_web_manual.py printed False. Troubleshooting a down web UI pointed users at a non-cause. Both shell scripts now evaluate the setting with the launcher's own autostart_enabled() (inline fallback if it cannot be imported) and report on / off / not set (on) / unparseable config; debug_web_manual.py uses the same function. They also check web_interface/blueprints/api_v3/ __init__.py: api_v3.py became a package in #553, so every healthy checkout was reported as missing a file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(install): what install_service.sh installs; verify script port; no sudo for --help install_service.sh installs and starts ledmatrix, ledmatrix-web and the update-verify units, not only ledmatrix.service (systemd/README.md, README.md). MIGRATION_GUIDE presented 'sudo install_service.sh --help' as a harmless check; it now shows --help without sudo and warns what a real run does. SSH_UNAVAILABLE_AFTER_INSTALL: verify_installation.sh checks the web interface on port 5000. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): note update-all, plugin system settings and script fixes Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(display): size the preview after orientation and pixel mappers display_geometry.physical_size claimed to give DisplayManager's answer but only computed cols*chain x rows*parallel. RGBMatrix.width/height are measured after the library's pixel mappers, so a Rotate:90 / orientation 90 chain previewed 128x32 for a 32x128 panel and a U-mapper chain of four 256x32 for 128x64. Model the built-in mappers' size effect as the pinned lib/pixel-mapper.cc does (Rotate, U-mapper, V-mapper, StackToRow, Remap; Mirror and unknown names leave it alone), and move the orientation composition here so DisplayManager and the preview share it. The module docstring no longer claims the sync handshake uses it; that imports only DEFAULT_CHAIN_LENGTH. Audit finding F18. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(display): refuse settings the rgbmatrix library aborts on, on every board The library answers several settings with a NULL matrix or abort() rather than an error, so the display service crash-looped (Restart=on-failure) instead of reaching fallback mode: rows above 64, chain_length above 255 (uint8_t binding setter, documented as "no upper limit"), a misspelled hardware_mapping, and parallel 2-3 on a single-output mapping, reachable from the Display form on the default adafruit-hat(-pwm) mapping. #586 only guarded the Pi 5 subset. - src/matrix_support.py holds the rules for every board (Options::Validate ranges, binding integer types, mapping names and outputs from lib/hardware-mapping.c) plus the Pi 5 ones, and is the one source of the API's numeric ranges. - DisplayManager checks them before building options and raises MatrixSettingsRefused, so a hand-edited config falls back with a logged, reported reason. Emulator mode only warns. - The config API refuses them with a 400 naming the setting; combinations are checked against stored values but reported only when the request sets a field involved. - The hardware status file gains "cause" (settings/library/forced). The fallback log and Display banner give the Pi 5 rebuild hint only for a library failure instead of rebuild + gpio_slowdown advice for every failure; one Pi 5 slowdown recommendation (1-3, start at 1). - The Display form offers classic/classic-pi1 and orientation 90/270 and renders any other stored mapping selected with a warning, so an unrelated save no longer rewrites them; the API accepts 90/270. Audit findings F03, F16, F19, F21. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(display): library limits, template defaults and Pi 5 slowdown - rows 8-64, chain_length 1-255, parallel limited by the mapping's outputs, classic/classic-pi1 mappings and orientation 90/270 documented. - Defaults are the config.template.json values: config migration adds missing keys from the template, so the listed "code defaults" never applied. - One Raspberry Pi 5 gpio_slowdown recommendation: 1-3 in PIO mode, starting at 1. - Troubleshooting describes the refused-settings fallback, and CHANGELOG corrects the Unreleased "no upper limit" entry. Audit findings F19, F20, F21. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): scroll_speeds.py opens the panel with the service's options --measure and --demo built RGBMatrixOptions from a private copy of the display service's builder that had drifted: gpio_slowdown came from display.hardware (default 2) instead of display.runtime (default 3), and rp1_rio, panel_type, disable_hardware_pulsing, inverse_colors, pixel_mapper_config and orientation were skipped, with different defaults (hardware_mapping "regular", pwm_bits 11). A panel needing a high slowdown was measured -- or garbled -- in a setup the service never drives. The option filling in DisplayManager._setup_matrix moves, unchanged, into DisplayManager.apply_matrix_options(options, config), which _setup_matrix calls and the script reuses (overriding only limit_refresh_rate_hz for --measure). The script now loads the whole config rather than the hardware block. Tests pin the script's options to the service's attribute for attribute. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): scroll_speeds.py recommends keys the resolver honours The ladder ended by telling users to set display_options.scroll_pixels_per_second. scroll_config ranks that key below the scroll_speed + scroll_delay pair, deliberately, and several plugin schemas default the pair into config, so the advised key was silently ignored (a schema-default 1/0.02 pair plus an advised 66 still resolved to 50 px/s). The advice is now the pair that selects the crisp speed exactly (pixels_per_frame every frame_hold/refresh seconds), explains that the pair outranks scroll_pixels_per_second, and gives the scoreboards' per-league scroll_settings.scroll_speed (px/s) form. Tests resolve the printed pair over a schema-default pair and check it lands on the advertised speed and hold. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs: withdraw the target_fps claim for sports_scroll; fix the Vegas speed formula - SPORTS_UNIFICATION.md still presented honouring global target_fps as sports_scroll's added behaviour and its one user-visible gain; note that it was withdrawn because it had become a speed multiplier. - ADVANCED_FEATURES.md gave Vegas scrolling as (scroll_speed / target_fps) * elapsed; the real rule is scroll_speed px/s by elapsed time, through a 0.1-5 px per scroll_delay clamp when frame_based_scrolling is on. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): scroll model fixes Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): link-github links plugins from the ledmatrix-plugins monorepo link-github <name> cloned https://github.com/ChuckBuilds/ledmatrix-<name>.git, and those per-plugin repositories no longer exist: official plugins are directories in the ledmatrix-plugins monorepo. It now clones (or pulls) the monorepo once into the dev directory, finds plugins/<name>, plugins/ledmatrix-<name> or the plugin whose manifest id is <name>, and links it under its manifest id. With an explicit repo URL it still links a single-repository plugin as before. dev_plugins.json: github_user is honoured again (monorepo owner, e.g. a fork), plus plugins_repo and plugins_branch; github_pattern, which was documented but never read, is dropped and warned about. Ships dev_plugins.json.example and git-ignores dev_plugins.json, both of which the guide promised. Reading JSON falls back to python3 when jq is missing (get_plugin_id silently returned nothing without jq). update/status/list find the git checkout above a monorepo plugin directory (its .git is not in the plugin dir), and update pulls a shared checkout once. status no longer exits 1 when nothing is broken. Docs: PLUGIN_DEVELOPMENT_GUIDE (quick start, link-github, configuration, workflow, store integration, hello-world link, submission), and the nonexistent scripts/git-hooks/pre-push-plugin-version and scripts/bump_plugin_version.py replaced with the real rule: bump the manifest version and run update_registry.py. scripts/dev/README.md and CLAUDE.md updated to match. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(scripts): monorepo workspace layout; fix_perms and install READMEs MULTI_ROOT_WORKSPACE_SETUP described one sibling repository per plugin; setup_plugin_repos.py links ../ledmatrix-plugins/plugins/* into plugin-repos/ and update_plugin_repos.py pulls only the monorepo, and the workspace file opens LEDMatrix plus ../ledmatrix-plugins. scripts/fix_perms/README.md listed cache directories fix_cache_permissions.sh never touches and a 'ledmatrix' service user that doesn't exist (also in scripts/install/README.md); adds safe_pip_install.sh. install/README: install_service.sh installs the web and update-verify units too. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): keep the rollback's pip retries inside the unit time limit The health check reinstalled the previous requirements by trying the next bash path after any failure, including a 600 s pip timeout. Two files, two paths: up to 40 minutes of pip alone, while systemd stops ledmatrix-update-verify.service at TimeoutStartSec=30min -- killing the rollback half-way and leaving the update 'verifying' until the web UI calls it lost. - Like permission_utils.install_requirements_file, only a sudo refusal moves on to the next bash; a pip that ran and failed or timed out is not repeated. The refusal wording is one list (permission_utils.SUDO_REFUSAL_PHRASES), mirrored in the stdlib-only verifier and pinned equal by a test. - All reinstalls in one rollback share a 600 s budget. - WORST_CASE_SECONDS adds up every timeout on the longest path (27.5 min); a test holds it under the unit's TimeoutStartSec and that under the web UI's VERIFY_LOST_SECONDS. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(plugins): prepare plugin configs one way for load, saves, GET, hot reload and dev tools Plugin config was prepared differently depending on how it arrived: - JSON POST /plugins/config built a partial body on schema defaults, so {"enabled": true} reset every other setting of the plugin. It now merges onto the stored section first, as the form path already did. - Legacy-boolean normalization (#588) ran only at load: GET /plugins/config returned the raw boolean, posting it back failed validation, and hot reload handed plugins the raw section (a legacy dynamic_duration: true came back as a boolean). schema_manager.prepare_plugin_config (normalize, then defaults) is now used by PluginManager.load_plugin, both save paths, GET, the save notifications and DisplayController's hot-reload callback. - The JSON save's filter kept only enabled/display_duration/live_priority and dropped a submitted skin, skin_options or vegas_* tuning key. There is now one core-owned per-plugin list, schema_manager.CORE_PLUGIN_PROPERTIES, used by validation and by the save filter; PluginManager's CORE_OWNED_CONFIG_KEYS is its vegas subset. - Plugin sections posted to /config/main were stored verbatim, including values /plugins/config rejects. They now go through the same preparation (_prepare_plugin_config_for_save, extracted from save_plugin_config), and a failing section rejects the whole save before anything is written. - dev_server read only top-level defaults and let a schema enabled:false win; build_full_config shallow-merged overrides, dropping sibling defaults; the harness extracted defaults differently from the device. loading.build_config now uses the device's extraction and preparation, and dev_server, check_plugin, render_plugin and the harness all use it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(mqtt-bridge): brightness changes apply live and touch nothing else The display service's hot reload applies a saved brightness within a few seconds, and /config/main no longer resets other display settings on a brightness-only JSON body. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): automatic update hardening Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(config): rewrite PLUGIN_CONFIG_ARCHITECTURE for the v3 web UI It described web_interface_v2.py and index_v2.html (both gone), client-side form generation, one POST per field with {key, value}, and 'no nested objects'. The v3 UI renders plugin forms server-side from the schema (pages_v3 partial + plugin_config.html macros, nested sections and x-widgets), posts the whole form once, and save_plugin_config() merges onto the stored section, validates, splits x-secret fields and notifies the plugin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(mqtt): brightness saves apply via hot reload and leave other settings alone The bridge README said brightness is applied on the display's next restart; the display controller's config hot reload applies it within seconds. It also now states that the bridge's partial JSON save changes only brightness (the /config/main merge fix in this change set). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): don't log pip's output from the health check's reinstall pip can echo a private index URL with embedded credentials; permission_utils redacts it, the stdlib-only verifier cannot, so it logs the exit code only. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(config): mark the plugin_system toggles as unused legacy keys auto_discover, auto_load_enabled and development_mode are read by nothing and leave the General tab in this change set (F40). CONFIG_REFERENCE said they were read by the plugin loader; PLUGIN_CONFIGURATION_GUIDE and the REST reference listed them as live settings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): docs and developer tools group Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): legacy plugin-system toggles no longer count as a General save auto_discover, auto_load_enabled and development_mode have left the General form, so a post carrying only one of them is not a general-settings save and must not treat web_display_autostart and auto_update as unchecked. The plugin_system block itself is left as on main for the branch that reworks it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): config-save and plugin-config preparation fixes Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(claude): re-check matrix_support.py rules when the library submodule is bumped Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: address Codacy findings on the core audit PR - plugin_manager.prepare_plugin_config: when the fallback legacy-boolean pass also fails, log a warning instead of a bare except/pass. - api_client.js: request() refuses any endpoint that is not a plain path under /api/v3 ("//host", backslashes, ".." or "." segments, whitespace, control characters) with INVALID_ENDPOINT before calling fetch(), and plugin ids are URL-encoded wherever they are put into a URL (also in the app-shell batch load). - test_update_all.js: pins both against the shipped client. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): check endpoint control characters without a control-character regex Codacy (ESLint no-control-regex, Biome noControlCharactersInRegex) flags the \x00-\x1f range in checkEndpoint's regex. Test the char codes instead; the endpoints refused are unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(auto-update): make the seed script executable on disk, not only in the index On Linux Repo.publish() commits with -a, which recorded scripts/run.sh as 100644 upstream because the seed file was never chmod +x. The pull then brought in the same mode the installer chmod had made locally, so installer_chmod saw no mode change left to check. The updater was fine: with the upstream commit at 100755 the --autostash carries the device's chmod across. Verified under Linux (WSL, git 2.43): the old helper fails exactly as CI did, the fixed one passes all 63 tests in the file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
536 lines
23 KiB
Python
536 lines
23 KiB
Python
"""Shared scroll-display scaffolding for the sports scoreboards.
|
|
|
|
Ten plugins ship a `scroll_display.py`. A method-level comparison of the eight
|
|
that share a shape (f1 and ufc are genuine forks) found a sharp split, and this
|
|
module is drawn along it rather than around all of it:
|
|
|
|
* The **orchestration layer is converged** — ``get_all_vegas_content_items`` is
|
|
byte-identical in all eight, and ``clear_all``, ``get_scroll_info``,
|
|
``get_dynamic_duration``, ``is_complete`` and ``display_frame`` are 96-100%
|
|
similar. That is what lives here.
|
|
* The **content layer has genuinely diverged** — ``prepare_scroll_content`` has
|
|
eight distinct bodies across eight plugins (145 lines, 53% similarity at
|
|
worst) and ``_load_separator_icons`` seven (6% at worst). Those build each
|
|
sport's game cards and icon strip; they are *not* drift to be merged but
|
|
per-sport rendering. They stay override points here, permanently.
|
|
|
|
Promoting the content layer would be exactly the mistake
|
|
``docs/SPORTS_UNIFICATION.md`` warns against — merging on the intuition that
|
|
same-named methods are the same method. Same name, different job.
|
|
|
|
What this module adds over the plugin copies is pacing through
|
|
:mod:`src.common.scroll_config`, the resolver every other scroller uses: the
|
|
configured px/s is snapped to a whole-pixel speed for the panel's refresh, the
|
|
helper steps a fixed number of pixels per presented frame, and each drawn frame
|
|
publishes the frame hold to the display manager. Speed depends only on
|
|
``scroll_speed`` and the panel refresh
|
|
(``display.hardware.limit_refresh_rate_hz``) -- not on the global
|
|
``target_fps``, and not on ``scroll_delay``, which is kept in the settings for
|
|
compatibility only.
|
|
|
|
Usage::
|
|
|
|
class HockeyScrollDisplay(SportsScrollDisplay):
|
|
SCROLL_LEAGUE_KEYS = ("nhl", "ncaa_mens", "ncaam_hockey")
|
|
|
|
def prepare_scroll_content(self, games, game_type, leagues, rankings=None):
|
|
... # build this sport's cards
|
|
|
|
class HockeyScrollDisplayManager(SportsScrollDisplayManager):
|
|
display_class = HockeyScrollDisplay
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import time
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
from PIL import Image
|
|
|
|
from src.common import scroll_config
|
|
from src.common.scroll_helper import ScrollHelper
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
#: Defaults every copy agreed on. A subclass overrides
|
|
#: :meth:`SportsScrollDisplay.scroll_settings_defaults` to change them —
|
|
#: the soccer lineage uses a 24px gap and min/max duration keys instead.
|
|
DEFAULT_SCROLL_SETTINGS: Dict[str, Any] = {
|
|
"scroll_speed": 50.0,
|
|
"scroll_delay": 0.01,
|
|
"gap_between_games": 48,
|
|
"show_league_separators": True,
|
|
"dynamic_duration": True,
|
|
}
|
|
|
|
#: Pacing to assume when scroll_delay is 0, i.e. the plugin has not set one.
|
|
#: Only used to interpret this module's own px/frame config shape; the speed
|
|
#: bounds and the px/s -> px/frame conversion belong to scroll_config now.
|
|
ASSUMED_FPS_WHEN_UNPACED = 100.0
|
|
|
|
|
|
class SportsScrollDisplay:
|
|
"""One scrolling strip of game cards.
|
|
|
|
Subclasses supply the content (:meth:`prepare_scroll_content`) and,
|
|
optionally, the per-sport league ladder and separator icons. Everything
|
|
else — helper configuration, frame pumping, completion, state — is here.
|
|
"""
|
|
|
|
#: Config keys to walk when looking for per-league ``scroll_settings``,
|
|
#: most-preferred first. A sport's own league names, which is the *only*
|
|
#: reason the eight copies of ``_get_scroll_settings`` differ. Empty means
|
|
#: the plugin has no per-league scroll settings.
|
|
SCROLL_LEAGUE_KEYS: tuple = ()
|
|
|
|
#: Config block holding scroll settings when the plugin keeps them in one
|
|
#: place rather than per league (the afl/nrl/soccer shape).
|
|
SCROLL_CONFIG_KEY: Optional[str] = None
|
|
|
|
def __init__(
|
|
self,
|
|
display_manager,
|
|
config: Dict[str, Any],
|
|
custom_logger: Optional[logging.Logger] = None,
|
|
global_config: Optional[Dict[str, Any]] = None,
|
|
):
|
|
"""
|
|
:param display_manager: the core display manager
|
|
:param config: the plugin's configuration
|
|
:param custom_logger: the plugin's logger, so scroll lines are attributed
|
|
:param global_config: the LEDMatrix global config, consulted for the
|
|
panel refresh when the display manager cannot report one.
|
|
Optional so an older caller that does not pass it keeps working.
|
|
"""
|
|
self.display_manager = display_manager
|
|
self.config = config
|
|
self.logger = custom_logger or logger
|
|
self.global_config = global_config or {}
|
|
|
|
if getattr(display_manager, "matrix", None) is not None:
|
|
self.display_width = display_manager.matrix.width
|
|
self.display_height = display_manager.matrix.height
|
|
else:
|
|
self.display_width = getattr(display_manager, "width", 128)
|
|
self.display_height = getattr(display_manager, "height", 32)
|
|
|
|
self.scroll_helper = ScrollHelper(
|
|
self.display_width, self.display_height, self.logger
|
|
)
|
|
self._configure_scroll_helper()
|
|
|
|
self._logo_cache: Dict[str, Image.Image] = {}
|
|
self._separator_icons: Dict[str, Image.Image] = {}
|
|
self._load_separator_icons()
|
|
|
|
self._current_games: List[Dict] = []
|
|
self._current_game_type: str = ""
|
|
self._current_leagues: List[str] = []
|
|
self._vegas_content_items: List[Image.Image] = []
|
|
self._is_scrolling = False
|
|
self._scroll_start_time: Optional[float] = None
|
|
self._last_log_time: float = 0
|
|
self._log_interval: float = 5.0
|
|
self._frame_count: int = 0
|
|
self._fps_sample_start: float = time.time()
|
|
|
|
# ------------------------------------------------------------------
|
|
# Override points
|
|
# ------------------------------------------------------------------
|
|
|
|
def prepare_scroll_content(
|
|
self,
|
|
games: List[Dict],
|
|
game_type: str,
|
|
leagues: List[str],
|
|
rankings_cache: Optional[Dict[str, int]] = None,
|
|
) -> bool:
|
|
"""Render ``games`` into one wide image and hand it to the scroll helper.
|
|
|
|
**Per-sport by nature, not by drift** — the eight plugin copies have
|
|
eight different bodies because each draws its own card. Implementations
|
|
build the strip, hand it over with
|
|
``self.scroll_helper.set_scrolling_image(...)`` (or
|
|
``create_scrolling_image(...)`` from a list of cards), and record
|
|
``self._current_games`` / ``_current_game_type`` / ``_current_leagues``.
|
|
|
|
:returns: True when there is content to scroll.
|
|
"""
|
|
raise NotImplementedError(
|
|
f"{type(self).__name__} must implement prepare_scroll_content(); "
|
|
"it builds this sport's game cards and is not shared code."
|
|
)
|
|
|
|
def _load_separator_icons(self) -> None:
|
|
"""Populate ``self._separator_icons``. Per-sport; no-op by default."""
|
|
|
|
def scroll_settings_defaults(self) -> Dict[str, Any]:
|
|
"""The baseline scroll settings before any config is applied."""
|
|
defaults = dict(DEFAULT_SCROLL_SETTINGS)
|
|
defaults["game_card_width"] = self.display_width
|
|
return defaults
|
|
|
|
# ------------------------------------------------------------------
|
|
# Settings
|
|
# ------------------------------------------------------------------
|
|
|
|
def _get_scroll_settings(self, league: Optional[str] = None) -> Dict[str, Any]:
|
|
"""Resolve scroll settings: defaults, then the most specific override.
|
|
|
|
Precedence: the named ``league``, then each entry of
|
|
:attr:`SCROLL_LEAGUE_KEYS` in order, then :attr:`SCROLL_CONFIG_KEY`.
|
|
The eight plugin copies implement exactly this and differ only in which
|
|
league names they walk — which is why the ladder is data here rather
|
|
than a body per sport.
|
|
"""
|
|
settings = self.scroll_settings_defaults()
|
|
|
|
candidates: List[str] = []
|
|
if league:
|
|
candidates.append(league)
|
|
candidates.extend(self.SCROLL_LEAGUE_KEYS)
|
|
for key in candidates:
|
|
override = (self.config.get(key) or {}).get("scroll_settings")
|
|
if override:
|
|
return {**settings, **override}
|
|
|
|
if self.SCROLL_CONFIG_KEY:
|
|
override = self.config.get(self.SCROLL_CONFIG_KEY) or {}
|
|
if override:
|
|
return {**settings, **override}
|
|
return settings
|
|
|
|
def _coerce_float(self, value: Any, default: float) -> float:
|
|
"""A usable float from config, or ``default``.
|
|
|
|
``dict.get(key, default)`` only helps when the key is *absent*; a key
|
|
present with ``null`` or a string returns that value verbatim and blows
|
|
up in the arithmetic below — inside ``__init__``, so the whole display
|
|
fails to construct.
|
|
"""
|
|
if value is None:
|
|
return default
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
self.logger.warning(
|
|
"Ignoring unusable scroll setting %r; using %s", value, default
|
|
)
|
|
return default
|
|
|
|
def _configure_scroll_helper(self) -> None:
|
|
"""Apply config to the scroll helper. Safe to call again after a change."""
|
|
settings = self._get_scroll_settings()
|
|
|
|
dynamic_duration = bool(settings.get("dynamic_duration", True))
|
|
self.scroll_helper.set_dynamic_duration_settings(
|
|
enabled=dynamic_duration,
|
|
min_duration=settings.get("min_duration", 30),
|
|
max_duration=settings.get("max_duration", 600),
|
|
buffer=0.2, # ensure the strip clears the panel completely
|
|
)
|
|
|
|
# Speed goes through scroll_config, which every other scrolling plugin
|
|
# already uses. What must NOT happen is handing it this module's
|
|
# settings dict: the two read the same key names with different
|
|
# meanings, and the collision is a factor of 1/scroll_delay.
|
|
#
|
|
# sports_scroll: scroll_speed is px/SECOND; scroll_delay is ignored
|
|
# for pacing (see _resolve_pixels_per_second).
|
|
# scroll_config: scroll_speed is px per STEP, so px/s = speed/delay.
|
|
#
|
|
# Passing {"scroll_speed": 50.0, "scroll_delay": 0.01} straight through
|
|
# resolves to 5000 px/s (clamped to 500) instead of 50. So this module
|
|
# keeps ownership of reading its own config -- _get_scroll_settings
|
|
# merges the league overrides -- and hands the resolver a plain px/s.
|
|
pixels_per_second = self._resolve_pixels_per_second(settings)
|
|
|
|
resolved = scroll_config.configure(
|
|
self.scroll_helper,
|
|
plugin_config=None,
|
|
global_config=self.global_config,
|
|
default_pixels_per_second=pixels_per_second,
|
|
display_manager=self.display_manager,
|
|
plugin_logger=self.logger,
|
|
refresh_hz=self._resolve_refresh_hz(),
|
|
)
|
|
self._scroll_settings = resolved
|
|
self.logger.info(
|
|
"ScrollHelper configured: %s (requested %.1f px/s), "
|
|
"dynamic_duration=%s",
|
|
resolved.describe(),
|
|
pixels_per_second, dynamic_duration,
|
|
)
|
|
|
|
def _resolve_pixels_per_second(self, settings: Dict[str, Any]) -> float:
|
|
"""This module's config shape, expressed as plain pixels per second.
|
|
|
|
``scroll_speed`` is already px/s here, and it is the whole answer.
|
|
``scroll_delay`` is kept in the settings for compatibility but is
|
|
ignored for pacing: the frame rate is the panel refresh divided by the
|
|
frame hold scroll_config picks, so no positive delay changes the speed.
|
|
The one exception is a delay of exactly 0 (below every scoreboard
|
|
schema's minimum), which is read as ``scroll_speed`` being px per
|
|
frame at ``ASSUMED_FPS_WHEN_UNPACED``.
|
|
"""
|
|
scroll_speed = self._coerce_float(settings.get("scroll_speed"), 50.0)
|
|
scroll_delay = self._coerce_float(settings.get("scroll_delay"), 0.01)
|
|
if scroll_delay <= 0:
|
|
return scroll_speed * ASSUMED_FPS_WHEN_UNPACED
|
|
return scroll_speed
|
|
|
|
def _resolve_refresh_hz(self) -> float:
|
|
"""The panel refresh the crisp ladder should be computed against.
|
|
|
|
This has to be the rate frames are actually presented at, because the
|
|
helper advances a fixed number of whole pixels per presented frame and
|
|
the display manager holds each frame for ``frame_hold`` refreshes. A
|
|
ladder built for any other rate plays back at the wrong speed: built
|
|
for 60 Hz and shown on a 100 Hz panel, it runs 100/60 too fast.
|
|
|
|
So it is the display manager's ``refresh_hz`` (what the panel is
|
|
driven at), then ``display.hardware.limit_refresh_rate_hz`` from the
|
|
global config, then scroll_config's default. The global ``target_fps``
|
|
is deliberately NOT consulted: before frame-locked presentation it was
|
|
the rate frames were shown at, but now honouring it only turned the
|
|
General tab's "Scroll Frame Rate" into a scoreboard speed multiplier.
|
|
"""
|
|
reported = getattr(self.display_manager, "refresh_hz", None)
|
|
# A real number only: a stub or a mock answering for anything must not
|
|
# become the refresh rate.
|
|
if (isinstance(reported, (int, float)) and not isinstance(reported, bool)
|
|
and reported > 0):
|
|
return float(reported)
|
|
return scroll_config.refresh_hz_from_config(self.global_config)
|
|
|
|
def _scroll_frame_hold(self) -> int:
|
|
"""Refreshes to hold each frame for, from the resolved settings."""
|
|
return getattr(getattr(self, "_scroll_settings", None), "frame_hold", 1)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Frame pumping
|
|
# ------------------------------------------------------------------
|
|
|
|
def display_scroll_frame(self) -> bool:
|
|
"""Advance and render one frame.
|
|
|
|
:returns: True if a frame was drawn; False when there is no content or
|
|
the frame could not be rendered.
|
|
"""
|
|
if not self.scroll_helper.cached_image:
|
|
return False
|
|
|
|
try:
|
|
# Inside the try, not before it: advancing the position and cropping
|
|
# the visible slice are as capable of raising as the display push,
|
|
# and the promise below is that no frame failure reaches the
|
|
# plugin's loop.
|
|
self.scroll_helper.update_scroll_position()
|
|
visible = self.scroll_helper.get_visible_portion()
|
|
if not visible:
|
|
return False
|
|
|
|
# Tell the core the panel is scrolling, and for how many
|
|
# refreshes to hold each frame. The helper advances a fixed number
|
|
# of whole pixels per presented frame, so without the hold a new
|
|
# frame is presented every refresh and the scroll runs frame_hold
|
|
# times too fast. And because deferred updates only run while
|
|
# nothing is scrolling, core would otherwise run blocking work in
|
|
# the middle of this scroll.
|
|
if hasattr(self.display_manager, "set_scrolling_state"):
|
|
self.display_manager.set_scrolling_state(
|
|
True, frame_hold=self._scroll_frame_hold())
|
|
|
|
self.display_manager.image = visible
|
|
self.display_manager.update_display()
|
|
self._frame_count += 1
|
|
self.scroll_helper.log_frame_rate()
|
|
self._log_scroll_progress()
|
|
except Exception:
|
|
# A display failure must not propagate into the plugin's loop.
|
|
self.logger.exception("Error displaying scroll frame")
|
|
return False
|
|
return True
|
|
|
|
def _log_scroll_progress(self) -> None:
|
|
"""Emit a throttled progress line."""
|
|
now = time.time()
|
|
if now - self._last_log_time < self._log_interval:
|
|
return
|
|
self._last_log_time = now
|
|
elapsed = now - self._fps_sample_start
|
|
fps = self._frame_count / elapsed if elapsed > 0 else 0.0
|
|
self.logger.debug(
|
|
f"Scrolling {len(self._current_games)} {self._current_game_type} "
|
|
f"game(s) at {fps:.1f} FPS"
|
|
)
|
|
|
|
def is_scroll_complete(self) -> bool:
|
|
"""True when the strip has scrolled fully past the panel."""
|
|
complete = self.scroll_helper.is_scroll_complete()
|
|
if complete:
|
|
self._release_scrolling_state()
|
|
return complete
|
|
|
|
def _release_scrolling_state(self) -> None:
|
|
"""Tell the core this display is no longer scrolling.
|
|
|
|
The scrolling flag and the frame hold are global to the display
|
|
manager, so leaving them set holds every other plugin's frames too.
|
|
"""
|
|
if hasattr(self.display_manager, "set_scrolling_state"):
|
|
self.display_manager.set_scrolling_state(False)
|
|
|
|
def reset_scroll(self) -> None:
|
|
"""Return the strip to its starting position, keeping the content."""
|
|
self.scroll_helper.reset_scroll()
|
|
self._frame_count = 0
|
|
self._fps_sample_start = time.time()
|
|
self.logger.debug("Scroll position reset")
|
|
|
|
def clear(self) -> None:
|
|
"""Drop cached content and reset tracking state."""
|
|
self.scroll_helper.clear_cache()
|
|
self._current_games = []
|
|
self._current_game_type = ""
|
|
self._current_leagues = []
|
|
self._vegas_content_items = []
|
|
self._is_scrolling = False
|
|
self._scroll_start_time = None
|
|
self._release_scrolling_state()
|
|
self.logger.debug("Scroll display cleared")
|
|
|
|
# ------------------------------------------------------------------
|
|
# Introspection
|
|
# ------------------------------------------------------------------
|
|
|
|
def get_dynamic_duration(self) -> int:
|
|
"""How long this content needs to scroll fully, in seconds."""
|
|
return self.scroll_helper.get_dynamic_duration()
|
|
|
|
def has_cached_content(self) -> bool:
|
|
"""Whether content is prepared and ready to scroll."""
|
|
return bool(self.scroll_helper.cached_image)
|
|
|
|
def get_current_game_count(self) -> int:
|
|
return len(self._current_games)
|
|
|
|
def get_current_leagues(self) -> List[str]:
|
|
return list(self._current_leagues)
|
|
|
|
def get_scroll_info(self) -> Dict[str, Any]:
|
|
"""Helper state plus this display's tracking state, for logging/debug."""
|
|
info = self.scroll_helper.get_scroll_info()
|
|
info.update(
|
|
{
|
|
"game_count": len(self._current_games),
|
|
"game_type": self._current_game_type,
|
|
"leagues": self._current_leagues,
|
|
"is_scrolling": self._is_scrolling,
|
|
}
|
|
)
|
|
return info
|
|
|
|
|
|
class SportsScrollDisplayManager:
|
|
"""One :class:`SportsScrollDisplay` per game type ('live'/'recent'/'upcoming').
|
|
|
|
Subclasses set :attr:`display_class`; everything else was near-identical
|
|
across the eight plugin copies.
|
|
"""
|
|
|
|
#: The SportsScrollDisplay subclass to instantiate per game type.
|
|
display_class = SportsScrollDisplay
|
|
|
|
def __init__(
|
|
self,
|
|
display_manager,
|
|
config: Dict[str, Any],
|
|
custom_logger: Optional[logging.Logger] = None,
|
|
global_config: Optional[Dict[str, Any]] = None,
|
|
):
|
|
self.display_manager = display_manager
|
|
self.config = config
|
|
self.logger = custom_logger or logger
|
|
self.global_config = global_config or {}
|
|
self._scroll_displays: Dict[str, SportsScrollDisplay] = {}
|
|
# "" rather than None, matching SportsScrollDisplay's own empty value —
|
|
# both are falsy, so `game_type or self._current_game_type` behaved
|
|
# either way, but two spellings of "nothing active" across two classes
|
|
# is a trap for anyone comparing state between them.
|
|
self._current_game_type: str = ""
|
|
|
|
def get_scroll_display(self, game_type: str) -> SportsScrollDisplay:
|
|
"""The display for ``game_type``, created on first use."""
|
|
if game_type not in self._scroll_displays:
|
|
self._scroll_displays[game_type] = self.display_class(
|
|
self.display_manager,
|
|
self.config,
|
|
self.logger,
|
|
global_config=self.global_config,
|
|
)
|
|
return self._scroll_displays[game_type]
|
|
|
|
def prepare_and_display(
|
|
self,
|
|
games: List[Dict],
|
|
game_type: str,
|
|
leagues: List[str],
|
|
rankings_cache: Optional[Dict[str, int]] = None,
|
|
) -> bool:
|
|
"""Build content for ``game_type`` and make it the active strip."""
|
|
scroll_display = self.get_scroll_display(game_type)
|
|
try:
|
|
success = scroll_display.prepare_scroll_content(
|
|
games, game_type, leagues, rankings_cache
|
|
)
|
|
except Exception:
|
|
# prepare_scroll_content is subclass-implemented and builds cards
|
|
# straight from feed data, which is exactly where this PR's other
|
|
# crashes came from. One sport's bad payload must not take down the
|
|
# shared orchestration for the others.
|
|
self.logger.exception(
|
|
"Error preparing scroll content for game_type=%s", game_type
|
|
)
|
|
return False
|
|
if success:
|
|
self._current_game_type = game_type
|
|
return success
|
|
|
|
def display_frame(self, game_type: Optional[str] = None) -> bool:
|
|
"""Advance the active strip (or a named one) by one frame."""
|
|
game_type = game_type or self._current_game_type
|
|
if not game_type:
|
|
return False
|
|
scroll_display = self._scroll_displays.get(game_type)
|
|
if scroll_display is None:
|
|
return False
|
|
return scroll_display.display_scroll_frame()
|
|
|
|
def is_complete(self, game_type: Optional[str] = None) -> bool:
|
|
"""True when the strip has finished — including when there isn't one,
|
|
so a caller waiting on completion is never wedged."""
|
|
game_type = game_type or self._current_game_type
|
|
if not game_type:
|
|
return True
|
|
scroll_display = self._scroll_displays.get(game_type)
|
|
if scroll_display is None:
|
|
return True
|
|
return scroll_display.is_scroll_complete()
|
|
|
|
def clear_all(self) -> None:
|
|
"""Clear every display and forget which one was active."""
|
|
for scroll_display in self._scroll_displays.values():
|
|
scroll_display.clear()
|
|
self._current_game_type = ""
|
|
|
|
def get_all_vegas_content_items(self) -> List[Image.Image]:
|
|
"""Every display's Vegas items, for splicing into the marquee."""
|
|
items: List[Image.Image] = []
|
|
for scroll_display in self._scroll_displays.values():
|
|
vegas_items = getattr(scroll_display, "_vegas_content_items", None)
|
|
if vegas_items:
|
|
items.extend(vegas_items)
|
|
return items
|